@talken/talkenkit 2.7.5-beta.2 → 2.7.5-beta.3

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 (160) hide show
  1. package/dist/AbcCredentialManager-6FBGTSSM.js +7 -0
  2. package/dist/abcWallet-6BIO6Q6T.js +184 -0
  3. package/dist/chunk-PZ4TCLAJ.js +7816 -0
  4. package/dist/chunk-SUYKWM5G.js +451 -0
  5. package/dist/components/ConfirmationModal/NonEvmSignConfirmationModal.d.ts +1 -1
  6. package/dist/components/ConfirmationModal/NonEvmTransferConfirmationModal.d.ts +1 -1
  7. package/dist/components/ConfirmationModal/SignConfirmationModal.d.ts +1 -1
  8. package/dist/components/ConfirmationModal/TransactionConfirmationModal.d.ts +2 -1
  9. package/dist/components/ConfirmationModal/constants.d.ts +0 -4
  10. package/dist/components/RainbowKitProvider/RainbowKitProvider.d.ts +31 -1
  11. package/dist/components/TransactionResultModal/TransactionResultModal.css.d.ts +3 -0
  12. package/dist/components/TransactionResultModal/TransactionResultModal.d.ts +1 -1
  13. package/dist/config/networks.d.ts +2 -1
  14. package/dist/gasless/GaslessConfigSingleton.d.ts +11 -0
  15. package/dist/gasless/api/ChainConfigApi.d.ts +20 -0
  16. package/dist/gasless/api/RelayerApi.d.ts +25 -0
  17. package/dist/gasless/api/TokenCapabilityApi.d.ts +12 -0
  18. package/dist/gasless/config.d.ts +12 -0
  19. package/dist/gasless/hooks/useGaslessTransfer.d.ts +18 -0
  20. package/dist/gasless/index.d.ts +12 -0
  21. package/dist/gasless/services/Eip7702Service.d.ts +80 -0
  22. package/dist/gasless/services/GaslessFeeService.d.ts +55 -0
  23. package/dist/gasless/services/GaslessTransferService.d.ts +61 -0
  24. package/dist/gasless/services/PermitSignService.d.ts +28 -0
  25. package/dist/gasless/signer/AbcWaasSigner.d.ts +27 -0
  26. package/dist/gasless/signer/GaslessSigner.d.ts +43 -0
  27. package/dist/gasless/signer/WagmiSigner.d.ts +63 -0
  28. package/dist/gasless/signer/index.d.ts +4 -0
  29. package/dist/gasless/types.d.ts +298 -0
  30. package/dist/gasless/utils/delegationGuard.d.ts +50 -0
  31. package/dist/gasless/utils/feeTokenResolver.d.ts +35 -0
  32. package/dist/gasless/utils/revokeDelegation.d.ts +55 -0
  33. package/dist/gasless/utils/transferDetector.d.ts +20 -0
  34. package/dist/hooks/internal/abcEmbeddedWallet.d.ts +1 -1
  35. package/dist/hooks/useXrplWallet.d.ts +77 -0
  36. package/dist/index.css +41 -37
  37. package/dist/index.d.ts +7 -2
  38. package/dist/index.js +2282 -1448
  39. package/dist/providers/AbcAuthProvider.d.ts +2 -1
  40. package/dist/providers/SignConfirmationProvider/SignConfirmationProvider.d.ts +1 -1
  41. package/dist/providers/SignConfirmationProvider/index.d.ts +1 -1
  42. package/dist/providers/SignConfirmationProvider/types.d.ts +14 -1
  43. package/dist/providers/SignConfirmationProvider/useTransactionResolver.d.ts +2 -1
  44. package/dist/providers/TransactionResultProvider/types.d.ts +7 -1
  45. package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.d.ts +2 -0
  46. package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.js +3 -3
  47. package/dist/wallets/walletConnectors/abcWallet/AbcEvmAutoConnector.js +5 -5
  48. package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.d.ts +5 -0
  49. package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.js +3 -3
  50. package/dist/wallets/walletConnectors/abcWallet/ProviderError.d.ts +3 -0
  51. package/dist/wallets/walletConnectors/abcWallet/ProviderError.js +5 -3
  52. package/dist/wallets/walletConnectors/abcWallet/StorageService.js +2 -2
  53. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.js +8 -8
  54. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.js +7 -7
  55. package/dist/wallets/walletConnectors/abcWallet/abcConnector.js +22 -21
  56. package/dist/wallets/walletConnectors/abcWallet/abcProvider.d.ts +16 -0
  57. package/dist/wallets/walletConnectors/abcWallet/abcProvider.js +11 -11
  58. package/dist/wallets/walletConnectors/abcWallet/abcSolanaProvider.js +22 -21
  59. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.js +3 -3
  60. package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.js +7 -7
  61. package/dist/wallets/walletConnectors/abcWallet/abcWallet.js +23 -22
  62. package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.d.ts +99 -0
  63. package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.js +19 -0
  64. package/dist/wallets/walletConnectors/abcWallet/api/ConfigApi.js +2 -2
  65. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.d.ts +3 -0
  66. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.js +15 -14
  67. package/dist/wallets/walletConnectors/abcWallet/api/TokenApi.js +2 -2
  68. package/dist/wallets/walletConnectors/abcWallet/api/WalletscanApi.js +3 -3
  69. package/dist/wallets/walletConnectors/abcWallet/api/index.js +20 -19
  70. package/dist/wallets/walletConnectors/abcWallet/api/modules/auth.js +4 -4
  71. package/dist/wallets/walletConnectors/abcWallet/api/modules/bitcoin.js +5 -5
  72. package/dist/wallets/walletConnectors/abcWallet/api/modules/evm.js +4 -4
  73. package/dist/wallets/walletConnectors/abcWallet/api/modules/solana.js +2 -2
  74. package/dist/wallets/walletConnectors/abcWallet/api/modules/tron.js +2 -2
  75. package/dist/wallets/walletConnectors/abcWallet/api/modules/wallet.js +2 -2
  76. package/dist/wallets/walletConnectors/abcWallet/api/modules/walletscan.js +2 -2
  77. package/dist/wallets/walletConnectors/abcWallet/api/modules/xrp.d.ts +85 -0
  78. package/dist/wallets/walletConnectors/abcWallet/api/modules/xrp.js +8 -0
  79. package/dist/wallets/walletConnectors/abcWallet/constants.d.ts +9 -0
  80. package/dist/wallets/walletConnectors/abcWallet/constants.js +1 -1
  81. package/dist/wallets/walletConnectors/abcWallet/index.d.ts +5 -0
  82. package/dist/wallets/walletConnectors/abcWallet/index.js +71 -56
  83. package/dist/wallets/walletConnectors/abcWallet/networkConfig.d.ts +31 -3
  84. package/dist/wallets/walletConnectors/abcWallet/networkConfig.js +11 -3
  85. package/dist/wallets/walletConnectors/abcWallet/sessionUtils.js +3 -3
  86. package/dist/wallets/walletConnectors/abcWallet/types/api.types.d.ts +3 -1
  87. package/dist/wallets/walletConnectors/abcWallet/types/auth.types.d.ts +3 -1
  88. package/dist/wallets/walletConnectors/abcWallet/types/config.types.d.ts +1 -0
  89. package/dist/wallets/walletConnectors/abcWallet/types/config.types.js +1 -1
  90. package/dist/wallets/walletConnectors/abcWallet/types/wallet.types.d.ts +15 -1
  91. package/dist/wallets/walletConnectors/abcWallet/types.js +2 -2
  92. package/dist/wallets/walletConnectors/abcWallet/utils.js +5 -5
  93. package/dist/wallets/walletConnectors/abcWallet/walletGeneration.d.ts +2 -1
  94. package/dist/wallets/walletConnectors/abcWallet/walletGeneration.js +8 -8
  95. package/dist/wallets/walletConnectors/berasigWallet/berasigWallet.js +2 -2
  96. package/dist/wallets/walletConnectors/bifrostWallet/bifrostWallet.js +2 -2
  97. package/dist/wallets/walletConnectors/binanceWallet/binanceWallet.js +2 -2
  98. package/dist/wallets/walletConnectors/bitgetWallet/bitgetWallet.js +2 -2
  99. package/dist/wallets/walletConnectors/bybitWallet/bybitWallet.js +2 -2
  100. package/dist/wallets/walletConnectors/chunk-2LH53QET.js +71 -0
  101. package/dist/wallets/walletConnectors/chunk-2LOET2LX.js +64 -0
  102. package/dist/wallets/walletConnectors/chunk-2XNFYA54.js +492 -0
  103. package/dist/wallets/walletConnectors/chunk-326CQ42T.js +378 -0
  104. package/dist/wallets/walletConnectors/chunk-3NWM24MH.js +61 -0
  105. package/dist/wallets/walletConnectors/chunk-3Z5DO42M.js +240 -0
  106. package/dist/wallets/walletConnectors/chunk-4Y7YP4IR.js +115 -0
  107. package/dist/wallets/walletConnectors/chunk-AJ2YNYCD.js +277 -0
  108. package/dist/wallets/walletConnectors/chunk-BOHX6ZNO.js +3030 -0
  109. package/dist/wallets/walletConnectors/chunk-E4B4UELA.js +3030 -0
  110. package/dist/wallets/walletConnectors/chunk-F74FF7OS.js +370 -0
  111. package/dist/wallets/walletConnectors/chunk-FWX2HD26.js +30 -0
  112. package/dist/wallets/walletConnectors/chunk-ICGK5DGY.js +146 -0
  113. package/dist/wallets/walletConnectors/chunk-IGZOEVKN.js +58 -0
  114. package/dist/wallets/walletConnectors/chunk-IJJQA3AB.js +218 -0
  115. package/dist/wallets/walletConnectors/chunk-JU6AJBYS.js +20 -0
  116. package/dist/wallets/walletConnectors/chunk-KTVJLN3O.js +58 -0
  117. package/dist/wallets/walletConnectors/chunk-L3EPZ4NZ.js +52 -0
  118. package/dist/wallets/walletConnectors/chunk-LQI5HRAB.js +218 -0
  119. package/dist/wallets/walletConnectors/chunk-LTN4JK3R.js +340 -0
  120. package/dist/wallets/walletConnectors/chunk-MGVZ2TUF.js +318 -0
  121. package/dist/wallets/walletConnectors/chunk-MU46EEQT.js +128 -0
  122. package/dist/wallets/walletConnectors/chunk-MY7UE4VE.js +240 -0
  123. package/dist/wallets/walletConnectors/chunk-NEMEHJ72.js +93 -0
  124. package/dist/wallets/walletConnectors/chunk-NF72HTDP.js +378 -0
  125. package/dist/wallets/walletConnectors/chunk-QI5BHIHY.js +318 -0
  126. package/dist/wallets/walletConnectors/chunk-QLPGMWGT.js +132 -0
  127. package/dist/wallets/walletConnectors/chunk-QODJUJ3A.js +370 -0
  128. package/dist/wallets/walletConnectors/chunk-TBWPVX5M.js +148 -0
  129. package/dist/wallets/walletConnectors/chunk-TLRR3FFT.js +132 -0
  130. package/dist/wallets/walletConnectors/chunk-TM6YD43A.js +341 -0
  131. package/dist/wallets/walletConnectors/chunk-TYJR3KGY.js +46 -0
  132. package/dist/wallets/walletConnectors/chunk-UPQCNBIW.js +341 -0
  133. package/dist/wallets/walletConnectors/chunk-VVXSRRXI.js +189 -0
  134. package/dist/wallets/walletConnectors/chunk-WHL6MSKS.js +492 -0
  135. package/dist/wallets/walletConnectors/chunk-WZ4ZJB74.js +340 -0
  136. package/dist/wallets/walletConnectors/chunk-X3DT5G3F.js +215 -0
  137. package/dist/wallets/walletConnectors/chunk-XDNFWX2X.js +199 -0
  138. package/dist/wallets/walletConnectors/chunk-YNE2UX2Z.js +137 -0
  139. package/dist/wallets/walletConnectors/chunk-YXWHHI4S.js +64 -0
  140. package/dist/wallets/walletConnectors/clvWallet/clvWallet.js +2 -2
  141. package/dist/wallets/walletConnectors/coin98Wallet/coin98Wallet.js +2 -2
  142. package/dist/wallets/walletConnectors/coreWallet/coreWallet.js +2 -2
  143. package/dist/wallets/walletConnectors/foxWallet/foxWallet.js +2 -2
  144. package/dist/wallets/walletConnectors/frontierWallet/frontierWallet.js +2 -2
  145. package/dist/wallets/walletConnectors/gateWallet/gateWallet.js +2 -2
  146. package/dist/wallets/walletConnectors/index.js +109 -108
  147. package/dist/wallets/walletConnectors/iopayWallet/iopayWallet.js +2 -2
  148. package/dist/wallets/walletConnectors/kaiaWallet/kaiaWallet.js +2 -2
  149. package/dist/wallets/walletConnectors/kaikasWallet/kaikasWallet.js +2 -2
  150. package/dist/wallets/walletConnectors/metaMaskWallet/metaMaskWallet.js +2 -2
  151. package/dist/wallets/walletConnectors/okxWallet/okxWallet.js +2 -2
  152. package/dist/wallets/walletConnectors/rainbowWallet/rainbowWallet.js +2 -2
  153. package/dist/wallets/walletConnectors/roninWallet/roninWallet.js +2 -2
  154. package/dist/wallets/walletConnectors/safepalWallet/safepalWallet.js +2 -2
  155. package/dist/wallets/walletConnectors/subWallet/subWallet.js +2 -2
  156. package/dist/wallets/walletConnectors/tokenPocketWallet/tokenPocketWallet.js +2 -2
  157. package/dist/wallets/walletConnectors/trustWallet/trustWallet.js +2 -2
  158. package/dist/wallets/walletConnectors/zealWallet/zealWallet.js +2 -2
  159. package/dist/wallets/walletConnectors/zerionWallet/zerionWallet.js +2 -2
  160. package/package.json +1 -1
