@meshconnect/uwc-bitcoin 0.2.4 → 0.3.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA;AACxD,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAA;AACzE,YAAY,EACV,2BAA2B,EAC3B,4BAA4B,EAC7B,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAClD,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AACxD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -1,2 +1,5 @@
1
1
  export { BitcoinNamespace, assertBitcoinNetwork, BITCOIN_NAMESPACE } from './bitcoin-namespace';
2
+ export { WalletStandardBitcoinAdapter } from './adapters/wallet-standard';
3
+ export { OkxBitcoinAdapter } from './adapters/okx';
4
+ export { bytesToHex, hexToBytes } from './encoding';
2
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAA;AAKzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meshconnect/uwc-bitcoin",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "Mesh-owned Bitcoin (bip122) namespace module for Universal Wallet Connector — network-specific logic (PSBT, address/network handling, mempool broadcast) with pluggable transport adapters (Wallet Standard bitcoin:* and WalletConnect bip122), consumed by the injected and walletConnect transport connectors",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -16,7 +16,8 @@
16
16
  "src"
17
17
  ],
18
18
  "dependencies": {
19
- "@meshconnect/uwc-types": "0.26.1"
19
+ "@meshconnect/uwc-constants": "0.7.5",
20
+ "@meshconnect/uwc-types": "0.27.0"
20
21
  },
