@sip-protocol/sdk 0.7.2 → 0.7.4

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 (262) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +267 -0
  3. package/dist/{TransportWebUSB-TQ7WZ4LE.mjs → TransportWebUSB-YQMAGJAJ.mjs} +12 -9
  4. package/dist/browser.d.mts +10 -4
  5. package/dist/browser.d.ts +10 -4
  6. package/dist/browser.js +48874 -18336
  7. package/dist/browser.mjs +674 -48
  8. package/dist/chunk-4GRJ5MAW.mjs +152 -0
  9. package/dist/chunk-5D7A3L3W.mjs +717 -0
  10. package/dist/chunk-64AYA5F5.mjs +7834 -0
  11. package/dist/chunk-GMDGB22A.mjs +379 -0
  12. package/dist/chunk-I534WKN7.mjs +328 -0
  13. package/dist/chunk-IBZVA5Y7.mjs +1003 -0
  14. package/dist/chunk-PRRZAWJE.mjs +223 -0
  15. package/dist/{chunk-UJCSKKID.mjs → chunk-XGB3TDIC.mjs} +13 -1
  16. package/dist/chunk-YWGJ77A2.mjs +33806 -0
  17. package/dist/{chunk-6WGN57S2.mjs → chunk-Z3K7W5S3.mjs} +48 -0
  18. package/dist/constants-LHAAUC2T.mjs +51 -0
  19. package/dist/dist-2OGQ7FED.mjs +3957 -0
  20. package/dist/dist-IFHPYLDX.mjs +254 -0
  21. package/dist/fulfillment_proof-ANHVPKTB.mjs +21 -0
  22. package/dist/funding_proof-ICFZ5LHY.mjs +21 -0
  23. package/dist/index-DXh2IGkz.d.ts +24681 -0
  24. package/dist/index-DeE1ZzA4.d.mts +24681 -0
  25. package/dist/index.d.mts +9 -3
  26. package/dist/index.d.ts +9 -3
  27. package/dist/index.js +48676 -17318
  28. package/dist/index.mjs +583 -19
  29. package/dist/interface-Bf7w1PLW.d.mts +679 -0
  30. package/dist/interface-Bf7w1PLW.d.ts +679 -0
  31. package/dist/{noir-DKfEzWy9.d.mts → noir-kzbLVTei.d.mts} +31 -21
  32. package/dist/{noir-DKfEzWy9.d.ts → noir-kzbLVTei.d.ts} +31 -21
  33. package/dist/proofs/halo2.d.mts +151 -0
  34. package/dist/proofs/halo2.d.ts +151 -0
  35. package/dist/proofs/halo2.js +350 -0
  36. package/dist/proofs/halo2.mjs +11 -0
  37. package/dist/proofs/kimchi.d.mts +160 -0
  38. package/dist/proofs/kimchi.d.ts +160 -0
  39. package/dist/proofs/kimchi.js +431 -0
  40. package/dist/proofs/kimchi.mjs +13 -0
  41. package/dist/proofs/noir.d.mts +1 -1
  42. package/dist/proofs/noir.d.ts +1 -1
  43. package/dist/proofs/noir.js +74 -18
  44. package/dist/proofs/noir.mjs +84 -24
  45. package/dist/solana-U3MEGU7W.mjs +280 -0
  46. package/dist/validity_proof-3POXLPNY.mjs +21 -0
  47. package/package.json +54 -21
  48. package/src/adapters/index.ts +41 -0
  49. package/src/adapters/jupiter.ts +571 -0
  50. package/src/adapters/near-intents.ts +135 -0
  51. package/src/advisor/advisor.ts +653 -0
  52. package/src/advisor/index.ts +54 -0
  53. package/src/advisor/tools.ts +303 -0
  54. package/src/advisor/types.ts +164 -0
  55. package/src/chains/ethereum/announcement.ts +536 -0
  56. package/src/chains/ethereum/bnb-optimizations.ts +474 -0
  57. package/src/chains/ethereum/commitment.ts +522 -0
  58. package/src/chains/ethereum/constants.ts +462 -0
  59. package/src/chains/ethereum/deployment.ts +596 -0
  60. package/src/chains/ethereum/gas-estimation.ts +538 -0
  61. package/src/chains/ethereum/index.ts +268 -0
  62. package/src/chains/ethereum/optimizations.ts +614 -0
  63. package/src/chains/ethereum/privacy-adapter.ts +855 -0
  64. package/src/chains/ethereum/registry.ts +584 -0
  65. package/src/chains/ethereum/rpc.ts +905 -0
  66. package/src/chains/ethereum/stealth.ts +491 -0
  67. package/src/chains/ethereum/token.ts +790 -0
  68. package/src/chains/ethereum/transfer.ts +637 -0
  69. package/src/chains/ethereum/types.ts +456 -0
  70. package/src/chains/ethereum/viewing-key.ts +455 -0
  71. package/src/chains/near/commitment.ts +608 -0
  72. package/src/chains/near/constants.ts +284 -0
  73. package/src/chains/near/function-call.ts +871 -0
  74. package/src/chains/near/history.ts +654 -0
  75. package/src/chains/near/implicit-account.ts +840 -0
  76. package/src/chains/near/index.ts +393 -0
  77. package/src/chains/near/native-transfer.ts +658 -0
  78. package/src/chains/near/nep141.ts +775 -0
  79. package/src/chains/near/privacy-adapter.ts +889 -0
  80. package/src/chains/near/resolver.ts +971 -0
  81. package/src/chains/near/rpc.ts +1016 -0
  82. package/src/chains/near/stealth.ts +419 -0
  83. package/src/chains/near/types.ts +317 -0
  84. package/src/chains/near/viewing-key.ts +876 -0
  85. package/src/chains/solana/anchor-transfer.ts +386 -0
  86. package/src/chains/solana/commitment.ts +577 -0
  87. package/src/chains/solana/constants.ts +126 -12
  88. package/src/chains/solana/ephemeral-keys.ts +543 -0
  89. package/src/chains/solana/index.ts +276 -1
  90. package/src/chains/solana/key-derivation.ts +418 -0
  91. package/src/chains/solana/kit-compat.ts +334 -0
  92. package/src/chains/solana/optimizations.ts +560 -0
  93. package/src/chains/solana/privacy-adapter.ts +605 -0
  94. package/src/chains/solana/providers/generic.ts +201 -0
  95. package/src/chains/solana/providers/helius-enhanced-types.ts +336 -0
  96. package/src/chains/solana/providers/helius-enhanced.ts +623 -0
  97. package/src/chains/solana/providers/helius.ts +402 -0
  98. package/src/chains/solana/providers/index.ts +85 -0
  99. package/src/chains/solana/providers/interface.ts +221 -0
  100. package/src/chains/solana/providers/quicknode.ts +409 -0
  101. package/src/chains/solana/providers/triton.ts +426 -0
  102. package/src/chains/solana/providers/webhook.ts +790 -0
  103. package/src/chains/solana/rpc-client.ts +1150 -0
  104. package/src/chains/solana/scan.ts +170 -73
  105. package/src/chains/solana/sol-transfer.ts +732 -0
  106. package/src/chains/solana/spl-transfer.ts +886 -0
  107. package/src/chains/solana/stealth-scanner.ts +703 -0
  108. package/src/chains/solana/sunspot-verifier.ts +453 -0
  109. package/src/chains/solana/transaction-builder.ts +755 -0
  110. package/src/chains/solana/transfer.ts +74 -5
  111. package/src/chains/solana/types.ts +77 -7
  112. package/src/chains/solana/utils.ts +110 -0
  113. package/src/chains/solana/viewing-key.ts +807 -0
  114. package/src/compliance/fireblocks.ts +921 -0
  115. package/src/compliance/index.ts +37 -0
  116. package/src/compliance/range-sas.ts +956 -0
  117. package/src/config/endpoints.ts +100 -0
  118. package/src/crypto.ts +11 -8
  119. package/src/errors.ts +82 -0
  120. package/src/evm/erc4337-relayer.ts +830 -0
  121. package/src/evm/index.ts +47 -0
  122. package/src/fees/calculator.ts +396 -0
  123. package/src/fees/index.ts +87 -0
  124. package/src/fees/near-contract.ts +429 -0
  125. package/src/fees/types.ts +268 -0
  126. package/src/index.ts +785 -1
  127. package/src/intent.ts +6 -3
  128. package/src/logger.ts +324 -0
  129. package/src/network/index.ts +80 -0
  130. package/src/network/proxy.ts +691 -0
  131. package/src/optimizations/index.ts +541 -0
  132. package/src/oracle/types.ts +1 -0
  133. package/src/privacy-backends/arcium-types.ts +727 -0
  134. package/src/privacy-backends/arcium.ts +719 -0
  135. package/src/privacy-backends/combined-privacy.ts +866 -0
  136. package/src/privacy-backends/cspl-token.ts +595 -0
  137. package/src/privacy-backends/cspl-types.ts +512 -0
  138. package/src/privacy-backends/cspl.ts +907 -0
  139. package/src/privacy-backends/health.ts +488 -0
  140. package/src/privacy-backends/inco-types.ts +323 -0
  141. package/src/privacy-backends/inco.ts +616 -0
  142. package/src/privacy-backends/index.ts +336 -0
  143. package/src/privacy-backends/interface.ts +906 -0
  144. package/src/privacy-backends/lru-cache.ts +343 -0
  145. package/src/privacy-backends/magicblock.ts +458 -0
  146. package/src/privacy-backends/mock.ts +258 -0
  147. package/src/privacy-backends/privacycash-types.ts +278 -0
  148. package/src/privacy-backends/privacycash.ts +456 -0
  149. package/src/privacy-backends/private-swap.ts +570 -0
  150. package/src/privacy-backends/rate-limiter.ts +683 -0
  151. package/src/privacy-backends/registry.ts +690 -0
  152. package/src/privacy-backends/router.ts +626 -0
  153. package/src/privacy-backends/shadowwire.ts +449 -0
  154. package/src/privacy-backends/sip-native.ts +256 -0
  155. package/src/privacy-logger.ts +191 -0
  156. package/src/production-safety.ts +373 -0
  157. package/src/proofs/aggregator.ts +1029 -0
  158. package/src/proofs/browser-composer.ts +1150 -0
  159. package/src/proofs/browser.ts +113 -25
  160. package/src/proofs/cache/index.ts +127 -0
  161. package/src/proofs/cache/interface.ts +545 -0
  162. package/src/proofs/cache/key-generator.ts +188 -0
  163. package/src/proofs/cache/lru-cache.ts +481 -0
  164. package/src/proofs/cache/multi-tier-cache.ts +575 -0
  165. package/src/proofs/cache/persistent-cache.ts +788 -0
  166. package/src/proofs/compliance-proof.ts +872 -0
  167. package/src/proofs/composer/base.ts +923 -0
  168. package/src/proofs/composer/index.ts +25 -0
  169. package/src/proofs/composer/interface.ts +518 -0
  170. package/src/proofs/composer/types.ts +383 -0
  171. package/src/proofs/converters/halo2.ts +452 -0
  172. package/src/proofs/converters/index.ts +208 -0
  173. package/src/proofs/converters/interface.ts +363 -0
  174. package/src/proofs/converters/kimchi.ts +462 -0
  175. package/src/proofs/converters/noir.ts +451 -0
  176. package/src/proofs/fallback.ts +888 -0
  177. package/src/proofs/halo2.ts +42 -0
  178. package/src/proofs/index.ts +471 -0
  179. package/src/proofs/interface.ts +13 -0
  180. package/src/proofs/kimchi.ts +42 -0
  181. package/src/proofs/lazy.ts +1004 -0
  182. package/src/proofs/mock.ts +25 -1
  183. package/src/proofs/noir.ts +111 -30
  184. package/src/proofs/orchestrator.ts +960 -0
  185. package/src/proofs/parallel/concurrency.ts +297 -0
  186. package/src/proofs/parallel/dependency-graph.ts +602 -0
  187. package/src/proofs/parallel/executor.ts +420 -0
  188. package/src/proofs/parallel/index.ts +131 -0
  189. package/src/proofs/parallel/interface.ts +685 -0
  190. package/src/proofs/parallel/worker-pool.ts +644 -0
  191. package/src/proofs/providers/halo2.ts +560 -0
  192. package/src/proofs/providers/index.ts +34 -0
  193. package/src/proofs/providers/kimchi.ts +641 -0
  194. package/src/proofs/validator.ts +881 -0
  195. package/src/proofs/verifier.ts +867 -0
  196. package/src/quantum/index.ts +112 -0
  197. package/src/quantum/winternitz-vault.ts +639 -0
  198. package/src/quantum/wots.ts +611 -0
  199. package/src/settlement/backends/direct-chain.ts +1 -0
  200. package/src/settlement/index.ts +9 -0
  201. package/src/settlement/router.ts +732 -46
  202. package/src/solana/index.ts +72 -0
  203. package/src/solana/jito-relayer.ts +687 -0
  204. package/src/solana/noir-verifier-types.ts +430 -0
  205. package/src/solana/noir-verifier.ts +816 -0
  206. package/src/stealth/address-derivation.ts +193 -0
  207. package/src/stealth/ed25519.ts +431 -0
  208. package/src/stealth/index.ts +233 -0
  209. package/src/stealth/meta-address.ts +221 -0
  210. package/src/stealth/secp256k1.ts +368 -0
  211. package/src/stealth/utils.ts +194 -0
  212. package/src/stealth.ts +50 -1504
  213. package/src/surveillance/algorithms/address-reuse.ts +143 -0
  214. package/src/surveillance/algorithms/cluster.ts +247 -0
  215. package/src/surveillance/algorithms/exchange.ts +295 -0
  216. package/src/surveillance/algorithms/temporal.ts +337 -0
  217. package/src/surveillance/analyzer.ts +442 -0
  218. package/src/surveillance/index.ts +64 -0
  219. package/src/surveillance/scoring.ts +372 -0
  220. package/src/surveillance/types.ts +264 -0
  221. package/src/sync/index.ts +106 -0
  222. package/src/sync/manager.ts +504 -0
  223. package/src/sync/mock-provider.ts +318 -0
  224. package/src/sync/oblivious.ts +625 -0
  225. package/src/tokens/index.ts +15 -0
  226. package/src/tokens/registry.ts +301 -0
  227. package/src/utils/deprecation.ts +94 -0
  228. package/src/utils/index.ts +9 -0
  229. package/src/wallet/ethereum/index.ts +68 -0
  230. package/src/wallet/ethereum/metamask-privacy.ts +420 -0
  231. package/src/wallet/ethereum/multi-wallet.ts +646 -0
  232. package/src/wallet/ethereum/privacy-adapter.ts +700 -0
  233. package/src/wallet/ethereum/types.ts +3 -1
  234. package/src/wallet/ethereum/walletconnect-adapter.ts +675 -0
  235. package/src/wallet/hardware/index.ts +10 -0
  236. package/src/wallet/hardware/ledger-privacy.ts +414 -0
  237. package/src/wallet/index.ts +71 -0
  238. package/src/wallet/near/adapter.ts +626 -0
  239. package/src/wallet/near/index.ts +86 -0
  240. package/src/wallet/near/meteor-wallet.ts +1153 -0
  241. package/src/wallet/near/my-near-wallet.ts +790 -0
  242. package/src/wallet/near/wallet-selector.ts +702 -0
  243. package/src/wallet/solana/adapter.ts +6 -4
  244. package/src/wallet/solana/index.ts +13 -0
  245. package/src/wallet/solana/privacy-adapter.ts +567 -0
  246. package/src/wallet/sui/types.ts +6 -4
  247. package/src/zcash/rpc-client.ts +13 -6
  248. package/dist/chunk-3INS3PR5.mjs +0 -884
  249. package/dist/chunk-3OVABDRH.mjs +0 -17096
  250. package/dist/chunk-DLDWZFYC.mjs +0 -1495
  251. package/dist/chunk-E6SZWREQ.mjs +0 -57
  252. package/dist/chunk-G33LB27A.mjs +0 -16166
  253. package/dist/chunk-HGU6HZRC.mjs +0 -231
  254. package/dist/chunk-L2K34JCU.mjs +0 -1496
  255. package/dist/chunk-SN4ZDTVW.mjs +0 -16166
  256. package/dist/constants-VOI7BSLK.mjs +0 -27
  257. package/dist/index-BYZbDjal.d.ts +0 -11390
  258. package/dist/index-CHB3KuOB.d.mts +0 -11859
  259. package/dist/index-CzWPI6Le.d.ts +0 -11859
  260. package/dist/index-xbWjohNq.d.mts +0 -11390
  261. package/dist/solana-5EMCTPTS.mjs +0 -46
  262. package/dist/solana-Q4NAVBTS.mjs +0 -46
