@swapkit/wallet-hardware 4.8.1 → 4.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +2 -2
  2. package/src/index.ts +1 -0
  3. package/src/keepkey/chains/cosmos.ts +69 -0
  4. package/src/keepkey/chains/evm.ts +141 -0
  5. package/src/keepkey/chains/mayachain.ts +98 -0
  6. package/src/keepkey/chains/ripple.ts +88 -0
  7. package/src/keepkey/chains/thorchain.ts +93 -0
  8. package/src/keepkey/chains/utxo.ts +364 -0
  9. package/src/keepkey/coins.ts +67 -0
  10. package/src/keepkey/index.ts +174 -0
  11. package/src/ledger/clients/cosmos.ts +84 -0
  12. package/src/ledger/clients/evm.ts +186 -0
  13. package/src/ledger/clients/near.ts +63 -0
  14. package/src/ledger/clients/sui.ts +130 -0
  15. package/src/ledger/clients/thorchain/common.ts +93 -0
  16. package/src/ledger/clients/thorchain/helpers.ts +120 -0
  17. package/src/ledger/clients/thorchain/index.ts +87 -0
  18. package/src/ledger/clients/thorchain/lib.ts +258 -0
  19. package/src/ledger/clients/thorchain/utils.ts +69 -0
  20. package/src/ledger/clients/tron.ts +85 -0
  21. package/src/ledger/clients/utxo-legacy-adapter.ts +71 -0
  22. package/src/ledger/clients/utxo-psbt.ts +145 -0
  23. package/src/ledger/clients/utxo.ts +359 -0
  24. package/src/ledger/clients/xrp.ts +50 -0
  25. package/src/ledger/cosmosTypes.ts +98 -0
  26. package/src/ledger/helpers/getLedgerAddress.ts +76 -0
  27. package/src/ledger/helpers/getLedgerClient.ts +124 -0
  28. package/src/ledger/helpers/getLedgerTransport.ts +102 -0
  29. package/src/ledger/helpers/index.ts +3 -0
  30. package/src/ledger/index.ts +546 -0
  31. package/src/ledger/interfaces/CosmosLedgerInterface.ts +54 -0
  32. package/src/ledger/types.ts +42 -0
  33. package/src/trezor/evmSigner.ts +210 -0
  34. package/src/trezor/index.ts +847 -0