21
22
  "devDependencies": {
22
23
  "typescript": "^5.9.3"
package/src/adapter.ts CHANGED
@@ -1,23 +1,27 @@
1
1
  import type {
2
2
  BitcoinAccount,
3
+ BitcoinPsbtSignRequest,
4
+ BitcoinSendTransferRequest,
3
5
  BitcoinSignMessageParams,
4
- SignatureType
6
+ SignatureType,
7
+ TransactionResult
5
8
  } from '@meshconnect/uwc-types'
6
9
 
7
10
  /**
8
11
  * The seam between the Bitcoin namespace module and a single transport.
9
12
  *
10
- * A concrete adapter (Phase 3) is constructed by its transport bound to an
13
+ * A concrete adapter is constructed by its transport bound to an
11
14
  * already-connected provider/session — Wallet Standard `bitcoin:*` for the
12
15
  * injected transport, WalletConnect bip122 for the WalletConnect transport —
13
16
  * so the port carries no `connect`/provider argument: connecting is the
14
17
  * transport's job. Each adapter converts between these transport-agnostic
15
- * domain shapes and its wallet's native interface (e.g. hex ↔ `Uint8Array`).
18
+ * domain shapes and its wallet's native interface (e.g. hex/base64 strings ↔
19
+ * `Uint8Array`).
16
20
  *
17
- * Phase 2 locks the grounded verify-flow methods. `signPsbt` (Path B, returns a
18
- * signed PSBT the module then finalizes + broadcasts) and `sendTransfer`
19
- * (Path A) are added alongside their concrete adapters in Phase 3 rather than
20
- * guessed here.
21
+ * `getAccounts` + `signMessage` are the always-present verify-flow methods.
22
+ * `signPsbt` and `sendTransfer` are optional because they map to distinct wallet
23
+ * paths — a Wallet Standard wallet signs a PSBT (Path B); a WalletConnect wallet
24
+ * does a high-level `sendTransfer` (Path A) — and not every adapter offers both.
21
25
  */
22
26
  export interface BitcoinTransportAdapter {
23
27
  /** Enumerate the bip122 accounts available on the connected session. */
@@ -26,6 +30,20 @@ export interface BitcoinTransportAdapter {
26
30
  /** Sign a message with the given account. */
27
31
  signMessage(params: BitcoinSignMessageParams): Promise<SignatureType>
28
32
 
33
+ /**
34
+ * Sign a PSBT (Path B). Returns the wallet-signed PSBT, base64-encoded — the
35
+ * wallet does NOT broadcast; finalizing + broadcasting is a separate step.
36
+ * Optional: only adapters whose wallet exposes PSBT signing implement it.
37
+ */
38
+ signPsbt?(request: BitcoinPsbtSignRequest): Promise<string>
39
+
40
+ /**
41
+ * High-level transfer (Path A): the wallet does coin selection, fee, signing,
42
+ * and broadcast, returning a txid. Optional: only adapters whose transport
43
+ * offers it (e.g. WalletConnect `sendTransfer`) implement it.
44
+ */
45
+ sendTransfer?(request: BitcoinSendTransferRequest): Promise<TransactionResult>
46
+
29
47
  /** Release any session resources the adapter holds. Optional. */
30
48
  disconnect?(): Promise<void>
31
49
  }
@@ -0,0 +1,176 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { WalletConnectorError } from '@meshconnect/uwc-types'
3
+ import { OkxBitcoinAdapter, type OkxBitcoinProvider } from './okx'
4
+ import {
5
+ base64ToBytes,
6
+ bytesToBase64,
7
+ bytesToHex,
8
+ hexToBytes
9
+ } from '../encoding'
10
+
11
+ const account = { address: 'bc1qokx', publicKey: '02aabbcc' }
12
+
13
+ /** A fake OKX injected bitcoin provider wired via vi mocks. */
14
+ const fakeProvider = (
15
+ overrides: Partial<OkxBitcoinProvider> = {}
16
+ ): OkxBitcoinProvider => ({
17
+ requestAccounts: vi.fn().mockResolvedValue([account.address]),
18
+ getAccounts: vi.fn().mockResolvedValue([account.address]),
19
+ getPublicKey: vi.fn().mockResolvedValue(account.publicKey),
20
+ signMessage: vi.fn().mockResolvedValue('c2lnbmF0dXJl'),
21
+ signPsbt: vi.fn().mockResolvedValue('abcdef01'),
22
+ on: vi.fn(),
23
+ removeListener: vi.fn(),
24
+ ...overrides
25
+ })
26
+
27
+ describe('OkxBitcoinAdapter', () => {
28
+ it('getAccounts prompts via requestAccounts and pairs the active public key', async () => {
29
+ const provider = fakeProvider()
30
+ const accounts = await new OkxBitcoinAdapter(provider).getAccounts()
31
+
32
+ expect(provider.requestAccounts).toHaveBeenCalledOnce()
33
+ expect(accounts).toEqual([{ address: 'bc1qokx', publicKey: '02aabbcc' }])
34
+ })
35
+
36
+ it('getAccounts tolerates a getPublicKey failure (empty key, not a throw)', async () => {
37
+ const provider = fakeProvider({
38
+ getPublicKey: vi.fn().mockRejectedValue(new Error('locked'))
39
+ })
40
+ const accounts = await new OkxBitcoinAdapter(provider).getAccounts()
41
+ expect(accounts).toEqual([{ address: 'bc1qokx', publicKey: '' }])
42
+ })
43
+
44
+ it('signMessage maps bip322 → bip322-simple and passes the base64 signature through', async () => {
45
+ const provider = fakeProvider()
46
+ const adapter = new OkxBitcoinAdapter(provider)
47
+
48
+ const result = await adapter.signMessage({
49
+ account: { address: account.address, publicKey: account.publicKey },
50
+ message: 'verify me',
51
+ protocol: 'bip322'
52
+ })
53
+
54
+ expect(provider.signMessage).toHaveBeenCalledWith(
55
+ 'verify me',
56
+ 'bip322-simple'
57
+ )
58
+ expect(result).toEqual({ type: 'standard', signature: 'c2lnbmF0dXJl' })
59
+ })
60
+
61
+ it('signMessage defaults to ecdsa when no protocol is given', async () => {
62
+ const provider = fakeProvider()
63
+ await new OkxBitcoinAdapter(provider).signMessage({
64
+ account: { address: account.address, publicKey: account.publicKey },
65
+ message: 'hi'
66
+ })
67
+ expect(provider.signMessage).toHaveBeenCalledWith('hi', 'ecdsa')
68
+ })
69
+
70
+ it('signMessage throws when the provider returns no signature', async () => {
71
+ const provider = fakeProvider({
72
+ signMessage: vi.fn().mockResolvedValue('')
73
+ })
74
+ await expect(
75
+ new OkxBitcoinAdapter(provider).signMessage({
76
+ account: { address: account.address, publicKey: account.publicKey },
77
+ message: 'hi'
78
+ })
79
+ ).rejects.toBeInstanceOf(WalletConnectorError)
80
+ })
81
+
82
+ it('signPsbt converts base64 → hex for OKX and hex → base64 on the way back', async () => {
83
+ // Round-trip fixture: a base64 PSBT whose hex the mock echoes back signed.
84
+ const psbtBytes = new Uint8Array([0x70, 0x73, 0x62, 0x74, 0xff])
85
+ const psbtB64 = bytesToBase64(psbtBytes)
86
+ const signedBytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef])
87
+ const provider = fakeProvider({
88
+ signPsbt: vi.fn().mockResolvedValue(bytesToHex(signedBytes))
89
+ })
90
+
91
+ const result = await new OkxBitcoinAdapter(provider).signPsbt({
92
+ from: account.address,
93
+ psbt: psbtB64
94
+ })
95
+
96
+ // OKX received the PSBT as HEX (autoFinalized:false = sign-only).
97
+ expect(provider.signPsbt).toHaveBeenCalledWith(bytesToHex(psbtBytes), {
98
+ autoFinalized: false
99
+ })
100
+ // ...and we returned it as base64.
101
+ expect(result).toBe(bytesToBase64(signedBytes))
102
+ expect(base64ToBytes(result)).toEqual(signedBytes)
103
+ })
104
+
105
+ it('maps inputsToSign → toSignInputs (index/address + numeric sighash)', async () => {
106
+ const provider = fakeProvider()
107
+ await new OkxBitcoinAdapter(provider).signPsbt({
108
+ from: 'bc1qokx',
109
+ psbt: bytesToBase64(new Uint8Array([1, 2])),
110
+ inputsToSign: [
111
+ { address: 'bc1qa', signingIndexes: [0, 2] },
112
+ {
113
+ address: 'bc1qb',
114
+ signingIndexes: [1],
115
+ sigHash: 'SINGLE|ANYONECANPAY'
116
+ }
117
+ ]
118
+ })
119
+
120
+ expect(provider.signPsbt).toHaveBeenCalledWith(expect.any(String), {
121
+ autoFinalized: false,
122
+ toSignInputs: [
123
+ { index: 0, address: 'bc1qa' },
124
+ { index: 2, address: 'bc1qa' },
125
+ { index: 1, address: 'bc1qb', sighashTypes: [0x83] }
126
+ ]
127
+ })
128
+ })
129
+
130
+ it('omits toSignInputs entirely when no inputsToSign is given', async () => {
131
+ const provider = fakeProvider()
132
+ await new OkxBitcoinAdapter(provider).signPsbt({
133
+ from: 'bc1qokx',
134
+ psbt: bytesToBase64(new Uint8Array([1, 2]))
135
+ })
136
+ expect(provider.signPsbt).toHaveBeenCalledWith(expect.any(String), {
137
+ autoFinalized: false
138
+ })
139
+ })
140
+
141
+ it('signPsbt throws when the provider returns no PSBT', async () => {
142
+ const provider = fakeProvider({
143
+ signPsbt: vi.fn().mockResolvedValue('')
144
+ })
145
+ await expect(
146
+ new OkxBitcoinAdapter(provider).signPsbt({
147
+ from: account.address,
148
+ psbt: bytesToBase64(new Uint8Array([1, 2]))
149
+ })
150
+ ).rejects.toBeInstanceOf(WalletConnectorError)
151
+ })
152
+
153
+ it('disconnect resolves (OKX has no disconnect RPC)', async () => {
154
+ await expect(
155
+ new OkxBitcoinAdapter(fakeProvider()).disconnect()
156
+ ).resolves.toBeUndefined()
157
+ })
158
+ })
159
+
160
+ describe('hexToBytes', () => {
161
+ it('round-trips with bytesToHex, tolerating a 0x / 0X prefix', () => {
162
+ const bytes = new Uint8Array([0x00, 0x0f, 0xa0, 0xff])
163
+ expect(hexToBytes(bytesToHex(bytes))).toEqual(bytes)
164
+ expect(hexToBytes('0x' + bytesToHex(bytes))).toEqual(bytes)
165
+ expect(hexToBytes('0X' + bytesToHex(bytes))).toEqual(bytes)
166
+ })
167
+
168
+ it('throws on odd-length hex', () => {
169
+ expect(() => hexToBytes('abc')).toThrow(/odd-length/)
170
+ })
171
+
172
+ it('throws on non-hex characters (no silent 0-coercion)', () => {
173
+ expect(() => hexToBytes('zz')).toThrow(/non-hex/)
174
+ expect(() => hexToBytes('12g4')).toThrow(/non-hex/)
175
+ })
176
+ })
@@ -0,0 +1,155 @@
1
+ import type {
2
+ BitcoinAccount,
3
+ BitcoinPsbtSignRequest,
4
+ BitcoinSigHash,
5
+ BitcoinSignMessageParams,
6
+ SignatureType
7
+ } from '@meshconnect/uwc-types'
8
+ import { WalletConnectorError } from '@meshconnect/uwc-types'
9
+ import type { BitcoinTransportAdapter } from '../adapter'
10
+ import {
11
+ base64ToBytes,
12
+ bytesToBase64,
13
+ bytesToHex,
14
+ hexToBytes
15
+ } from '../encoding'
16
+
17
+ /**
18
+ * The subset of OKX's injected Bitcoin provider this adapter drives
19
+ * (`window.okxwallet.bitcoin`). OKX does NOT expose Bitcoin through Wallet
20
+ * Standard — only this legacy injected provider — so it needs a dedicated
21
+ * adapter, not `WalletStandardBitcoinAdapter`.
22
+ *
23
+ * Wire conventions the provider follows:
24
+ * - `requestAccounts()` prompts + returns the authorized addresses; the caller
25
+ * pairs `getPublicKey()` for the active account's compressed key (hex).
26
+ * - `signMessage(msg, type)` returns a base64 signature.
27
+ * - `signPsbt(psbtHex, options)` takes AND returns PSBT as HEX — so this adapter
28
+ * converts base64 ↔ hex at the boundary (our domain is base64/BIP-174).
29
+ */
30
+ export interface OkxBitcoinProvider {
31
+ /** Prompt for connection; returns the authorized addresses. */
32
+ requestAccounts(): Promise<string[]>
33
+ /** Non-prompting: the already-authorized addresses ([] if not connected). */
34
+ getAccounts(): Promise<string[]>
35
+ /** The active account's compressed public key, hex-encoded. */
36
+ getPublicKey(): Promise<string>
37
+ /** Sign a message; returns a base64 signature. */
38
+ signMessage(
39
+ message: string,
40
+ type?: 'ecdsa' | 'bip322-simple'
41
+ ): Promise<string>
42
+ /**
43
+ * Sign a PSBT (hex in, signed PSBT hex out). `toSignInputs` scopes which
44
+ * inputs to sign (index + expected address, optional sighash), mirroring the
45
+ * Wallet Standard adapter's `inputsToSign`; omitted → the wallet signs all it
46
+ * can.
47
+ */
48
+ signPsbt(
49
+ psbtHex: string,
50
+ options?: {
51
+ autoFinalized?: boolean
52
+ toSignInputs?: {
53
+ index: number
54
+ address: string
55
+ sighashTypes?: number[]
56
+ }[]
57
+ }
58
+ ): Promise<string>
59
+ on(event: string, handler: (accounts: string[]) => void): void
60
+ removeListener(event: string, handler: (accounts: string[]) => void): void
61
+ }
62
+
63
+ /** Bitcoin SIGHASH flag → numeric value (Bitcoin Core encoding) for the
64
+ * provider's `toSignInputs.sighashTypes`. */
65
+ const SIGHASH_VALUES: Record<BitcoinSigHash, number> = {
66
+ ALL: 0x01,
67
+ NONE: 0x02,
68
+ SINGLE: 0x03,
69
+ 'ALL|ANYONECANPAY': 0x81,
70
+ 'NONE|ANYONECANPAY': 0x82,
71
+ 'SINGLE|ANYONECANPAY': 0x83
72
+ }
73
+
74
+ /**
75
+ * OKX (legacy injected) Bitcoin transport adapter — the non-Wallet-Standard
76
+ * injected path. The injected transport resolves `window.okxwallet.bitcoin` by
77
+ * its `injectedId` and hands it here; this adapter maps our domain shapes onto
78
+ * the provider's methods.
79
+ *
80
+ * `sendTransfer` is intentionally not implemented — that is the WalletConnect
81
+ * high-level path. (OKX has `sendBitcoin`, but broadcast is out of scope here:
82
+ * this stays sign-only, matching `WalletStandardBitcoinAdapter`.)
83
+ */
84
+ export class OkxBitcoinAdapter implements BitcoinTransportAdapter {
85
+ constructor(private readonly provider: OkxBitcoinProvider) {}
86
+
87
+ async getAccounts(): Promise<BitcoinAccount[]> {
88
+ const addresses = await this.provider.requestAccounts()
89
+ // The provider exposes one active public key; pair it with the first
90
+ // (active) address. Tolerate a missing key rather than failing the connect.
91
+ let publicKey = ''
92
+ try {
93
+ publicKey = await this.provider.getPublicKey()
94
+ } catch {
95
+ publicKey = ''
96
+ }
97
+ return addresses.map((address, index) => ({
98
+ address,
99
+ publicKey: index === 0 ? publicKey : ''
100
+ }))
101
+ }
102
+
103
+ async signMessage(params: BitcoinSignMessageParams): Promise<SignatureType> {
104
+ // OKX signs with its OWN active account (no address param), so the caller's
105
+ // `params.account` is advisory here. Map our protocol name to the
106
+ // provider's ('bip322' → 'bip322-simple').
107
+ const type = params.protocol === 'bip322' ? 'bip322-simple' : 'ecdsa'
108
+ const signature = await this.provider.signMessage(params.message, type)
109
+ if (!signature) {
110
+ throw new WalletConnectorError({
111
+ type: 'unknown',
112
+ message: 'okx bitcoin: signMessage returned no signature'
113
+ })
114
+ }
115
+ // OKX returns a base64 signature — matches our contract.
116
+ return { type: 'standard', signature }
117
+ }
118
+
119
+ async signPsbt(request: BitcoinPsbtSignRequest): Promise<string> {
120
+ // Our domain is base64 (BIP-174); OKX speaks hex. autoFinalized:false keeps
121
+ // this sign-only (the wallet returns the signed-but-unfinalized PSBT).
122
+ const psbtHex = bytesToHex(base64ToBytes(request.psbt))
123
+ // Forward which inputs to sign (index + address, optional sighash) so the
124
+ // wallet signs exactly the requested set — matching the Wallet Standard
125
+ // adapter's `inputsToSign`. `request.from` isn't forwarded: OKX signs with
126
+ // its single active account, so there's no per-`from` routing. Omitted →
127
+ // OKX signs all inputs it can.
128
+ const toSignInputs = request.inputsToSign?.flatMap(input =>
129
+ input.signingIndexes.map(index => ({
130
+ index,
131
+ address: input.address,
132
+ ...(input.sigHash
133
+ ? { sighashTypes: [SIGHASH_VALUES[input.sigHash]] }
134
+ : {})
135
+ }))
136
+ )
137
+ const signedHex = await this.provider.signPsbt(psbtHex, {
138
+ autoFinalized: false,
139
+ ...(toSignInputs ? { toSignInputs } : {})
140
+ })
141
+ if (!signedHex) {
142
+ throw new WalletConnectorError({
143
+ type: 'unknown',
144
+ message: 'okx bitcoin: signPsbt returned no PSBT'
145
+ })
146
+ }
147
+ return bytesToBase64(hexToBytes(signedHex))
148
+ }
149
+
150
+ disconnect(): Promise<void> {
151
+ // OKX's injected provider has no disconnect RPC; clearing session state is
152
+ // the caller's job.
153
+ return Promise.resolve()
154
+ }
155
+ }
@@ -0,0 +1,148 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { WalletConnectorError } from '@meshconnect/uwc-types'
3
+ import {
4
+ WalletStandardBitcoinAdapter,
5
+ type WalletStandardBitcoinAccount,
6
+ type WalletStandardBitcoinWallet
7
+ } from './wallet-standard'
8
+ import { base64ToBytes, bytesToBase64, utf8ToBytes } from '../encoding'
9
+
10
+ const wsAccount: WalletStandardBitcoinAccount = {
11
+ address: 'bc1qpayment',
12
+ publicKey: new Uint8Array([2, 0xaa, 0xbb, 0xcc]),
13
+ purpose: 'payment'
14
+ }
15
+
16
+ /** A fake `bitcoin:*` wallet with all three features wired via vi mocks. */
17
+ const fakeWallet = (
18
+ overrides: Partial<WalletStandardBitcoinWallet['features']> = {}
19
+ ): WalletStandardBitcoinWallet => ({
20
+ name: 'Fake BTC Wallet',
21
+ accounts: [],
22
+ features: {
23
+ 'bitcoin:connect': {
24
+ connect: vi.fn().mockResolvedValue({ accounts: [wsAccount] })
25
+ },
26
+ 'bitcoin:signMessage': {
27
+ signMessage: vi.fn().mockResolvedValue([
28
+ {
29
+ signature: new Uint8Array([1, 2, 3]),
30
+ signedMessage: new Uint8Array()
31
+ }
32
+ ])
33
+ },
34
+ 'bitcoin:signTransaction': {
35
+ signTransaction: vi
36
+ .fn()
37
+ .mockResolvedValue([{ psbt: new Uint8Array([9, 8, 7]) }])
38
+ },
39
+ ...overrides
40
+ }
41
+ })
42
+
43
+ describe('WalletStandardBitcoinAdapter', () => {
44
+ it('getAccounts connects and maps accounts to hex publicKey', async () => {
45
+ const wallet = fakeWallet()
46
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
47
+
48
+ const accounts = await adapter.getAccounts()
49
+
50
+ expect(wallet.features['bitcoin:connect']!.connect).toHaveBeenCalledWith({
51
+ purposes: ['payment']
52
+ })
53
+ expect(accounts).toEqual([
54
+ { address: 'bc1qpayment', publicKey: '02aabbcc', purpose: 'payment' }
55
+ ])
56
+ })
57
+
58
+ it('signMessage encodes the message and returns a base64 standard signature', async () => {
59
+ const wallet = fakeWallet()
60
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
61
+
62
+ const sig = await adapter.signMessage({
63
+ account: { address: 'bc1qpayment', publicKey: '02aabbcc' },
64
+ message: 'verify me'
65
+ })
66
+
67
+ const call = (
68
+ wallet.features['bitcoin:signMessage']!.signMessage as ReturnType<
69
+ typeof vi.fn
70
+ >
71
+ ).mock.calls[0][0]
72
+ expect(call.account).toBe(wsAccount)
73
+ expect(call.message).toEqual(utf8ToBytes('verify me'))
74
+ expect(sig).toEqual({
75
+ type: 'standard',
76
+ signature: bytesToBase64(new Uint8Array([1, 2, 3]))
77
+ })
78
+ })
79
+
80
+ it('signPsbt round-trips base64 <-> bytes and returns the signed PSBT', async () => {
81
+ const wallet = fakeWallet()
82
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
83
+ const psbt = bytesToBase64(new Uint8Array([10, 20, 30]))
84
+
85
+ const signed = await adapter.signPsbt({ from: 'bc1qpayment', psbt })
86
+
87
+ const call = (
88
+ wallet.features['bitcoin:signTransaction']!.signTransaction as ReturnType<
89
+ typeof vi.fn
90
+ >
91
+ ).mock.calls[0][0]
92
+ expect(call.account).toBe(wsAccount)
93
+ expect(call.psbt).toEqual(base64ToBytes(psbt))
94
+ expect(signed).toBe(bytesToBase64(new Uint8Array([9, 8, 7])))
95
+ })
96
+
97
+ it('signPsbt maps inputsToSign accounts by address', async () => {
98
+ const wallet = fakeWallet()
99
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
100
+ await adapter.getAccounts()
101
+
102
+ await adapter.signPsbt({
103
+ from: 'bc1qpayment',
104
+ psbt: bytesToBase64(new Uint8Array([1])),
105
+ inputsToSign: [
106
+ { address: 'bc1qpayment', signingIndexes: [0], sigHash: 'ALL' }
107
+ ]
108
+ })
109
+
110
+ const call = (
111
+ wallet.features['bitcoin:signTransaction']!.signTransaction as ReturnType<
112
+ typeof vi.fn
113
+ >
114
+ ).mock.calls[0][0]
115
+ expect(call.inputsToSign).toEqual([
116
+ { account: wsAccount, signingIndexes: [0], sigHash: 'ALL' }
117
+ ])
118
+ })
119
+
120
+ it('throws for an address with no connected account', async () => {
121
+ const wallet = fakeWallet()
122
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
123
+
124
+ await expect(
125
+ adapter.signMessage({
126
+ account: { address: 'bc1qunknown', publicKey: '00' },
127
+ message: 'x'
128
+ })
129
+ ).rejects.toBeInstanceOf(WalletConnectorError)
130
+ })
131
+
132
+ it('throws when the wallet lacks the signTransaction feature', async () => {
133
+ const wallet = fakeWallet({ 'bitcoin:signTransaction': undefined })
134
+ const adapter = new WalletStandardBitcoinAdapter(wallet)
135
+
136
+ await expect(
137
+ adapter.signPsbt({
138
+ from: 'bc1qpayment',
139
+ psbt: bytesToBase64(new Uint8Array([1]))
140
+ })
141
+ ).rejects.toBeInstanceOf(WalletConnectorError)
142
+ })
143
+
144
+ it('does not implement sendTransfer (Wallet Standard has no high-level transfer)', () => {
145
+ const adapter = new WalletStandardBitcoinAdapter(fakeWallet())
146
+ expect(adapter.sendTransfer).toBeUndefined()
147
+ })
148
+ })