@@ -0,0 +1,71 @@
1
+ "use client";
2
+ import {
3
+ TALKEN_API_ENDPOINTS
4
+ } from "./chunk-3Z5DO42M.js";
5
+
6
+ // src/wallets/walletConnectors/abcWallet/api/modules/walletscan.ts
7
+ var TalkenWalletscanModule = class {
8
+ constructor(client) {
9
+ this.client = client;
10
+ }
11
+ /**
12
+ * Get all wallet tokens with balances
13
+ * GET /wallet/scan?type=tokens&chainKeys=...&walletAddress=...
14
+ */
15
+ async getTokens(params) {
16
+ const qs = new URLSearchParams({
17
+ type: "tokens",
18
+ chainKeys: params.chainKeys,
19
+ walletAddress: params.walletAddress
20
+ }).toString();
21
+ return this.client.get(
22
+ `${TALKEN_API_ENDPOINTS.WALLET_SCAN}?${qs}`
23
+ );
24
+ }
25
+ /**
26
+ * Get token metadata by contract address
27
+ * GET /wallet/scan?type=tokens&chainKeys=...&contractAddress=...
28
+ */
29
+ async getToken(params) {
30
+ const qs = new URLSearchParams({
31
+ type: "tokens",
32
+ chainKeys: params.chainKeys,
33
+ contractAddress: params.contractAddress
34
+ }).toString();
35
+ return this.client.get(
36
+ `${TALKEN_API_ENDPOINTS.WALLET_SCAN}?${qs}`
37
+ );
38
+ }
39
+ /**
40
+ * Get native coin balances
41
+ * GET /wallet/scan?type=natives&chainKeys=...&walletAddress=...
42
+ */
43
+ async getNativeTokens(params) {
44
+ const qs = new URLSearchParams({
45
+ type: "natives",
46
+ chainKeys: params.chainKeys,
47
+ walletAddress: params.walletAddress
48
+ }).toString();
49
+ return this.client.get(
50
+ `${TALKEN_API_ENDPOINTS.WALLET_SCAN}?${qs}`
51
+ );
52
+ }
53
+ /**
54
+ * Get NFT metadata
55
+ * GET /wallet/scan?type=nfts&chainKeys=...&walletAddress=...
56
+ */
57
+ async getNfts(params) {
58
+ const qs = new URLSearchParams({
59
+ type: "nfts",
60
+ chainKeys: params.chainKeys,
61
+ walletAddress: params.walletAddress
62
+ }).toString();
63
+ return this.client.get(
64
+ `${TALKEN_API_ENDPOINTS.WALLET_SCAN}?${qs}`
65
+ );
66
+ }
67
+ };
68
+
69
+ export {
70
+ TalkenWalletscanModule
71
+ };
@@ -0,0 +1,64 @@
1
+ "use client";
2
+ import {
3
+ TALKEN_API_ENDPOINTS
4
+ } from "./chunk-3Z5DO42M.js";
5
+
6
+ // src/wallets/walletConnectors/abcWallet/api/modules/wallet.ts
7
+ var TalkenWalletModule = class {
8
+ constructor(client) {
9
+ this.client = client;
10
+ }
11
+ /**
12
+ * Generate/recover MPC wallets (create = idempotent generate/recover)
13
+ * POST /wallet/mpc { action: 'create', email?, pin }
14
+ *
15
+ * @param pin - SHA-256 hashed PIN
16
+ * @param email - User email (optional; server resolves from bearer token if omitted)
17
+ */
18
+ async generate(pin, email) {
19
+ return this.client.post(TALKEN_API_ENDPOINTS.WALLET_MPC, {
20
+ action: "create",
21
+ ...email && { email },
22
+ pin
23
+ });
24
+ }
25
+ /**
26
+ * Recover is the same as generate (create is idempotent)
27
+ */
28
+ async recover(pin, email) {
29
+ return this.generate(pin, email);
30
+ }
31
+ /**
32
+ * Get wallet info
33
+ * POST /wallet/mpc { action: 'info' }
34
+ */
35
+ async getInfo() {
36
+ return this.client.post(TALKEN_API_ENDPOINTS.WALLET_MPC, {
37
+ action: "info"
38
+ });
39
+ }
40
+ /**
41
+ * Get addresses for all chains
42
+ * POST /wallet/address { chain: 'all' }
43
+ */
44
+ async getAddresses() {
45
+ return this.client.post(TALKEN_API_ENDPOINTS.WALLET_ADDRESS, {
46
+ chain: "all"
47
+ });
48
+ }
49
+ /**
50
+ * Get addresses for a specific chain
51
+ * POST /wallet/address { chain, publicKey?, pin? }
52
+ */
53
+ async getAddressForChain(chain, publicKey, pin) {
54
+ return this.client.post(TALKEN_API_ENDPOINTS.WALLET_ADDRESS, {
55
+ chain,
56
+ ...publicKey && { publicKey },
57
+ ...pin && { pin }
58
+ });
59
+ }
60
+ };
61
+
62
+ export {
63
+ TalkenWalletModule
64
+ };
@@ -0,0 +1,492 @@
1
+ "use client";
2
+ import {
3
+ AbstractChainProvider
4
+ } from "./chunk-QLPGMWGT.js";
5
+ import {
6
+ BitcoinProviderError,
7
+ ProviderErrorCode
8
+ } from "./chunk-YXWHHI4S.js";
9
+ import {
10
+ createLogger
11
+ } from "./chunk-762I67R6.js";
12
+ import {
13
+ getCredentialManager
14
+ } from "./chunk-YNE2UX2Z.js";
15
+
16
+ // src/wallets/walletConnectors/abcWallet/abcBitcoinProvider.ts
17
+ var logger = createLogger("BitcoinProvider");
18
+ function isTalkenApiClient(client) {
19
+ return typeof client?.bitcoin?.getUtxos === "function";
20
+ }
21
+ var BITCOIN_NETWORKS = {
22
+ mainnet: {
23
+ name: "Bitcoin Mainnet",
24
+ type: "bitcoin",
25
+ explorer: "https://blockstream.info"
26
+ },
27
+ testnet: {
28
+ name: "Bitcoin Testnet",
29
+ type: "bitcoin_testnet",
30
+ explorer: "https://blockstream.info/testnet"
31
+ }
32
+ };
33
+ var AbcBitcoinProvider = class extends AbstractChainProvider {
34
+ // 1 minute
35
+ constructor(client) {
36
+ super(isTalkenApiClient(client) ? client : void 0);
37
+ this.network = BITCOIN_NETWORKS.testnet;
38
+ this.utxoCache = /* @__PURE__ */ new Map();
39
+ this.cacheExpiry = /* @__PURE__ */ new Map();
40
+ this.CACHE_TTL = 6e4;
41
+ }
42
+ extractHashSignature(result) {
43
+ const data = result;
44
+ return data?.signatureHex || data?.signstr || data?.result?.signstr || data?.data?.signatureHex || data?.data?.signstr || data?.data?.result?.signstr || "";
45
+ }
46
+ getRecoveryEmail() {
47
+ return getCredentialManager().getEmail() || void 0;
48
+ }
49
+ /**
50
+ * Call request interceptor if set (throws on user cancel)
51
+ */
52
+ async callInterceptor(request) {
53
+ if (this.requestInterceptor) {
54
+ await this.requestInterceptor(request);
55
+ }
56
+ }
57
+ onWalletSet(wallet) {
58
+ if (wallet.network === "bitcoin") {
59
+ this.network = BITCOIN_NETWORKS.mainnet;
60
+ } else {
61
+ this.network = BITCOIN_NETWORKS.testnet;
62
+ }
63
+ this.clearUtxoCache();
64
+ this.emit("connect", {
65
+ address: wallet.address,
66
+ network: this.network.type
67
+ });
68
+ logger.info(
69
+ "Wallet connected:",
70
+ `${wallet.address.substring(0, 6)}...${wallet.address.substring(wallet.address.length - 6)}`
71
+ );
72
+ }
73
+ clearWallet() {
74
+ this.clearUtxoCache();
75
+ super.clearWallet();
76
+ logger.info("Wallet disconnected");
77
+ }
78
+ /**
79
+ * Set network
80
+ */
81
+ setNetwork(networkKey) {
82
+ const newNetwork = BITCOIN_NETWORKS[networkKey];
83
+ if (!newNetwork) {
84
+ throw new BitcoinProviderError(
85
+ ProviderErrorCode.INVALID_PARAMS,
86
+ `Unknown network: ${networkKey}`
87
+ );
88
+ }
89
+ const previousType = this.network.type;
90
+ this.network = newNetwork;
91
+ if (previousType !== newNetwork.type) {
92
+ this.emit("networkChanged", newNetwork.type);
93
+ this.clearUtxoCache();
94
+ }
95
+ }
96
+ /**
97
+ * Get current network
98
+ */
99
+ getNetwork() {
100
+ return this.network;
101
+ }
102
+ /**
103
+ * Get Bitcoin address
104
+ */
105
+ async getAddress() {
106
+ if (!this.wallet) {
107
+ throw new BitcoinProviderError(
108
+ ProviderErrorCode.DISCONNECTED,
109
+ "Wallet not connected"
110
+ );
111
+ }
112
+ return this.wallet.address;
113
+ }
114
+ /**
115
+ * Get compressed public key (33 bytes)
116
+ */
117
+ async getPublicKey() {
118
+ if (!this.wallet) {
119
+ throw new BitcoinProviderError(
120
+ ProviderErrorCode.DISCONNECTED,
121
+ "Wallet not connected"
122
+ );
123
+ }
124
+ return this.wallet.publicKey;
125
+ }
126
+ /**
127
+ * Get address type (bech32, p2pkh, etc.)
128
+ */
129
+ getAddressType() {
130
+ if (!this.wallet) {
131
+ throw new BitcoinProviderError(
132
+ ProviderErrorCode.DISCONNECTED,
133
+ "Wallet not connected"
134
+ );
135
+ }
136
+ return this.wallet.addressType;
137
+ }
138
+ /**
139
+ * Clear UTXO cache
140
+ */
141
+ clearUtxoCache() {
142
+ this.utxoCache.clear();
143
+ this.cacheExpiry.clear();
144
+ }
145
+ /**
146
+ * Check if cache is valid
147
+ */
148
+ isCacheValid(address) {
149
+ const expiry = this.cacheExpiry.get(address);
150
+ if (!expiry)
151
+ return false;
152
+ return Date.now() < expiry;
153
+ }
154
+ normalizeUtxos(rawUtxos) {
155
+ return rawUtxos.map((u) => ({
156
+ txid: String(u?.txid ?? u?.tx_hash ?? ""),
157
+ vout: Number(u?.vout ?? u?.output_index ?? 0),
158
+ value: Number(u?.value ?? u?.satoshis ?? 0),
159
+ scriptPubKey: String(
160
+ u?.scriptPubKey ?? u?.script_pub_key ?? u?.script ?? ""
161
+ ),
162
+ confirmations: Number(u?.confirmations ?? 0)
163
+ })).filter(
164
+ (u) => Boolean(u.txid) && Number.isFinite(u.vout) && Number.isFinite(u.value) && Number.isFinite(u.confirmations)
165
+ );
166
+ }
167
+ /**
168
+ * Get UTXOs for address (with caching)
169
+ */
170
+ async getUtxos(forceRefresh = false) {
171
+ if (!this.wallet) {
172
+ throw new BitcoinProviderError(
173
+ ProviderErrorCode.DISCONNECTED,
174
+ "Wallet not connected"
175
+ );
176
+ }
177
+ const address = this.wallet.address;
178
+ if (!forceRefresh && this.isCacheValid(address)) {
179
+ const cached = this.utxoCache.get(address);
180
+ if (cached) {
181
+ logger.debug(`Using cached UTXOs (${cached.length} items)`);
182
+ return cached;
183
+ }
184
+ }
185
+ try {
186
+ logger.debug("Fetching UTXOs from network...");
187
+ const api = this.getTalkenApiClientOrThrow();
188
+ const result = await api.bitcoin.getUtxos(this.network.type, address);
189
+ const utxos = this.normalizeUtxos(result.utxos || []);
190
+ this.utxoCache.set(address, utxos);
191
+ this.cacheExpiry.set(address, Date.now() + this.CACHE_TTL);
192
+ logger.info(`Fetched ${utxos.length} UTXOs`);
193
+ return utxos;
194
+ } catch (error) {
195
+ logger.error("Failed to fetch UTXOs:", error.message);
196
+ throw new BitcoinProviderError(
197
+ ProviderErrorCode.INTERNAL_ERROR,
198
+ "Failed to fetch UTXOs",
199
+ error
200
+ );
201
+ }
202
+ }
203
+ /**
204
+ * Get total balance (sum of all UTXOs)
205
+ * Returns balance in satoshis
206
+ */
207
+ async getBalance(forceRefresh = false) {
208
+ const utxos = await this.getUtxos(forceRefresh);
209
+ const balance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
210
+ logger.debug(`Balance: ${balance} satoshis (${balance / 1e8} BTC)`);
211
+ return balance;
212
+ }
213
+ /**
214
+ * Estimate transaction fee
215
+ * Returns fee rate in satoshis per byte
216
+ */
217
+ async estimateFee(targetBlocks = 6) {
218
+ try {
219
+ const api = this.getTalkenApiClientOrThrow();
220
+ const result = await api.bitcoin.getFeeRate(
221
+ this.network.type,
222
+ targetBlocks
223
+ );
224
+ const feeRate = Number(result.feeRate);
225
+ if (!Number.isFinite(feeRate) || feeRate <= 0) {
226
+ throw new Error("Invalid fee rate");
227
+ }
228
+ logger.debug(`Fee rate: ${feeRate} sat/byte`);
229
+ return feeRate;
230
+ } catch (_error) {
231
+ logger.warn("Fee estimation failed, using default");
232
+ return 1;
233
+ }
234
+ }
235
+ /**
236
+ * Sign Bitcoin message (Bitcoin Signed Message format)
237
+ * Uses secp256k1 sign/hash endpoint with double-SHA256 of prefixed message.
238
+ *
239
+ * Format: SHA256(SHA256("\x18Bitcoin Signed Message:\n" + varint(len) + message))
240
+ *
241
+ * @param message - Message to sign (string)
242
+ * @returns Signature in hex format (compact: r + s + v)
243
+ */
244
+ async signMessage(message) {
245
+ if (!this.wallet) {
246
+ throw new BitcoinProviderError(
247
+ ProviderErrorCode.DISCONNECTED,
248
+ "Wallet not connected"
249
+ );
250
+ }
251
+ await this.callInterceptor({
252
+ chain: "bitcoin",
253
+ method: "signMessage",
254
+ address: this.wallet.address,
255
+ network: this.network.type,
256
+ message
257
+ });
258
+ logger.info("Signing Bitcoin message...");
259
+ const prefix = "Bitcoin Signed Message:\n";
260
+ const msgBytes = new TextEncoder().encode(message);
261
+ const varint = this.encodeVarint(msgBytes.length);
262
+ const prefixBytes = new TextEncoder().encode(prefix);
263
+ const preimage = new Uint8Array(
264
+ prefixBytes.length + varint.length + msgBytes.length
265
+ );
266
+ preimage.set(prefixBytes, 0);
267
+ preimage.set(varint, prefixBytes.length);
268
+ preimage.set(msgBytes, prefixBytes.length + varint.length);
269
+ const hash1 = await crypto.subtle.digest("SHA-256", preimage);
270
+ const hash2 = await crypto.subtle.digest("SHA-256", hash1);
271
+ const hashHex = Array.from(new Uint8Array(hash2)).map((b) => b.toString(16).padStart(2, "0")).join("");
272
+ const api = this.getTalkenApiClientOrThrow();
273
+ if (!api) {
274
+ throw new BitcoinProviderError(
275
+ ProviderErrorCode.INTERNAL_ERROR,
276
+ "TalkenApiClient not initialized"
277
+ );
278
+ }
279
+ const pinHash = getCredentialManager().getPinHash() || "";
280
+ const email = this.getRecoveryEmail();
281
+ let signstr = "";
282
+ try {
283
+ const result = await api.bitcoin.execute({
284
+ action: "signHash",
285
+ hash: hashHex,
286
+ pin: pinHash || void 0,
287
+ network: this.network.type,
288
+ ...email && { email }
289
+ });
290
+ signstr = this.extractHashSignature(result);
291
+ } catch (error) {
292
+ logger.warn(
293
+ "BTC signHash endpoint failed, falling back to generic sign/hash:",
294
+ error
295
+ );
296
+ }
297
+ if (!signstr) {
298
+ signstr = this.extractHashSignature(
299
+ await api.bitcoin.signHash({
300
+ hash: hashHex,
301
+ pin: pinHash || void 0,
302
+ network: this.network.type,
303
+ ...email && { email }
304
+ })
305
+ );
306
+ }
307
+ if (!signstr) {
308
+ throw new BitcoinProviderError(
309
+ ProviderErrorCode.INTERNAL_ERROR,
310
+ "Empty signature from sign/hash"
311
+ );
312
+ }
313
+ logger.info("Message signed successfully");
314
+ return signstr;
315
+ }
316
+ /** Encode integer as Bitcoin varint */
317
+ encodeVarint(n) {
318
+ if (n < 253)
319
+ return new Uint8Array([n]);
320
+ if (n <= 65535) {
321
+ const buf2 = new Uint8Array(3);
322
+ buf2[0] = 253;
323
+ buf2[1] = n & 255;
324
+ buf2[2] = n >> 8 & 255;
325
+ return buf2;
326
+ }
327
+ const buf = new Uint8Array(5);
328
+ buf[0] = 254;
329
+ buf[1] = n & 255;
330
+ buf[2] = n >> 8 & 255;
331
+ buf[3] = n >> 16 & 255;
332
+ buf[4] = n >> 24 & 255;
333
+ return buf;
334
+ }
335
+ /**
336
+ * High-level transaction sending (like Solana pattern)
337
+ * Creates, signs, and broadcasts transaction
338
+ *
339
+ * @param params - Transaction parameters
340
+ * @param params.toAddress - Recipient Bitcoin address
341
+ * @param params.amount - Amount in BTC (will be converted to satoshis)
342
+ * @returns Transaction hash
343
+ */
344
+ async sendTransaction(params) {
345
+ if (!this.wallet) {
346
+ throw new BitcoinProviderError(
347
+ ProviderErrorCode.DISCONNECTED,
348
+ "Wallet not connected"
349
+ );
350
+ }
351
+ try {
352
+ const INPUT_PER_BYTE = 141;
353
+ const BUFFER = 500;
354
+ let estimatedFeeBtc;
355
+ try {
356
+ const feeRate = await this.estimateFee();
357
+ const estimatedSatoshi = feeRate * 2 * INPUT_PER_BYTE + BUFFER;
358
+ estimatedFeeBtc = (estimatedSatoshi / 1e8).toFixed(8).replace(/0+$/, "").replace(/\.$/, "");
359
+ } catch {
360
+ }
361
+ await this.callInterceptor({
362
+ chain: "bitcoin",
363
+ method: "sendTransaction",
364
+ fromAddress: this.wallet.address,
365
+ toAddress: params.toAddress,
366
+ amount: String(params.amount),
367
+ symbol: "BTC",
368
+ network: this.network.type,
369
+ isNativeToken: true,
370
+ estimatedFee: estimatedFeeBtc,
371
+ feeSymbol: "BTC"
372
+ });
373
+ logger.info("Starting high-level transaction...");
374
+ const api = this.getTalkenApiClientOrThrow();
375
+ const pinHash = api.isAccessKeyMode() ? void 0 : getCredentialManager().getPinHash();
376
+ if (!pinHash && !api.isAccessKeyMode()) {
377
+ throw new BitcoinProviderError(
378
+ ProviderErrorCode.INTERNAL_ERROR,
379
+ "PIN hash not found. Please login again."
380
+ );
381
+ }
382
+ const email = this.getRecoveryEmail();
383
+ const satoshis = Math.floor(params.amount * 1e8);
384
+ const result = await api.bitcoin.sendTransaction({
385
+ toAddress: params.toAddress,
386
+ amountSats: satoshis.toString(),
387
+ pin: pinHash || void 0,
388
+ ...email && { email }
389
+ });
390
+ logger.info(
391
+ "BTC transaction complete via TalkenApiClient:",
392
+ result.txHash
393
+ );
394
+ this.emit("transactionBroadcasted", {
395
+ txHash: result.txHash,
396
+ explorerUrl: `${this.network.explorer}/tx/${result.txHash}`
397
+ });
398
+ this.clearUtxoCache();
399
+ return result.txHash;
400
+ } catch (error) {
401
+ if (error.message?.includes("cancelled") || error.message?.includes("rejected")) {
402
+ logger.info("User cancelled transaction");
403
+ throw new BitcoinProviderError(
404
+ ProviderErrorCode.USER_REJECTED,
405
+ "User rejected transaction",
406
+ error
407
+ );
408
+ }
409
+ logger.error("Transaction failed:", error.message);
410
+ if (error.message?.includes("insufficient")) {
411
+ throw new BitcoinProviderError(
412
+ ProviderErrorCode.INSUFFICIENT_FUNDS,
413
+ "Insufficient BTC balance",
414
+ error
415
+ );
416
+ }
417
+ this.emit("error", error);
418
+ throw new BitcoinProviderError(
419
+ ProviderErrorCode.INTERNAL_ERROR,
420
+ "Failed to send transaction",
421
+ error
422
+ );
423
+ }
424
+ }
425
+ /**
426
+ * Broadcast signed transaction to network
427
+ *
428
+ * @param rawTransaction - Raw transaction in hex format
429
+ * @param psbt - Optional finalized PSBT
430
+ * @returns Transaction hash
431
+ */
432
+ async broadcastTransaction(rawTransaction, psbt) {
433
+ if (!this.wallet) {
434
+ throw new BitcoinProviderError(
435
+ ProviderErrorCode.DISCONNECTED,
436
+ "Wallet not connected"
437
+ );
438
+ }
439
+ try {
440
+ logger.info("Broadcasting transaction...");
441
+ if (psbt) {
442
+ logger.debug(
443
+ "PSBT argument provided; raw tx broadcast uses rawTransaction only via talken-api"
444
+ );
445
+ }
446
+ const api = this.getTalkenApiClientOrThrow();
447
+ const result = await api.bitcoin.broadcastRawTransaction({
448
+ network: this.network.type,
449
+ rawTransaction
450
+ });
451
+ logger.info("Transaction broadcasted:", result.txHash);
452
+ this.emit("transactionBroadcasted", {
453
+ txHash: result.txHash,
454
+ explorerUrl: `${this.network.explorer}/tx/${result.txHash}`
455
+ });
456
+ this.clearUtxoCache();
457
+ return result.txHash;
458
+ } catch (error) {
459
+ logger.error("Transaction broadcast failed:", error.message);
460
+ this.emit("error", error);
461
+ throw new BitcoinProviderError(
462
+ ProviderErrorCode.INTERNAL_ERROR,
463
+ "Failed to broadcast transaction",
464
+ error
465
+ );
466
+ }
467
+ }
468
+ /**
469
+ * Get wallet info
470
+ */
471
+ getWalletInfo() {
472
+ if (!this.wallet)
473
+ return null;
474
+ return {
475
+ address: this.wallet.address,
476
+ publicKey: this.wallet.publicKey,
477
+ addressType: this.wallet.addressType,
478
+ network: this.network.type
479
+ };
480
+ }
481
+ /**
482
+ * Refresh UTXO cache
483
+ */
484
+ async refreshUtxos() {
485
+ return this.getUtxos(true);
486
+ }
487
+ };
488
+
489
+ export {
490
+ BITCOIN_NETWORKS,
491
+ AbcBitcoinProvider
492
+ };