@@ -0,0 +1,626 @@
1
+ /**
2
+ * NEAR Wallet Adapter with Privacy Support
3
+ *
4
+ * Extends the base wallet adapter to support NEAR same-chain privacy operations,
5
+ * including stealth address generation and privacy transaction signing.
6
+ *
7
+ * @example Basic usage
8
+ * ```typescript
9
+ * import { NEARWalletAdapter } from '@sip-protocol/sdk'
10
+ *
11
+ * const wallet = new NEARWalletAdapter({
12
+ * network: 'mainnet',
13
+ * })
14
+ *
15
+ * await wallet.connect()
16
+ *
17
+ * // Generate stealth meta-address
18
+ * const { metaAddress, encoded } = await wallet.generateStealthMetaAddress()
19
+ *
20
+ * // Sign a privacy transaction
21
+ * const signed = await wallet.signPrivacyTransaction(transfer)
22
+ * ```
23
+ *
24
+ * @packageDocumentation
25
+ */
26
+
27
+ import { ed25519 } from '@noble/curves/ed25519'
28
+ import { sha256 } from '@noble/hashes/sha2'
29
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
30
+ import type {
31
+ ChainId,
32
+ HexString,
33
+ Asset,
34
+ Signature,
35
+ UnsignedTransaction,
36
+ SignedTransaction,
37
+ TransactionReceipt,
38
+ StealthMetaAddress,
39
+ StealthAddress,
40
+ } from '@sip-protocol/types'
41
+ import { BaseWalletAdapter } from '../base-adapter'
42
+ import { WalletError } from '../errors'
43
+ import { WalletErrorCode } from '@sip-protocol/types'
44
+ import type { NEARNetwork } from '../../chains/near/constants'
45
+ import {
46
+ generateNEARStealthAddress,
47
+ deriveNEARStealthPrivateKey,
48
+ encodeNEARStealthMetaAddress,
49
+ parseNEARStealthMetaAddress,
50
+ checkNEARStealthAddress,
51
+ } from '../../chains/near/stealth'
52
+ import type { NEARAction } from '../../chains/near/implicit-account'
53
+
54
+ // ─── Types ────────────────────────────────────────────────────────────────────
55
+
56
+ /**
57
+ * NEAR wallet adapter configuration
58
+ */
59
+ export interface NEARWalletAdapterConfig {
60
+ /** NEAR network (mainnet, testnet) */
61
+ network: NEARNetwork
62
+ /** Wallet name/identifier */
63
+ walletName?: string
64
+ /** RPC URL override */
65
+ rpcUrl?: string
66
+ }
67
+
68
+ /**
69
+ * NEAR wallet connection options
70
+ */
71
+ export interface NEARConnectOptions {
72
+ /** Contract to request access for (optional) */
73
+ contractId?: string
74
+ /** Methods to request access for (optional) */
75
+ methodNames?: string[]
76
+ }
77
+
78
+ /**
79
+ * Privacy key pair derived from wallet
80
+ */
81
+ export interface NEARPrivacyKeyPair {
82
+ /** Spending private key */
83
+ spendingPrivateKey: HexString
84
+ /** Spending public key */
85
+ spendingPublicKey: HexString
86
+ /** Viewing private key */
87
+ viewingPrivateKey: HexString
88
+ /** Viewing public key */
89
+ viewingPublicKey: HexString
90
+ /** Derivation path used */
91
+ derivationPath: string
92
+ }
93
+
94
+ /**
95
+ * Stealth address with derived keys
96
+ */
97
+ export interface NEARStealthAddressWithKeys {
98
+ /** The stealth address */
99
+ stealthAddress: StealthAddress
100
+ /** NEAR implicit account ID */
101
+ stealthAccountId: string
102
+ /** Private key for spending (derived) */
103
+ privateKey?: HexString
104
+ }
105
+
106
+ /**
107
+ * Privacy transaction to sign
108
+ */
109
+ export interface NEARPrivacyTransaction {
110
+ /** Receiver account ID */
111
+ receiverId: string
112
+ /** Transaction actions */
113
+ actions: NEARAction[]
114
+ /** Announcement memo for stealth address */
115
+ announcementMemo?: string
116
+ /** Is this from a stealth account */
117
+ fromStealthAccount?: boolean
118
+ /** Stealth account keypair (if signing from stealth) */
119
+ stealthKeyPair?: {
120
+ publicKey: HexString
121
+ privateKey: HexString
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Signed privacy transaction
127
+ */
128
+ export interface NEARSignedPrivacyTransaction {
129
+ /** Serialized signed transaction */
130
+ signedTx: string
131
+ /** Transaction hash */
132
+ txHash: string
133
+ /** Sender account ID */
134
+ senderId: string
135
+ /** Receiver account ID */
136
+ receiverId: string
137
+ }
138
+
139
+ /**
140
+ * Viewing key export format
141
+ */
142
+ export interface NEARViewingKeyExport {
143
+ /** Network */
144
+ network: NEARNetwork
145
+ /** Viewing public key */
146
+ viewingPublicKey: HexString
147
+ /** Viewing private key (encrypted or raw) */
148
+ viewingPrivateKey: HexString
149
+ /** Associated spending public key */
150
+ spendingPublicKey: HexString
151
+ /** Creation timestamp */
152
+ createdAt: number
153
+ /** Label */
154
+ label?: string
155
+ }
156
+
157
+ // ─── NEAR Wallet Adapter ──────────────────────────────────────────────────────
158
+
159
+ /**
160
+ * NEAR Wallet Adapter with Privacy Support
161
+ *
162
+ * Provides wallet connection and privacy operations for NEAR.
163
+ */
164
+ export class NEARWalletAdapter extends BaseWalletAdapter {
165
+ readonly chain: ChainId = 'near'
166
+ readonly name: string
167
+
168
+ private config: NEARWalletAdapterConfig
169
+ private privacyKeyPair: NEARPrivacyKeyPair | null = null
170
+ private stealthAddresses: Map<string, NEARStealthAddressWithKeys> = new Map()
171
+
172
+ constructor(config: NEARWalletAdapterConfig) {
173
+ super()
174
+ this.config = config
175
+ this.name = config.walletName ?? `near-${config.network}`
176
+ }
177
+
178
+ // ─── Connection ─────────────────────────────────────────────────────────────
179
+
180
+ /**
181
+ * Connect to NEAR wallet
182
+ */
183
+ async connect(options?: NEARConnectOptions): Promise<void> {
184
+ this._connectionState = 'connecting'
185
+
186
+ try {
187
+ // In a real implementation, this would connect to NEAR Wallet Selector
188
+ // For now, we simulate the connection
189
+
190
+ // Check if window.near exists (browser extension)
191
+ if (typeof window !== 'undefined' && (window as any).near) {
192
+ const near = (window as any).near
193
+ const account = await near.requestSignIn({
194
+ contractId: options?.contractId,
195
+ methodNames: options?.methodNames,
196
+ })
197
+
198
+ this._address = account.accountId
199
+ this._publicKey = `0x${account.publicKey}` as HexString
200
+ } else {
201
+ // Mock connection for non-browser environments
202
+ throw new WalletError(
203
+ 'NEAR wallet not available',
204
+ WalletErrorCode.NOT_INSTALLED
205
+ )
206
+ }
207
+
208
+ this._connectionState = 'connected'
209
+ this.emitConnect(this._address, this.chain)
210
+ } catch (error) {
211
+ this._connectionState = 'error'
212
+
213
+ if (error instanceof WalletError) {
214
+ throw error
215
+ }
216
+
217
+ throw new WalletError(
218
+ `Failed to connect to NEAR wallet: ${error}`,
219
+ WalletErrorCode.CONNECTION_FAILED
220
+ )
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Disconnect from NEAR wallet
226
+ */
227
+ async disconnect(): Promise<void> {
228
+ if (typeof window !== 'undefined' && (window as any).near) {
229
+ await (window as any).near.signOut()
230
+ }
231
+
232
+ this.privacyKeyPair = null
233
+ this.stealthAddresses.clear()
234
+ this.setDisconnected('User disconnected')
235
+ }
236
+
237
+ // ─── Standard Wallet Operations ─────────────────────────────────────────────
238
+
239
+ /**
240
+ * Sign a message
241
+ */
242
+ async signMessage(message: Uint8Array): Promise<Signature> {
243
+ this.requireConnected()
244
+
245
+ if (typeof window !== 'undefined' && (window as any).near) {
246
+ const near = (window as any).near
247
+ const result = await near.signMessage({
248
+ message: Buffer.from(message).toString('base64'),
249
+ recipient: this._address,
250
+ })
251
+
252
+ return {
253
+ signature: `0x${result.signature}` as HexString,
254
+ publicKey: this._publicKey as HexString,
255
+ recoveryId: 0,
256
+ }
257
+ }
258
+
259
+ throw new WalletError(
260
+ 'NEAR wallet not available for signing',
261
+ WalletErrorCode.SIGNING_FAILED
262
+ )
263
+ }
264
+
265
+ /**
266
+ * Sign a transaction
267
+ */
268
+ async signTransaction(tx: UnsignedTransaction): Promise<SignedTransaction> {
269
+ this.requireConnected()
270
+
271
+ const signature = await this.signMessage(
272
+ new TextEncoder().encode(JSON.stringify(tx.data))
273
+ )
274
+
275
+ return {
276
+ unsigned: tx,
277
+ signatures: [signature],
278
+ serialized: `0x${Buffer.from(JSON.stringify(tx)).toString('hex')}` as HexString,
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Sign and send a transaction
284
+ */
285
+ async signAndSendTransaction(tx: UnsignedTransaction): Promise<TransactionReceipt> {
286
+ this.requireConnected()
287
+
288
+ if (typeof window !== 'undefined' && (window as any).near) {
289
+ const near = (window as any).near
290
+ const txData = tx.data as { receiverId?: string; actions?: unknown[] }
291
+ const result = await near.signAndSendTransaction({
292
+ receiverId: txData.receiverId ?? this._address,
293
+ actions: txData.actions ?? tx.data,
294
+ })
295
+
296
+ return {
297
+ txHash: `0x${result.transaction.hash}` as HexString,
298
+ status: result.status ? 'confirmed' : 'failed',
299
+ blockNumber: BigInt(result.transaction.block_height ?? 0),
300
+ feeUsed: BigInt(result.transaction.gas_used ?? 0),
301
+ timestamp: Date.now(),
302
+ }
303
+ }
304
+
305
+ throw new WalletError(
306
+ 'NEAR wallet not available for transaction',
307
+ WalletErrorCode.TRANSACTION_FAILED
308
+ )
309
+ }
310
+
311
+ /**
312
+ * Get native NEAR balance
313
+ */
314
+ async getBalance(): Promise<bigint> {
315
+ this.requireConnected()
316
+
317
+ // In a real implementation, query the RPC
318
+ // For now, return 0
319
+ return 0n
320
+ }
321
+
322
+ /**
323
+ * Get token balance
324
+ */
325
+ async getTokenBalance(_asset: Asset): Promise<bigint> {
326
+ this.requireConnected()
327
+
328
+ // In a real implementation, query the token contract using _asset.contract
329
+ // For now, return 0
330
+ return 0n
331
+ }
332
+
333
+ // ─── Privacy Operations ─────────────────────────────────────────────────────
334
+
335
+ /**
336
+ * Derive privacy keys from wallet
337
+ *
338
+ * Uses a deterministic derivation from the wallet's signing capability
339
+ * to generate privacy keys without exposing the seed.
340
+ */
341
+ async derivePrivacyKeys(label: string = 'default'): Promise<NEARPrivacyKeyPair> {
342
+ this.requireConnected()
343
+
344
+ // Derive keys using signature-based derivation
345
+ // This works even when the wallet doesn't expose the seed
346
+ const derivationPath = `sip/near/${this.config.network}/${label}`
347
+ const derivationMessage = new TextEncoder().encode(
348
+ `SIP Privacy Key Derivation: ${derivationPath}`
349
+ )
350
+
351
+ // Sign the derivation message to get entropy
352
+ const signature = await this.signMessage(derivationMessage)
353
+ const entropy = hexToBytes(signature.signature.slice(2))
354
+
355
+ // Derive spending key from first half
356
+ const spendingEntropy = sha256(new Uint8Array([...entropy.slice(0, 32), 0x01]))
357
+ const spendingPrivateKeyScalar = bytesToBigIntLE(spendingEntropy) % ED25519_ORDER
358
+ const spendingPrivateKeyBytes = bigIntToBytesLE(spendingPrivateKeyScalar, 32)
359
+ const spendingPublicKeyBytes = ed25519.getPublicKey(spendingPrivateKeyBytes)
360
+
361
+ // Derive viewing key from second half
362
+ const viewingEntropy = sha256(new Uint8Array([...entropy.slice(32, 64), 0x02]))
363
+ const viewingPrivateKeyScalar = bytesToBigIntLE(viewingEntropy) % ED25519_ORDER
364
+ const viewingPrivateKeyBytes = bigIntToBytesLE(viewingPrivateKeyScalar, 32)
365
+ const viewingPublicKeyBytes = ed25519.getPublicKey(viewingPrivateKeyBytes)
366
+
367
+ const keyPair: NEARPrivacyKeyPair = {
368
+ spendingPrivateKey: `0x${bytesToHex(spendingPrivateKeyBytes)}` as HexString,
369
+ spendingPublicKey: `0x${bytesToHex(spendingPublicKeyBytes)}` as HexString,
370
+ viewingPrivateKey: `0x${bytesToHex(viewingPrivateKeyBytes)}` as HexString,
371
+ viewingPublicKey: `0x${bytesToHex(viewingPublicKeyBytes)}` as HexString,
372
+ derivationPath,
373
+ }
374
+
375
+ this.privacyKeyPair = keyPair
376
+ return keyPair
377
+ }
378
+
379
+ /**
380
+ * Generate a stealth meta-address
381
+ *
382
+ * Creates a meta-address that can be shared publicly for receiving
383
+ * private payments.
384
+ */
385
+ async generateStealthMetaAddress(label?: string): Promise<{
386
+ metaAddress: StealthMetaAddress
387
+ encoded: string
388
+ viewingPrivateKey: HexString
389
+ spendingPrivateKey: HexString
390
+ }> {
391
+ // Use derived keys if available, otherwise derive new ones
392
+ const keys = this.privacyKeyPair ?? await this.derivePrivacyKeys(label)
393
+
394
+ // Create meta-address from derived keys
395
+ const metaAddress: StealthMetaAddress = {
396
+ chain: 'near',
397
+ spendingKey: keys.spendingPublicKey,
398
+ viewingKey: keys.viewingPublicKey,
399
+ }
400
+
401
+ const encoded = encodeNEARStealthMetaAddress(metaAddress)
402
+
403
+ return {
404
+ metaAddress,
405
+ encoded,
406
+ viewingPrivateKey: keys.viewingPrivateKey,
407
+ spendingPrivateKey: keys.spendingPrivateKey,
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Generate a fresh stealth address for receiving
413
+ *
414
+ * Creates a one-time stealth address from a meta-address.
415
+ */
416
+ generateStealthAddress(metaAddress: StealthMetaAddress | string): NEARStealthAddressWithKeys {
417
+ const meta = typeof metaAddress === 'string'
418
+ ? parseNEARStealthMetaAddress(metaAddress)
419
+ : metaAddress
420
+
421
+ const { stealthAddress, implicitAccountId } = generateNEARStealthAddress(meta)
422
+
423
+ const result: NEARStealthAddressWithKeys = {
424
+ stealthAddress,
425
+ stealthAccountId: implicitAccountId,
426
+ }
427
+
428
+ // Store for later spending
429
+ this.stealthAddresses.set(implicitAccountId, result)
430
+
431
+ return result
432
+ }
433
+
434
+ /**
435
+ * Check if a stealth address belongs to this wallet
436
+ */
437
+ async checkStealthAddress(
438
+ stealthAddress: StealthAddress
439
+ ): Promise<boolean> {
440
+ const keys = this.privacyKeyPair ?? await this.derivePrivacyKeys()
441
+
442
+ return checkNEARStealthAddress(
443
+ stealthAddress,
444
+ keys.spendingPublicKey,
445
+ keys.viewingPrivateKey
446
+ )
447
+ }
448
+
449
+ /**
450
+ * Derive the private key for a stealth address
451
+ *
452
+ * Only works for stealth addresses that belong to this wallet.
453
+ */
454
+ async deriveStealthPrivateKey(
455
+ stealthAddress: StealthAddress
456
+ ): Promise<HexString> {
457
+ const keys = this.privacyKeyPair ?? await this.derivePrivacyKeys()
458
+
459
+ const isOwner = await this.checkStealthAddress(stealthAddress)
460
+ if (!isOwner) {
461
+ throw new WalletError(
462
+ 'Stealth address does not belong to this wallet',
463
+ WalletErrorCode.INVALID_TRANSACTION
464
+ )
465
+ }
466
+
467
+ const recovery = deriveNEARStealthPrivateKey(
468
+ stealthAddress,
469
+ keys.spendingPrivateKey,
470
+ keys.viewingPrivateKey
471
+ )
472
+
473
+ return recovery.privateKey
474
+ }
475
+
476
+ /**
477
+ * Sign a privacy transaction
478
+ *
479
+ * Signs a transaction for privacy operations, including stealth transfers.
480
+ */
481
+ async signPrivacyTransaction(
482
+ tx: NEARPrivacyTransaction
483
+ ): Promise<NEARSignedPrivacyTransaction> {
484
+ // If from stealth account, use the stealth keypair
485
+ if (tx.fromStealthAccount && tx.stealthKeyPair) {
486
+ return this.signWithStealthKey(tx, tx.stealthKeyPair)
487
+ }
488
+
489
+ // Otherwise, sign with main wallet
490
+ this.requireConnected()
491
+
492
+ const unsigned: UnsignedTransaction = {
493
+ chain: 'near',
494
+ data: {
495
+ signerId: this._address,
496
+ receiverId: tx.receiverId,
497
+ actions: tx.actions,
498
+ },
499
+ metadata: {
500
+ network: this.config.network,
501
+ announcementMemo: tx.announcementMemo,
502
+ },
503
+ }
504
+
505
+ const signed = await this.signTransaction(unsigned)
506
+
507
+ return {
508
+ signedTx: signed.serialized,
509
+ txHash: sha256Hash(signed.serialized),
510
+ senderId: this._address,
511
+ receiverId: tx.receiverId,
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Sign with a stealth key
517
+ */
518
+ private async signWithStealthKey(
519
+ tx: NEARPrivacyTransaction,
520
+ keyPair: { publicKey: HexString; privateKey: HexString }
521
+ ): Promise<NEARSignedPrivacyTransaction> {
522
+ // Derive the implicit account ID from the public key
523
+ const publicKeyBytes = hexToBytes(keyPair.publicKey.slice(2))
524
+ const accountId = bytesToHex(publicKeyBytes)
525
+
526
+ // Create the transaction to sign (convert bigints to strings for serialization)
527
+ const txData = {
528
+ signerId: accountId,
529
+ receiverId: tx.receiverId,
530
+ actions: tx.actions.map(action => ({
531
+ type: action.type,
532
+ params: Object.fromEntries(
533
+ Object.entries(action.params).map(([k, v]) => [
534
+ k,
535
+ typeof v === 'bigint' ? v.toString() : v,
536
+ ])
537
+ ),
538
+ })),
539
+ publicKey: keyPair.publicKey,
540
+ }
541
+
542
+ // Sign with ed25519
543
+ const message = new TextEncoder().encode(JSON.stringify(txData))
544
+ const privateKeyBytes = hexToBytes(keyPair.privateKey.slice(2))
545
+
546
+ // Note: In a real implementation, you'd use proper NEAR transaction serialization
547
+ const signature = ed25519.sign(message, privateKeyBytes)
548
+ const signedTx = JSON.stringify({
549
+ ...txData,
550
+ signature: bytesToHex(signature),
551
+ })
552
+
553
+ return {
554
+ signedTx,
555
+ txHash: sha256Hash(signedTx),
556
+ senderId: accountId,
557
+ receiverId: tx.receiverId,
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Export viewing key
563
+ *
564
+ * Exports the viewing key for sharing with auditors or other services.
565
+ */
566
+ async exportViewingKey(label?: string): Promise<NEARViewingKeyExport> {
567
+ const keys = this.privacyKeyPair ?? await this.derivePrivacyKeys(label)
568
+
569
+ return {
570
+ network: this.config.network,
571
+ viewingPublicKey: keys.viewingPublicKey,
572
+ viewingPrivateKey: keys.viewingPrivateKey,
573
+ spendingPublicKey: keys.spendingPublicKey,
574
+ createdAt: Date.now(),
575
+ label,
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Get all tracked stealth addresses
581
+ */
582
+ getStealthAddresses(): Map<string, NEARStealthAddressWithKeys> {
583
+ return new Map(this.stealthAddresses)
584
+ }
585
+
586
+ /**
587
+ * Get network
588
+ */
589
+ getNetwork(): NEARNetwork {
590
+ return this.config.network
591
+ }
592
+
593
+ /**
594
+ * Check if privacy keys are derived
595
+ */
596
+ hasPrivacyKeys(): boolean {
597
+ return this.privacyKeyPair !== null
598
+ }
599
+ }
600
+
601
+ // ─── Utility Functions ────────────────────────────────────────────────────────
602
+
603
+ const ED25519_ORDER = 2n ** 252n + 27742317777372353535851937790883648493n
604
+
605
+ function bytesToBigIntLE(bytes: Uint8Array): bigint {
606
+ let result = 0n
607
+ for (let i = bytes.length - 1; i >= 0; i--) {
608
+ result = (result << 8n) | BigInt(bytes[i])
609
+ }
610
+ return result
611
+ }
612
+
613
+ function bigIntToBytesLE(n: bigint, length: number): Uint8Array {
614
+ const bytes = new Uint8Array(length)
615
+ let temp = n
616
+ for (let i = 0; i < length; i++) {
617
+ bytes[i] = Number(temp & 0xffn)
618
+ temp = temp >> 8n
619
+ }
620
+ return bytes
621
+ }
622
+
623
+ function sha256Hash(data: string): string {
624
+ const hash = sha256(new TextEncoder().encode(data))
625
+ return `0x${bytesToHex(hash)}`
626
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * NEAR Wallet Adapter with Privacy Support
3
+ *
4
+ * Provides wallet connection and privacy operations for NEAR.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+
9
+ export {
10
+ NEARWalletAdapter,
11
+ type NEARWalletAdapterConfig,
12
+ type NEARConnectOptions,
13
+ type NEARPrivacyKeyPair,
14
+ type NEARStealthAddressWithKeys,
15
+ type NEARPrivacyTransaction,
16
+ type NEARSignedPrivacyTransaction,
17
+ type NEARViewingKeyExport,
18
+ } from './adapter'
19
+
20
+ // Wallet Selector integration
21
+ export {
22
+ PrivacyWalletSelector,
23
+ createPrivacyWalletSelector,
24
+ createMainnetPrivacySelector,
25
+ createTestnetPrivacySelector,
26
+ type WalletSelector,
27
+ type WalletSelectorState,
28
+ type Wallet,
29
+ type WalletAction,
30
+ type WalletTransactionResult,
31
+ type SignAndSendTransactionParams,
32
+ type SignAndSendTransactionsParams,
33
+ type SignMessageParams,
34
+ type SignedMessage,
35
+ type PrivacyWalletSelectorConfig,
36
+ type PrivacyKeyPair,
37
+ type StealthAddressResult,
38
+ type PrivateTransferParams,
39
+ type PrivateTransferResult,
40
+ type WalletPrivacyCapabilities,
41
+ type ViewingKeyExport,
42
+ } from './wallet-selector'
43
+
44
+ // MyNearWallet integration
45
+ export {
46
+ MyNearWalletPrivacy,
47
+ createMyNearWalletPrivacy,
48
+ createMainnetMyNearWallet,
49
+ createTestnetMyNearWallet,
50
+ parseMyNearWalletCallback,
51
+ MY_NEAR_WALLET_MAINNET,
52
+ MY_NEAR_WALLET_TESTNET,
53
+ type MyNearWalletConfig,
54
+ type MyNearWalletConnectionState,
55
+ type MyNearWalletPrivacyKeys,
56
+ type MyNearWalletStealthAddress,
57
+ type MyNearWalletPrivateTransferParams,
58
+ type TransactionPreview,
59
+ type MyNearWalletCallbackResult,
60
+ type MyNearWalletViewingKeyExport,
61
+ type LedgerStatus,
62
+ } from './my-near-wallet'
63
+
64
+ // Meteor Wallet integration
65
+ export {
66
+ MeteorWalletPrivacy,
67
+ createMeteorWalletPrivacy,
68
+ createMainnetMeteorWallet,
69
+ createTestnetMeteorWallet,
70
+ isMeteorWalletAvailable,
71
+ MeteorWalletError,
72
+ MeteorErrorCode,
73
+ METEOR_DEEP_LINK_SCHEME,
74
+ METEOR_APP_LINK_MAINNET,
75
+ METEOR_APP_LINK_TESTNET,
76
+ METEOR_PROVIDER_KEY,
77
+ type MeteorWalletProvider,
78
+ type MeteorWalletConfig,
79
+ type MeteorConnectionState,
80
+ type MeteorSigningMode,
81
+ type MeteorPrivacyKeys,
82
+ type MeteorPrivateTransferParams,
83
+ type TransactionSimulation,
84
+ type MeteorTransactionResult,
85
+ type MeteorAccountInfo,
86
+ } from './meteor-wallet'