@@ -0,0 +1,847 @@
1
+ import {
2
+ Chain,
3
+ type DerivationPathArray,
4
+ derivationPathToString,
5
+ FeeOption,
6
+ filterSupportedChains,
7
+ type GenericTransferParams,
8
+ SKConfig,
9
+ SwapKitError,
10
+ type UTXOChain,
11
+ WalletOption,
12
+ } from "@swapkit/helpers";
13
+ import {
14
+ assertDerivationIndex,
15
+ createHDWalletHelpers,
16
+ getNetworkForChain,
17
+ getUTXOAccountIndexFromPath,
18
+ getUTXOAccountPath,
19
+ getUtxoApi,
20
+ type UTXOToolboxes,
21
+ type UTXOType,
22
+ } from "@swapkit/toolboxes/utxo";
23
+ import type { BTCNetwork, PCZT, Transaction, ZcashTransaction } from "@swapkit/utxo-signer";
24
+ import { NETWORKS, ZcashConsensusBranchId, ZcashVersionGroupId } from "@swapkit/utxo-signer";
25
+ import { createWallet, getWalletSupportedChains } from "@swapkit/wallet-core";
26
+
27
+ function decodeOpReturnData(script: Uint8Array): string | null {
28
+ if (script.length < 2 || script[0] !== 0x6a) return null;
29
+ const dataLen = script[1];
30
+ if (dataLen === undefined || script.length < 2 + dataLen) return null;
31
+ return Buffer.from(script.slice(2, 2 + dataLen)).toString("hex");
32
+ }
33
+
34
+ function getScriptType(derivationPath: DerivationPathArray) {
35
+ switch (derivationPath[0]) {
36
+ case 84:
37
+ return { input: "SPENDWITNESS", output: "PAYTOWITNESS" } as const;
38
+ case 49:
39
+ return { input: "SPENDP2SHWITNESS", output: "PAYTOP2SHWITNESS" } as const;
40
+ case 44:
41
+ return { input: "SPENDADDRESS", output: "PAYTOADDRESS" } as const;
42
+ default:
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function hardenDerivationPath(derivationPath: DerivationPathArray): number[] {
48
+ return derivationPath.map((pathElement, index) =>
49
+ index < 3 ? ((pathElement as number) | 0x80000000) >>> 0 : (pathElement as number),
50
+ );
51
+ }
52
+
53
+ function buildPCZTInputsForTrezor(
54
+ pczt: PCZT,
55
+ address_n: number[],
56
+ hexEncode: { encode: (data: Uint8Array) => string },
57
+ ) {
58
+ const inputs = [];
59
+ for (let i = 0; i < pczt.inputsLength; i++) {
60
+ const input = pczt.getInput(i);
61
+ inputs.push({
62
+ address_n,
63
+ amount: input.value.toString(),
64
+ prev_hash: hexEncode.encode(new Uint8Array([...input.txid].reverse())),
65
+ prev_index: input.index,
66
+ script_type: "SPENDADDRESS" as const,
67
+ });
68
+ }
69
+ return inputs;
70
+ }
71
+
72
+ async function buildPCZTOutputsForTrezor(pczt: PCZT, address_n: number[], myAddress: string, chain: Chain) {
73
+ const outputs = [];
74
+ for (let i = 0; i < pczt.outputsLength; i++) {
75
+ const output = pczt.getOutput(i);
76
+ const script = output.scriptPubkey;
77
+
78
+ if (output.value === 0n && script?.length > 0 && script[0] === 0x6a) {
79
+ const opReturnData = decodeOpReturnData(script);
80
+ if (opReturnData) {
81
+ outputs.push({ amount: "0", op_return_data: opReturnData, script_type: "PAYTOOPRETURN" as const });
82
+ continue;
83
+ }
84
+ throw new SwapKitError({
85
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
86
+ info: { chain, error: "Malformed OP_RETURN output cannot be signed" },
87
+ });
88
+ }
89
+
90
+ const outputAddress = await decodeOutputAddress(script);
91
+
92
+ if (!outputAddress && output.value > 0n) {
93
+ throw new SwapKitError({
94
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
95
+ info: { chain, error: "Unable to decode output address from scriptPubkey" },
96
+ });
97
+ }
98
+
99
+ const isChangeAddress = outputAddress === myAddress;
100
+
101
+ if (isChangeAddress) {
102
+ outputs.push({ address_n, amount: output.value.toString(), script_type: "PAYTOADDRESS" as const });
103
+ } else {
104
+ outputs.push({ address: outputAddress, amount: output.value.toString(), script_type: "PAYTOADDRESS" as const });
105
+ }
106
+ }
107
+ return outputs;
108
+ }
109
+
110
+ async function decodeOutputAddress(script: Uint8Array): Promise<string | undefined> {
111
+ try {
112
+ const { OutScript, Address } = await import("@swapkit/utxo-signer");
113
+ const decoded = OutScript.decode(script);
114
+ if (decoded.type === "pkh" || decoded.type === "pk") {
115
+ return Address(NETWORKS.zcash).encode(decoded);
116
+ }
117
+ } catch {
118
+ // ignore decode errors
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ async function extractSignaturesFromSignedTx(signedTxHex: string, pczt: PCZT): Promise<PCZT> {
124
+ const { ZcashTransaction: ZcashTx, Script } = await import("@swapkit/utxo-signer");
125
+ const signedTx = ZcashTx.fromHex(signedTxHex, { allowUnknownOutputs: true });
126
+ const signedPczt = pczt.clone();
127
+
128
+ for (let i = 0; i < signedTx.inputsLength; i++) {
129
+ const signedInput = signedTx.getInput(i);
130
+ const script = signedInput.script;
131
+ if (script && script.length > 0) {
132
+ const scriptParts = Script.decode(script);
133
+ if (scriptParts.length >= 2) {
134
+ signedPczt.addSignature(i, scriptParts[1] as Uint8Array, scriptParts[0] as Uint8Array);
135
+ }
136
+ }
137
+ }
138
+ return signedPczt;
139
+ }
140
+
141
+ function buildZcashTxInputsForTrezor(
142
+ tx: ZcashTransaction,
143
+ utxoInputs: UTXOType[],
144
+ address_n: number[],
145
+ hexEncode: { encode: (data: Uint8Array) => string },
146
+ ) {
147
+ const inputs = [];
148
+ for (let i = 0; i < tx.inputsLength; i++) {
149
+ const input = tx.getInput(i);
150
+ const utxoInfo = utxoInputs[i];
151
+ inputs.push({
152
+ address_n,
153
+ amount: utxoInfo?.value?.toString() || "0",
154
+ prev_hash: input.txid ? hexEncode.encode(new Uint8Array([...input.txid].reverse())) : "",
155
+ prev_index: input.index ?? 0,
156
+ script_type: "SPENDADDRESS" as const,
157
+ });
158
+ }
159
+ return inputs;
160
+ }
161
+
162
+ function buildZcashTxOutputsForTrezor(tx: ZcashTransaction, address_n: number[], myAddress: string, chain: Chain) {
163
+ const outputs = [];
164
+ for (let i = 0; i < tx.outputsLength; i++) {
165
+ const output = tx.getOutput(i);
166
+ const outputAddress = tx.getOutputAddress(i, NETWORKS.zcash);
167
+ const script = output.script;
168
+
169
+ if (output.amount === 0n && script?.length > 0 && script[0] === 0x6a) {
170
+ const opReturnData = decodeOpReturnData(script);
171
+ if (opReturnData) {
172
+ outputs.push({ amount: "0", op_return_data: opReturnData, script_type: "PAYTOOPRETURN" as const });
173
+ continue;
174
+ }
175
+ continue;
176
+ }
177
+
178
+ if (!outputAddress && (output.amount ?? 0n) > 0n) {
179
+ throw new SwapKitError({
180
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
181
+ info: { chain, error: "Unable to decode output address" },
182
+ });
183
+ }
184
+
185
+ const isChangeAddress = outputAddress === myAddress;
186
+ const outputParam = isChangeAddress || !outputAddress ? { address_n } : { address: outputAddress };
187
+ outputs.push({ ...outputParam, amount: output.amount?.toString() || "0", script_type: "PAYTOADDRESS" as const });
188
+ }
189
+ return outputs;
190
+ }
191
+
192
+ function buildUtxoOutputsForTrezor(
193
+ tx: Transaction,
194
+ network: BTCNetwork,
195
+ address_n: number[],
196
+ myAddress: string,
197
+ memo: string,
198
+ chain: Chain,
199
+ scriptType: { input: string; output: string },
200
+ toCashAddress: (addr: string) => string,
201
+ stripPrefix: (addr: string) => string,
202
+ ) {
203
+ const outputs: any[] = [];
204
+ for (let i = 0; i < tx.outputsLength; i++) {
205
+ const output = tx.getOutput(i);
206
+ const outputAddress = tx.getOutputAddress(i, network);
207
+
208
+ if (!outputAddress) {
209
+ outputs.push({ amount: "0", op_return_data: Buffer.from(memo).toString("hex"), script_type: "PAYTOOPRETURN" });
210
+ continue;
211
+ }
212
+
213
+ const finalAddress = chain === Chain.BitcoinCash ? stripPrefix(toCashAddress(outputAddress)) : outputAddress;
214
+ const isChangeAddress = finalAddress === myAddress;
215
+
216
+ outputs.push(
217
+ isChangeAddress
218
+ ? { address_n, amount: Number(output.amount), script_type: scriptType.output }
219
+ : { address: finalAddress, amount: Number(output.amount), script_type: "PAYTOADDRESS" },
220
+ );
221
+ }
222
+ return outputs;
223
+ }
224
+
225
+ async function getTrezorWallet<T extends Chain>({
226
+ chain,
227
+ derivationPath,
228
+ }: {
229
+ chain: T;
230
+ derivationPath: DerivationPathArray;
231
+ }) {
232
+ switch (chain) {
233
+ case Chain.Arbitrum:
234
+ case Chain.Aurora:
235
+ case Chain.Avalanche:
236
+ case Chain.Base:
237
+ case Chain.Berachain:
238
+ case Chain.BinanceSmartChain:
239
+ case Chain.Ethereum:
240
+ case Chain.Gnosis:
241
+ case Chain.Monad:
242
+ case Chain.Optimism:
243
+ case Chain.Polygon:
244
+ case Chain.XLayer: {
245
+ const { getProvider, getEvmToolboxAsync } = await import("@swapkit/toolboxes/evm");
246
+ const { getEVMSigner } = await import("./evmSigner");
247
+
248
+ const provider = await getProvider(chain);
249
+ const signer = await getEVMSigner({ chain, derivationPath, provider });
250
+ const address = await signer.getAddress();
251
+ const toolbox = await getEvmToolboxAsync(chain, { provider, signer });
252
+
253
+ return { ...toolbox, address };
254
+ }
255
+
256
+ case Chain.Zcash: {
257
+ const { getUtxoToolbox } = await import("@swapkit/toolboxes/utxo");
258
+
259
+ const derivationPathStr = derivationPathToString(derivationPath);
260
+
261
+ const getAddress = async () => {
262
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
263
+ const { success, payload } = await TrezorConnect.getAddress({ coin: "zcash", path: derivationPathStr });
264
+
265
+ if (!success) {
266
+ throw new SwapKitError({
267
+ errorKey: "wallet_trezor_failed_to_get_address",
268
+ info: { chain, error: (payload as { error: string; code?: string }).error || "Unknown error" },
269
+ });
270
+ }
271
+
272
+ return payload.address;
273
+ };
274
+
275
+ const address = await getAddress();
276
+
277
+ const signer = {
278
+ getAddress: async () => address,
279
+
280
+ signPCZT: async (pczt: PCZT): Promise<PCZT> => {
281
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
282
+ const { hex: hexEncode } = await import("@scure/base");
283
+ const address_n = hardenDerivationPath(derivationPath);
284
+ const global = pczt.getGlobal();
285
+
286
+ const inputs = buildPCZTInputsForTrezor(pczt, address_n, hexEncode);
287
+ const outputs = await buildPCZTOutputsForTrezor(pczt, address_n, address, chain);
288
+
289
+ const result = await TrezorConnect.signTransaction({
290
+ branchId: global.consensusBranchId,
291
+ coin: "zcash",
292
+ expiry: global.expiryHeight,
293
+ inputs,
294
+ locktime: global.lockTime,
295
+ outputs: outputs as any,
296
+ overwintered: true,
297
+ version: global.txVersion,
298
+ versionGroupId: global.versionGroupId,
299
+ });
300
+
301
+ if (!result.success) {
302
+ throw new SwapKitError({
303
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
304
+ info: { chain, error: (result.payload as { error: string; code?: string }).error },
305
+ });
306
+ }
307
+
308
+ return extractSignaturesFromSignedTx(result.payload.serializedTx, pczt);
309
+ },
310
+
311
+ signTransaction: async (tx: ZcashTransaction, utxoInputs: UTXOType[]) => {
312
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
313
+ const { hex: hexEncode } = await import("@scure/base");
314
+ const address_n = hardenDerivationPath(derivationPath);
315
+
316
+ const inputs = buildZcashTxInputsForTrezor(tx, utxoInputs, address_n, hexEncode);
317
+ const outputs = buildZcashTxOutputsForTrezor(tx, address_n, address, chain);
318
+
319
+ const result = await TrezorConnect.signTransaction({
320
+ branchId: ZcashConsensusBranchId.NU6,
321
+ coin: "zcash",
322
+ expiry: 0,
323
+ inputs,
324
+ locktime: 0,
325
+ outputs: outputs as any,
326
+ overwintered: true,
327
+ version: 4,
328
+ versionGroupId: ZcashVersionGroupId.SAPLING,
329
+ });
330
+
331
+ if (result.success) {
332
+ return result.payload.serializedTx;
333
+ }
334
+
335
+ throw new SwapKitError({
336
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
337
+ info: { chain, error: (result.payload as { error: string; code?: string }).error },
338
+ });
339
+ },
340
+ };
341
+
342
+ const toolbox = getUtxoToolbox(Chain.Zcash);
343
+
344
+ const transfer = async (params: GenericTransferParams) => {
345
+ if (!(address && params.recipient)) {
346
+ throw new SwapKitError({
347
+ errorKey: "wallet_missing_params",
348
+ info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },
349
+ });
350
+ }
351
+
352
+ const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];
353
+
354
+ const { tx, inputs: txInputs } = await toolbox.createTransaction({
355
+ ...params,
356
+ feeRate,
357
+ fetchTxHex: false,
358
+ sender: address,
359
+ });
360
+
361
+ const txHex = await signer.signTransaction(tx, txInputs);
362
+ const broadcastResult = await toolbox.broadcastTx(txHex);
363
+
364
+ return broadcastResult;
365
+ };
366
+
367
+ const transferWithPCZT = async (params: GenericTransferParams) => {
368
+ if (!(address && params.recipient)) {
369
+ throw new SwapKitError({
370
+ errorKey: "wallet_missing_params",
371
+ info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },
372
+ });
373
+ }
374
+
375
+ const { createPCZT, OutScript } = await import("@swapkit/utxo-signer");
376
+ const { hex: hexEncode } = await import("@scure/base");
377
+ const { getUtxoApi } = await import("@swapkit/toolboxes/utxo");
378
+
379
+ const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];
380
+
381
+ const utxos = await getUtxoApi(Chain.Zcash).getUtxos({ address });
382
+
383
+ const { tx, inputs: txInputs } = await toolbox.createTransaction({
384
+ ...params,
385
+ feeRate,
386
+ fetchTxHex: false,
387
+ sender: address,
388
+ });
389
+
390
+ const pczt = createPCZT();
391
+
392
+ for (const utxoInput of txInputs) {
393
+ const utxo = utxos.find((u) => u.hash === utxoInput.hash && u.index === utxoInput.index);
394
+ const scriptPubkey = utxo?.witnessUtxo?.script
395
+ ? new Uint8Array(utxo.witnessUtxo.script)
396
+ : OutScript.encode({ hash: hexEncode.decode((utxoInput as any).address || ""), type: "pkh" });
397
+
398
+ pczt.addInput({
399
+ index: utxoInput.index,
400
+ scriptPubkey,
401
+ txid: hexEncode.decode(utxoInput.hash).reverse() as unknown as Uint8Array,
402
+ value: BigInt(utxoInput.value),
403
+ });
404
+ }
405
+
406
+ for (let i = 0; i < tx.outputsLength; i++) {
407
+ const output = tx.getOutput(i);
408
+ pczt.addOutput({ scriptPubkey: output.script || new Uint8Array(), value: output.amount || 0n });
409
+ }
410
+
411
+ const signedPczt = await signer.signPCZT(pczt);
412
+ signedPczt.finalizeAllInputs();
413
+ const finalTx = signedPczt.extract();
414
+ const broadcastResult = await toolbox.broadcastTx(finalTx.toHex());
415
+
416
+ return broadcastResult;
417
+ };
418
+
419
+ return {
420
+ ...toolbox,
421
+ address,
422
+ signPCZT: signer.signPCZT,
423
+ signTransaction: signer.signTransaction,
424
+ transfer,
425
+ transferWithPCZT,
426
+ };
427
+ }
428
+
429
+ case Chain.Bitcoin:
430
+ case Chain.BitcoinCash:
431
+ case Chain.Dash:
432
+ case Chain.Dogecoin:
433
+ case Chain.Litecoin: {
434
+ const { toCashAddress, getUtxoToolbox } = await import("@swapkit/toolboxes/utxo");
435
+ const utxoChain = chain as UTXOChain;
436
+ const scriptType = getScriptType(derivationPath);
437
+
438
+ if (!scriptType) {
439
+ throw new SwapKitError({ errorKey: "wallet_trezor_derivation_path_not_supported", info: { derivationPath } });
440
+ }
441
+
442
+ const coin = chain.toLowerCase();
443
+
444
+ const getAddress = async (path: DerivationPathArray = derivationPath) => {
445
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
446
+ const { success, payload } = await TrezorConnect.getAddress({ coin, path: derivationPathToString(path) });
447
+
448
+ if (!success) {
449
+ throw new SwapKitError({
450
+ errorKey: "wallet_trezor_failed_to_get_address",
451
+ info: { chain, error: (payload as { error: string; code?: string }).error || "Unknown error" },
452
+ });
453
+ }
454
+
455
+ if (chain === Chain.BitcoinCash) {
456
+ const toolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);
457
+ return toolbox.stripPrefix(payload.address);
458
+ }
459
+
460
+ return payload.address;
461
+ };
462
+
463
+ const address = await getAddress();
464
+
465
+ const signTransaction = async (tx: Transaction, inputs: UTXOType[], memo = "") => {
466
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
467
+ const address_n = hardenDerivationPath(derivationPath);
468
+ const toolbox = getUtxoToolbox(chain as typeof Chain.BitcoinCash);
469
+ const network = getNetworkForChain(chain as UTXOChain);
470
+
471
+ const outputs = buildUtxoOutputsForTrezor(
472
+ tx,
473
+ network,
474
+ address_n,
475
+ address,
476
+ memo,
477
+ chain,
478
+ scriptType,
479
+ toCashAddress,
480
+ toolbox.stripPrefix,
481
+ );
482
+
483
+ const result = await TrezorConnect.signTransaction({
484
+ coin,
485
+ inputs: inputs.map(({ hash, index, value }) => ({
486
+ address_n,
487
+ amount: value,
488
+ prev_hash: hash,
489
+ prev_index: index,
490
+ script_type: scriptType.input,
491
+ })),
492
+ outputs,
493
+ });
494
+
495
+ if (result.success) {
496
+ return result.payload.serializedTx;
497
+ }
498
+
499
+ throw new SwapKitError({
500
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
501
+ info: { chain, error: (result.payload as { error: string; code?: string }).error },
502
+ });
503
+ };
504
+
505
+ const signTransactionWithMultipleInputs = async (
506
+ tx: Transaction,
507
+ inputs: Array<{ hash: string; index: number; value: number; derivationIndex: number; isChange: boolean }>,
508
+ memo = "",
509
+ ) => {
510
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
511
+ const toolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);
512
+ const network = getNetworkForChain(chain as UTXOChain);
513
+ const baseAddressN = hardenDerivationPath(derivationPath.slice(0, 3) as DerivationPathArray);
514
+
515
+ const outputs = buildUtxoOutputsForTrezor(
516
+ tx,
517
+ network,
518
+ baseAddressN,
519
+ address,
520
+ memo,
521
+ chain,
522
+ scriptType,
523
+ toCashAddress,
524
+ toolbox.stripPrefix,
525
+ );
526
+
527
+ const trezorInputs = inputs.map(({ hash, index: inputIndex, value, derivationIndex, isChange }) => {
528
+ const changePath = isChange ? 1 : 0;
529
+ const inputAddressN = [...baseAddressN, changePath, derivationIndex];
530
+ return {
531
+ address_n: inputAddressN,
532
+ amount: value,
533
+ prev_hash: hash,
534
+ prev_index: inputIndex,
535
+ script_type: scriptType.input,
536
+ };
537
+ });
538
+
539
+ const result = await TrezorConnect.signTransaction({ coin, inputs: trezorInputs, outputs });
540
+
541
+ if (result.success) {
542
+ return result.payload.serializedTx;
543
+ }
544
+
545
+ throw new SwapKitError({
546
+ errorKey: "wallet_trezor_failed_to_sign_transaction",
547
+ info: { chain, error: (result.payload as { error: string; code?: string }).error },
548
+ });
549
+ };
550
+
551
+ const transferFromMultipleAddresses = async ({
552
+ utxos,
553
+ recipient,
554
+ assetValue,
555
+ memo,
556
+ feeRate,
557
+ feeOptionKey,
558
+ }: {
559
+ utxos: Array<{
560
+ hash: string;
561
+ index: number;
562
+ value: number;
563
+ txHex?: string;
564
+ derivationIndex: number;
565
+ isChange: boolean;
566
+ address: string;
567
+ }>;
568
+ recipient: string;
569
+ assetValue: { getBaseValue: (unit: string) => number; chain: string };
570
+ memo?: string;
571
+ feeRate?: number;
572
+ feeOptionKey?: (typeof FeeOption)[keyof typeof FeeOption];
573
+ }) => {
574
+ const toolbox = getUtxoToolbox(chain);
575
+ const txFeeRate = feeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];
576
+
577
+ const { tx, inputs: selectedInputs } = await toolbox.createTransaction({
578
+ assetValue: assetValue as any,
579
+ feeRate: txFeeRate,
580
+ fetchTxHex: true,
581
+ memo,
582
+ recipient,
583
+ sender: address,
584
+ });
585
+
586
+ const inputsWithDerivation = selectedInputs.map((input: { hash: string; index: number; value: number }) => {
587
+ const utxoInfo = utxos.find((u) => u.hash === input.hash && u.index === input.index);
588
+ return { ...input, derivationIndex: utxoInfo?.derivationIndex ?? 0, isChange: utxoInfo?.isChange ?? false };
589
+ });
590
+
591
+ const signedTxHex = await signTransactionWithMultipleInputs(tx as Transaction, inputsWithDerivation, memo);
592
+ return toolbox.broadcastTx(signedTxHex);
593
+ };
594
+
595
+ const transfer = async ({
596
+ recipient,
597
+ feeOptionKey,
598
+ feeRate: paramFeeRate,
599
+ memo,
600
+ ...rest
601
+ }: GenericTransferParams) => {
602
+ if (!(address && recipient)) {
603
+ throw new SwapKitError({
604
+ errorKey: "wallet_missing_params",
605
+ info: { address, memo, recipient, wallet: WalletOption.TREZOR },
606
+ });
607
+ }
608
+
609
+ const toolbox = getUtxoToolbox(chain);
610
+
611
+ const feeRate = paramFeeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];
612
+
613
+ const createTxMethod = (toolbox as UTXOToolboxes["BTC"]).createTransaction;
614
+
615
+ const { tx, inputs } = await createTxMethod({
616
+ ...rest,
617
+ feeRate,
618
+ fetchTxHex: true,
619
+ memo,
620
+ recipient,
621
+ sender: address,
622
+ });
623
+
624
+ const signedTxHex = await signTransaction(tx, inputs, memo);
625
+ const txHash = await toolbox.broadcastTx(signedTxHex);
626
+
627
+ return txHash;
628
+ };
629
+
630
+ const toolbox = await getUtxoToolbox(chain);
631
+
632
+ async function getExtendedPublicKeyInfo({ accountIndex }: { accountIndex?: number } = {}) {
633
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
634
+ const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });
635
+ const path = derivationPathToString(resolvedAccountPath);
636
+ const { success, payload } = await TrezorConnect.getPublicKey({ coin, path });
637
+
638
+ if (!success) {
639
+ throw new SwapKitError({
640
+ errorKey: "wallet_trezor_failed_to_get_public_key",
641
+ info: { chain, error: (payload as { error: string; code?: string }).error || "Unknown error" },
642
+ });
643
+ }
644
+
645
+ return {
646
+ accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),
647
+ chainCode: payload.chainCode,
648
+ depth: payload.depth,
649
+ fingerprint: payload.fingerprint,
650
+ path: payload.serializedPath,
651
+ publicKey: payload.publicKey,
652
+ xpub: payload.xpub,
653
+ xpubSegwit: payload.xpubSegwit,
654
+ };
655
+ }
656
+
657
+ function getExtendedPublicKey() {
658
+ return getExtendedPublicKeyInfo();
659
+ }
660
+
661
+ async function deriveAddressAtIndex({
662
+ accountIndex,
663
+ index,
664
+ change = false,
665
+ }: {
666
+ accountIndex?: number;
667
+ index: number;
668
+ change?: boolean;
669
+ }) {
670
+ assertDerivationIndex("index", index);
671
+
672
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
673
+ const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });
674
+ const fullPath = `${derivationPathToString(resolvedAccountPath)}/${Number(change)}/${index}`;
675
+
676
+ const { success, payload } = await TrezorConnect.getAddress({ coin, path: fullPath, showOnTrezor: false });
677
+
678
+ if (!success) {
679
+ return undefined;
680
+ }
681
+
682
+ let finalAddress = payload.address;
683
+ if (chain === Chain.BitcoinCash) {
684
+ const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);
685
+ finalAddress = bchToolbox.stripPrefix(payload.address);
686
+ }
687
+
688
+ const pubKeyResult = await TrezorConnect.getPublicKey({ coin, path: fullPath });
689
+ const pubkey = pubKeyResult.success ? pubKeyResult.payload.publicKey : "";
690
+
691
+ return {
692
+ accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),
693
+ address: finalAddress,
694
+ change,
695
+ index,
696
+ path: fullPath,
697
+ pubkey,
698
+ };
699
+ }
700
+
701
+ async function deriveAddressesBatch({
702
+ accountIndex,
703
+ count,
704
+ startIndex = 0,
705
+ change = false,
706
+ }: {
707
+ accountIndex?: number;
708
+ count: number;
709
+ startIndex?: number;
710
+ change?: boolean;
711
+ }) {
712
+ assertDerivationIndex("count", count);
713
+ assertDerivationIndex("startIndex", startIndex);
714
+
715
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
716
+ const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });
717
+ const accountPath = derivationPathToString(resolvedAccountPath);
718
+
719
+ const paths = Array.from({ length: count }, (_, i) => ({
720
+ coin,
721
+ path: `${accountPath}/${Number(change)}/${startIndex + i}`,
722
+ showOnTrezor: false,
723
+ }));
724
+
725
+ const { success, payload } = await TrezorConnect.getAddress({ bundle: paths });
726
+
727
+ if (!success || !Array.isArray(payload)) {
728
+ return [];
729
+ }
730
+
731
+ const addresses = await Promise.all(
732
+ payload.map(async (result, i) => {
733
+ let finalAddress = result.address;
734
+ if (chain === Chain.BitcoinCash) {
735
+ const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);
736
+ finalAddress = bchToolbox.stripPrefix(result.address);
737
+ }
738
+
739
+ return {
740
+ accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),
741
+ address: finalAddress,
742
+ change,
743
+ index: startIndex + i,
744
+ path: `${accountPath}/${Number(change)}/${startIndex + i}`,
745
+ pubkey: "",
746
+ };
747
+ }),
748
+ );
749
+
750
+ return addresses;
751
+ }
752
+
753
+ const hdHelpers = createHDWalletHelpers({
754
+ chain,
755
+ deriveAddress: deriveAddressAtIndex,
756
+ getBalance: toolbox.getBalance,
757
+ getUtxos: (addr: string) => getUtxoApi(chain).getUtxos({ address: addr, fetchTxHex: true }),
758
+ });
759
+
760
+ return {
761
+ ...toolbox,
762
+ ...hdHelpers,
763
+ address,
764
+ deriveAddressAtIndex,
765
+ deriveAddresses: deriveAddressesBatch,
766
+ getExtendedPublicKey,
767
+ getExtendedPublicKeyInfo,
768
+ signTransaction,
769
+ signTransactionWithMultipleInputs,
770
+ transfer,
771
+ transferFromMultipleAddresses,
772
+ };
773
+ }
774
+
775
+ default:
776
+ throw new SwapKitError({ errorKey: "wallet_chain_not_supported", info: { chain, wallet: WalletOption.TREZOR } });
777
+ }
778
+ }
779
+
780
+ export const trezorWallet = createWallet({
781
+ connect: ({ addChain, supportedChains, walletType }) =>
782
+ async function connectTrezor(chains: Chain[], derivationPath: DerivationPathArray) {
783
+ const [chain] = filterSupportedChains({ chains, supportedChains, walletType });
784
+ if (!chain) {
785
+ throw new SwapKitError({
786
+ errorKey: "wallet_chain_not_supported",
787
+ info: { chain, wallet: WalletOption.TREZOR },
788
+ });
789
+ }
790
+
791
+ const TrezorConnect = (await import("@trezor/connect-web")).default;
792
+ const { success } = await TrezorConnect.getDeviceState();
793
+
794
+ if (!success) {
795
+ const trezorConfig = SKConfig.get("integrations").trezor;
796
+ const manifest = trezorConfig
797
+ ? { ...trezorConfig, appName: (trezorConfig as any).appName || "SwapKit" }
798
+ : { appName: "SwapKit", appUrl: "", email: "" };
799
+ TrezorConnect.init({ lazyLoad: true, manifest });
800
+ }
801
+
802
+ const wallet = await getTrezorWallet({ chain, derivationPath });
803
+
804
+ addChain({ ...wallet, chain, walletType });
805
+
806
+ return true;
807
+ },
808
+ directSigningSupport: {
809
+ [Chain.Arbitrum]: true,
810
+ [Chain.Aurora]: true,
811
+ [Chain.Avalanche]: true,
812
+ [Chain.Base]: true,
813
+ [Chain.Berachain]: true,
814
+ [Chain.BinanceSmartChain]: true,
815
+ [Chain.Ethereum]: true,
816
+ [Chain.Gnosis]: true,
817
+ [Chain.Monad]: true,
818
+ [Chain.Optimism]: true,
819
+ [Chain.Polygon]: true,
820
+ [Chain.XLayer]: true,
821
+ // BTC/BCH/DASH/DOGE/LTC/ZEC: pending PSBT→TrezorConnect converter (V3 plan PR)
822
+ },
823
+ name: "connectTrezor",
824
+ supportedChains: [
825
+ Chain.Arbitrum,
826
+ Chain.Aurora,
827
+ Chain.Avalanche,
828
+ Chain.Base,
829
+ Chain.Berachain,
830
+ Chain.BinanceSmartChain,
831
+ Chain.Bitcoin,
832
+ Chain.BitcoinCash,
833
+ Chain.Dash,
834
+ Chain.Dogecoin,
835
+ Chain.Ethereum,
836
+ Chain.Gnosis,
837
+ Chain.Litecoin,
838
+ Chain.Monad,
839
+ Chain.Optimism,
840
+ Chain.Polygon,
841
+ Chain.XLayer,
842
+ Chain.Zcash,
843
+ ],
844
+ walletType: WalletOption.TREZOR,
845
+ });
846
+
847
+ export const TREZOR_SUPPORTED_CHAINS = getWalletSupportedChains(trezorWallet);