web3-tools-mcp 2.0.1 → 3.0.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.
Files changed (167) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +5 -0
  3. package/dist/anvil.d.ts +17 -19
  4. package/dist/anvil.d.ts.map +1 -1
  5. package/dist/anvil.js +124 -228
  6. package/dist/anvil.js.map +1 -1
  7. package/dist/chains.d.ts +9 -1
  8. package/dist/chains.d.ts.map +1 -1
  9. package/dist/chains.js +11 -2
  10. package/dist/chains.js.map +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/context.d.ts +22 -0
  14. package/dist/context.d.ts.map +1 -0
  15. package/dist/context.js +24 -0
  16. package/dist/context.js.map +1 -0
  17. package/dist/hosted.d.ts +12 -0
  18. package/dist/hosted.d.ts.map +1 -0
  19. package/dist/hosted.js +12 -0
  20. package/dist/hosted.js.map +1 -0
  21. package/dist/http-server.d.ts +13 -0
  22. package/dist/http-server.d.ts.map +1 -1
  23. package/dist/http-server.js +13 -4
  24. package/dist/http-server.js.map +1 -1
  25. package/dist/index.js +19 -15
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib.d.ts +24 -0
  28. package/dist/lib.d.ts.map +1 -0
  29. package/dist/lib.js +23 -0
  30. package/dist/lib.js.map +1 -0
  31. package/dist/log.d.ts +16 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +20 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/mcp-server.d.ts +4 -0
  36. package/dist/mcp-server.d.ts.map +1 -0
  37. package/dist/mcp-server.js +43 -0
  38. package/dist/mcp-server.js.map +1 -0
  39. package/dist/oauth.d.ts +41 -6
  40. package/dist/oauth.d.ts.map +1 -1
  41. package/dist/oauth.js +75 -41
  42. package/dist/oauth.js.map +1 -1
  43. package/dist/preview.d.ts +7 -0
  44. package/dist/preview.d.ts.map +1 -1
  45. package/dist/preview.js +14 -2
  46. package/dist/preview.js.map +1 -1
  47. package/dist/signing-requests.d.ts +81 -0
  48. package/dist/signing-requests.d.ts.map +1 -0
  49. package/dist/signing-requests.js +138 -0
  50. package/dist/signing-requests.js.map +1 -0
  51. package/dist/tools/index.d.ts +27 -1
  52. package/dist/tools/index.d.ts.map +1 -1
  53. package/dist/tools/index.js +37 -15
  54. package/dist/tools/index.js.map +1 -1
  55. package/dist/tools/{advanced.d.ts → read/advanced.d.ts} +30 -26
  56. package/dist/tools/read/advanced.d.ts.map +1 -0
  57. package/dist/tools/{advanced.js → read/advanced.js} +10 -10
  58. package/dist/tools/read/advanced.js.map +1 -0
  59. package/dist/tools/{balance.d.ts → read/balance.d.ts} +8 -7
  60. package/dist/tools/read/balance.d.ts.map +1 -0
  61. package/dist/tools/{balance.js → read/balance.js} +2 -2
  62. package/dist/tools/read/balance.js.map +1 -0
  63. package/dist/tools/{contract-info.d.ts → read/contract-info.d.ts} +18 -15
  64. package/dist/tools/read/contract-info.d.ts.map +1 -0
  65. package/dist/tools/{contract-info.js → read/contract-info.js} +2 -2
  66. package/dist/tools/read/contract-info.js.map +1 -0
  67. package/dist/tools/{contract.d.ts → read/contract.d.ts} +14 -12
  68. package/dist/tools/read/contract.d.ts.map +1 -0
  69. package/dist/tools/{contract.js → read/contract.js} +2 -2
  70. package/dist/tools/read/contract.js.map +1 -0
  71. package/dist/tools/{ens.d.ts → read/ens.d.ts} +30 -25
  72. package/dist/tools/read/ens.d.ts.map +1 -0
  73. package/dist/tools/{ens.js → read/ens.js} +2 -2
  74. package/dist/tools/read/ens.js.map +1 -0
  75. package/dist/tools/read/gas.d.ts +171 -0
  76. package/dist/tools/read/gas.d.ts.map +1 -0
  77. package/dist/tools/read/gas.js +368 -0
  78. package/dist/tools/read/gas.js.map +1 -0
  79. package/dist/tools/{logs.d.ts → read/logs.d.ts} +6 -5
  80. package/dist/tools/read/logs.d.ts.map +1 -0
  81. package/dist/tools/{logs.js → read/logs.js} +2 -2
  82. package/dist/tools/read/logs.js.map +1 -0
  83. package/dist/tools/{signatures.d.ts → read/signatures.d.ts} +8 -4
  84. package/dist/tools/read/signatures.d.ts.map +1 -0
  85. package/dist/tools/{signatures.js → read/signatures.js} +1 -1
  86. package/dist/tools/read/signatures.js.map +1 -0
  87. package/dist/tools/read/signing.d.ts +27 -0
  88. package/dist/tools/read/signing.d.ts.map +1 -0
  89. package/dist/tools/read/signing.js +75 -0
  90. package/dist/tools/read/signing.js.map +1 -0
  91. package/dist/tools/sign/errors.d.ts +9 -0
  92. package/dist/tools/sign/errors.d.ts.map +1 -0
  93. package/dist/tools/sign/errors.js +29 -0
  94. package/dist/tools/sign/errors.js.map +1 -0
  95. package/dist/tools/{transactions.d.ts → sign/transactions.d.ts} +48 -62
  96. package/dist/tools/sign/transactions.d.ts.map +1 -0
  97. package/dist/tools/sign/transactions.js +316 -0
  98. package/dist/tools/sign/transactions.js.map +1 -0
  99. package/dist/tools/sign/wallet.d.ts +50 -0
  100. package/dist/tools/sign/wallet.d.ts.map +1 -0
  101. package/dist/tools/sign/wallet.js +180 -0
  102. package/dist/tools/sign/wallet.js.map +1 -0
  103. package/dist/utils.d.ts +5 -2
  104. package/dist/utils.d.ts.map +1 -1
  105. package/dist/utils.js +5 -2
  106. package/dist/utils.js.map +1 -1
  107. package/dist/wallet-client.d.ts +33 -4
  108. package/dist/wallet-client.d.ts.map +1 -1
  109. package/dist/wallet-client.js +90 -24
  110. package/dist/wallet-client.js.map +1 -1
  111. package/dist/walletconnect.d.ts +111 -13
  112. package/dist/walletconnect.d.ts.map +1 -1
  113. package/dist/walletconnect.js +248 -68
  114. package/dist/walletconnect.js.map +1 -1
  115. package/package.json +10 -4
  116. package/src/anvil.ts +150 -271
  117. package/src/chains.ts +14 -2
  118. package/src/client.ts +0 -1
  119. package/src/context.ts +27 -0
  120. package/src/hosted.ts +11 -0
  121. package/src/http-server.ts +30 -5
  122. package/src/index.ts +19 -16
  123. package/src/lib.ts +24 -0
  124. package/src/log.ts +25 -0
  125. package/src/mcp-server.ts +47 -0
  126. package/src/oauth.ts +98 -45
  127. package/src/preview.ts +21 -2
  128. package/src/signing-requests.ts +198 -0
  129. package/src/tools/index.ts +67 -16
  130. package/src/tools/{advanced.ts → read/advanced.ts} +13 -11
  131. package/src/tools/{balance.ts → read/balance.ts} +3 -3
  132. package/src/tools/{contract-info.ts → read/contract-info.ts} +3 -3
  133. package/src/tools/{contract.ts → read/contract.ts} +3 -3
  134. package/src/tools/{ens.ts → read/ens.ts} +3 -3
  135. package/src/tools/read/gas.ts +480 -0
  136. package/src/tools/{logs.ts → read/logs.ts} +3 -3
  137. package/src/tools/{signatures.ts → read/signatures.ts} +2 -2
  138. package/src/tools/read/signing.ts +86 -0
  139. package/src/tools/sign/errors.ts +28 -0
  140. package/src/tools/sign/transactions.ts +428 -0
  141. package/src/tools/sign/wallet.ts +216 -0
  142. package/src/utils.ts +5 -2
  143. package/src/wallet-client.ts +91 -22
  144. package/src/walletconnect.ts +286 -66
  145. package/dist/tools/advanced.d.ts.map +0 -1
  146. package/dist/tools/advanced.js.map +0 -1
  147. package/dist/tools/balance.d.ts.map +0 -1
  148. package/dist/tools/balance.js.map +0 -1
  149. package/dist/tools/contract-info.d.ts.map +0 -1
  150. package/dist/tools/contract-info.js.map +0 -1
  151. package/dist/tools/contract.d.ts.map +0 -1
  152. package/dist/tools/contract.js.map +0 -1
  153. package/dist/tools/ens.d.ts.map +0 -1
  154. package/dist/tools/ens.js.map +0 -1
  155. package/dist/tools/gas.d.ts +0 -99
  156. package/dist/tools/gas.d.ts.map +0 -1
  157. package/dist/tools/gas.js +0 -181
  158. package/dist/tools/gas.js.map +0 -1
  159. package/dist/tools/logs.d.ts.map +0 -1
  160. package/dist/tools/logs.js.map +0 -1
  161. package/dist/tools/signatures.d.ts.map +0 -1
  162. package/dist/tools/signatures.js.map +0 -1
  163. package/dist/tools/transactions.d.ts.map +0 -1
  164. package/dist/tools/transactions.js +0 -361
  165. package/dist/tools/transactions.js.map +0 -1
  166. package/src/tools/gas.ts +0 -219
  167. package/src/tools/transactions.ts +0 -452
@@ -1,452 +0,0 @@
1
- import { randomBytes } from 'node:crypto'
2
- import qrcode from 'qrcode-terminal'
3
- import { type AbiFunction, type Address, encodeFunctionData, isAddress, parseAbiItem, parseUnits, toHex } from 'viem'
4
- import { z } from 'zod'
5
- import { getClientManager, SUPPORTED_CHAINS } from '../client.js'
6
- import { buildTxPreview, type RawTx, type TxPreview } from '../preview.js'
7
- import type { ChainName } from '../types.js'
8
- import { createTool, formatResponse } from '../utils.js'
9
- import { getWalletClient } from '../wallet-client.js'
10
- import { getPhoneSigner, pairingLinks } from '../walletconnect.js'
11
-
12
- /** Render a pairing URI as an ASCII QR, so it can be scanned straight from the chat. */
13
- function qrFor(uri: string): Promise<string> {
14
- return new Promise((resolve) => qrcode.generate(uri, { small: true }, resolve))
15
- }
16
-
17
- function generateRequestId(): string {
18
- return randomBytes(16).toString('hex')
19
- }
20
-
21
- function requireAddress(label: string, address: string): Address {
22
- if (!isAddress(address)) throw new Error(`Invalid ${label}: ${address}`)
23
- return address
24
- }
25
-
26
- function explorerTxUrl(chain: ChainName, txHash: unknown): string | undefined {
27
- return getClientManager().explorerUrl(chain, `/tx/${txHash}`)
28
- }
29
-
30
- /**
31
- * Which wallet to send the request to. Deliberately required on every signing tool: both
32
- * signers can be live at once, and only the person holding the devices knows which one is
33
- * actually to hand. Guessing strands the request in front of a screen nobody is looking at.
34
- *
35
- * Either way the transaction is decoded and simulated first — the wallet shows its own
36
- * summary, so the preview is returned to the caller too, to be read before approving.
37
- */
38
- const SignWithSchema = z
39
- .enum(['phone', 'browser'])
40
- .describe(
41
- 'Where to approve this: "phone" for a paired WalletConnect wallet, "browser" for the wallet signing page. Ask the user which they want — do not assume, even when only one is connected. Call wallet_status first: it says which signers are ready, and when no signing page is open it returns walletUrl. In that case give the user that link, ask them to open it and connect a wallet, and only call this once they confirm — a signing request cannot reach a page nobody has open.'
42
- )
43
-
44
- type SignWith = z.infer<typeof SignWithSchema>
45
-
46
- async function signOnPhone(chain: ChainName, tx: RawTx & { data?: string }) {
47
- const phone = getPhoneSigner()
48
- if (!phone) {
49
- throw new Error(
50
- 'Phone signing is not configured on this server. Set WALLETCONNECT_PROJECT_ID, or sign in the browser instead.'
51
- )
52
- }
53
- if (!(await phone.isPaired())) {
54
- throw new Error('No phone wallet is paired. Run pair_phone_wallet and scan the QR, or sign in the browser instead.')
55
- }
56
-
57
- const session = await phone.session()
58
- const from = session?.accounts[0]
59
- const preview = await buildTxPreview(chain, tx, from)
60
-
61
- const txHash = await phone.request(chain, 'eth_sendTransaction', [
62
- { from, to: tx.to, value: tx.value ?? '0x0', ...(tx.data && { data: tx.data }) }
63
- ])
64
-
65
- return { txHash, preview, signedWith: 'phone' as const }
66
- }
67
-
68
- async function requestSignature(chain: ChainName, tx: RawTx & { data?: string }, signWith: SignWith) {
69
- if (signWith === 'phone') return signOnPhone(chain, tx)
70
-
71
- const wallet = getWalletClient()
72
- await wallet.waitForSigner()
73
-
74
- const preview = await buildTxPreview(chain, tx, wallet.getAddress())
75
-
76
- return {
77
- txHash: await wallet.request({
78
- id: generateRequestId(),
79
- type: 'send_transaction',
80
- chain,
81
- data: { to: tx.to, value: tx.value ?? '0x0', ...(tx.data && { data: tx.data }) },
82
- preview
83
- }),
84
- preview,
85
- signedWith: 'browser' as const
86
- }
87
- }
88
-
89
- /** What the caller should see about a transaction before it is approved. */
90
- function previewSummary(preview: TxPreview) {
91
- return {
92
- action: preview.decoded?.intent ?? preview.decoded?.functionName,
93
- protocol: preview.decoded?.protocol ?? preview.toLabel,
94
- details: preview.decoded?.fields.map((f) => `${f.name}: ${f.value}${f.warning ? ` (${f.warning})` : ''}`),
95
- simulation: preview.simulation
96
- }
97
- }
98
-
99
- /**
100
- * WalletConnect rejects with a plain `{ code, message }` rather than an Error, which
101
- * String() renders as "[object Object]" — the reason a wallet gave for refusing is the
102
- * whole point of the message, so dig it out.
103
- */
104
- function describeError(error: unknown): string {
105
- if (error instanceof Error) return error.message
106
- if (error && typeof error === 'object') {
107
- const { message, code, reason } = error as { message?: string; code?: number; reason?: string }
108
- const text = message ?? reason
109
- if (text) return code === undefined ? text : `${text} (code ${code})`
110
- return JSON.stringify(error)
111
- }
112
- return String(error)
113
- }
114
-
115
- function failure(error: unknown, message: string) {
116
- console.error('[Transaction]', message, '—', describeError(error))
117
- return formatResponse({
118
- success: false,
119
- error: describeError(error),
120
- message
121
- })
122
- }
123
-
124
- export default {
125
- send_native_token: createTool(
126
- 'Send Native Token',
127
- 'Send native tokens (ETH, MATIC, BNB, etc.) to an address. Simulates the transaction, then sends it to the signer you choose for approval.',
128
- z.object({
129
- chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
130
- to: z.string().describe('Recipient address'),
131
- amount: z.string().describe('Amount in native token (e.g., "0.1" for 0.1 ETH)'),
132
- data: z.string().optional().describe('Optional hex-encoded data to include with transaction'),
133
- signWith: SignWithSchema
134
- }),
135
- async (args) => {
136
- try {
137
- const to = requireAddress('recipient address', args.to)
138
- const value = `0x${parseUnits(args.amount, 18).toString(16)}`
139
-
140
- const { txHash, preview, signedWith } = await requestSignature(
141
- args.chain as ChainName,
142
- { to, value, data: args.data },
143
- args.signWith
144
- )
145
-
146
- return formatResponse({
147
- success: true,
148
- chain: args.chain,
149
- transactionHash: txHash,
150
- to,
151
- amount: args.amount,
152
- signedWith,
153
- preview: previewSummary(preview),
154
- explorerUrl: explorerTxUrl(args.chain as ChainName, txHash)
155
- })
156
- } catch (error) {
157
- return failure(error, 'Transaction failed or was rejected')
158
- }
159
- }
160
- ),
161
-
162
- send_erc20_token: createTool(
163
- 'Send ERC20 Token',
164
- 'Send ERC20 tokens to an address. Simulates the transfer, then sends it to the signer you choose for approval.',
165
- z.object({
166
- chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
167
- tokenAddress: z.string().describe('ERC20 token contract address'),
168
- to: z.string().describe('Recipient address'),
169
- amount: z.string().describe('Amount in token units (e.g., "100" for 100 USDC)'),
170
- decimals: z.number().optional().default(18).describe('Token decimals (default: 18)'),
171
- signWith: SignWithSchema
172
- }),
173
- async (args) => {
174
- try {
175
- const tokenAddress = requireAddress('token address', args.tokenAddress)
176
- const to = requireAddress('recipient address', args.to)
177
-
178
- const data = encodeFunctionData({
179
- abi: [parseAbiItem('function transfer(address to, uint256 amount)')],
180
- args: [to, parseUnits(args.amount, args.decimals ?? 18)]
181
- })
182
-
183
- const { txHash, preview, signedWith } = await requestSignature(
184
- args.chain as ChainName,
185
- {
186
- to: tokenAddress,
187
- data,
188
- value: '0x0'
189
- },
190
- args.signWith
191
- )
192
-
193
- return formatResponse({
194
- success: true,
195
- chain: args.chain,
196
- transactionHash: txHash,
197
- tokenAddress,
198
- to,
199
- amount: args.amount,
200
- signedWith,
201
- preview: previewSummary(preview),
202
- explorerUrl: explorerTxUrl(args.chain as ChainName, txHash)
203
- })
204
- } catch (error) {
205
- return failure(error, 'Token transfer failed or was rejected')
206
- }
207
- }
208
- ),
209
-
210
- write_contract: createTool(
211
- 'Write Contract',
212
- 'Send a transaction that calls a state-changing contract function. Simulates it first, then asks your wallet to approve. Costs gas.',
213
- z.object({
214
- chain: z.enum(SUPPORTED_CHAINS).describe('Blockchain network'),
215
- contractAddress: z.string().describe('Contract address'),
216
- functionAbi: z.string().describe('Function ABI definition (e.g., "function transfer(address to, uint256 amount)")'),
217
- args: z
218
- .array(z.union([z.string(), z.number(), z.boolean()]))
219
- .optional()
220
- .describe('Function arguments in order matching the ABI signature'),
221
- value: z.string().optional().describe('Optional native value to send with transaction (in ETH units, e.g., "0.1")'),
222
- signWith: SignWithSchema
223
- }),
224
- async (args) => {
225
- try {
226
- const contractAddress = requireAddress('contract address', args.contractAddress)
227
- const abiItem = parseAbiItem(args.functionAbi) as AbiFunction
228
-
229
- const data = encodeFunctionData({
230
- abi: [abiItem],
231
- functionName: abiItem.name,
232
- args: (args.args || []) as readonly unknown[]
233
- })
234
- const value = args.value ? `0x${parseUnits(args.value, 18).toString(16)}` : '0x0'
235
-
236
- const { txHash, preview, signedWith } = await requestSignature(
237
- args.chain as ChainName,
238
- {
239
- to: contractAddress,
240
- data,
241
- value
242
- },
243
- args.signWith
244
- )
245
-
246
- return formatResponse({
247
- success: true,
248
- chain: args.chain,
249
- transactionHash: txHash,
250
- contractAddress,
251
- functionName: abiItem.name,
252
- signedWith,
253
- preview: previewSummary(preview),
254
- explorerUrl: explorerTxUrl(args.chain as ChainName, txHash)
255
- })
256
- } catch (error) {
257
- return failure(error, 'Contract call failed or was rejected')
258
- }
259
- }
260
- ),
261
-
262
- sign_message: createTool(
263
- 'Sign Message',
264
- 'Sign a message with your wallet, on whichever signer you choose.',
265
- z.object({
266
- message: z.string().describe('Message to sign'),
267
- signWith: SignWithSchema
268
- }),
269
- async (args) => {
270
- try {
271
- let signature: unknown
272
-
273
- if (args.signWith === 'phone') {
274
- const phone = getPhoneSigner()
275
- const session = await phone?.session()
276
- if (!session) {
277
- throw new Error('No phone wallet is paired. Run pair_phone_wallet and scan the QR, or sign in the browser instead.')
278
- }
279
- signature = await phone!.request('mainnet', 'personal_sign', [toHex(args.message), session.accounts[0]])
280
- } else {
281
- await getWalletClient().waitForSigner()
282
- signature = await getWalletClient().request({
283
- id: generateRequestId(),
284
- type: 'sign_message',
285
- chain: 'any',
286
- data: { message: args.message }
287
- })
288
- }
289
-
290
- return formatResponse({
291
- success: true,
292
- message: args.message,
293
- signature,
294
- signedWith: args.signWith,
295
- signatureType: 'personal_sign'
296
- })
297
- } catch (error) {
298
- return failure(error, 'Message signing failed or was rejected')
299
- }
300
- }
301
- ),
302
-
303
- pair_phone_wallet: createTool(
304
- 'Pair Phone Wallet',
305
- 'Pair a phone wallet over WalletConnect, so transactions are signed on the phone instead of in a browser. ' +
306
- 'Returns a QR to scan plus links that open a wallet directly — show those to the user as clickable links. ' +
307
- 'Requires a WalletConnect project id.',
308
- z.object({
309
- chains: z
310
- .array(z.enum(SUPPORTED_CHAINS))
311
- .optional()
312
- .describe('Chains to request access to (defaults to every supported network)'),
313
- wallet: z.string().optional().describe('Name of the wallet to open, e.g. "rabby" — omit to list the common ones'),
314
- agent: z
315
- .string()
316
- .optional()
317
- .describe(
318
- 'Who is asking, shown in the wallet approval dialog, e.g. "Claude Code". Say who you actually are — ' +
319
- 'the user reads this when deciding whether to grant signing access.'
320
- )
321
- }),
322
- async (args) => {
323
- const phone = getPhoneSigner()
324
- if (!phone) {
325
- return formatResponse({
326
- success: false,
327
- message:
328
- 'No WalletConnect project id configured. Get a free one at https://dashboard.walletconnect.com and pass --walletconnect-project-id or set WALLETCONNECT_PROJECT_ID.'
329
- })
330
- }
331
-
332
- try {
333
- const existing = await phone.session()
334
- if (existing) {
335
- return formatResponse({
336
- alreadyPaired: true,
337
- address: existing.accounts[0],
338
- wallet: existing.peer,
339
- message: 'A phone wallet is already paired. Transactions will be sent to it.'
340
- })
341
- }
342
-
343
- const chains = (args.chains ?? SUPPORTED_CHAINS.filter((c) => c !== 'localhost')) as ChainName[]
344
- const uri = await phone.pair(chains, args.agent)
345
- const projectId = getClientManager().getConfig().walletConnectProjectId as string
346
-
347
- return formatResponse({
348
- qr: await qrFor(uri),
349
- uri,
350
- // For an agent running on the phone itself there is nothing to scan, so hand over
351
- // links that open the wallet directly. `wallet` narrows the list to one.
352
- openOnThisDevice: await pairingLinks(projectId, uri, args.wallet),
353
- // Approving grants an agent standing permission to request signatures, so the
354
- // wallet dialog names the agent rather than implying a website is connecting.
355
- shownInWallet: args.agent ? `${args.agent} via web3-tools-mcp` : 'web3-tools-mcp (AI agent)',
356
- howToPresent:
357
- 'Render each openOnThisDevice entry as a clickable link labelled with the wallet name, and show the ' +
358
- 'uri as copyable text. On a phone that tap is the whole flow. Show the QR only when the user is on a ' +
359
- 'different device from their wallet — it is unreadable inline on the phone that holds the wallet. ' +
360
- 'If a link does nothing, some clients drop custom schemes like rabby://, so tell them to paste the uri.',
361
- message:
362
- 'On another device: scan the QR with your wallet. On this device: tap one of the openOnThisDevice ' +
363
- 'links, or copy the uri and paste it into your wallet under WalletConnect — every wallet supports ' +
364
- 'that, and it is the one that always works. Then run wallet_status to confirm.'
365
- })
366
- } catch (error) {
367
- return failure(error, 'Could not start WalletConnect pairing')
368
- }
369
- }
370
- ),
371
-
372
- disconnect_phone_wallet: createTool(
373
- 'Disconnect Phone Wallet',
374
- 'End every WalletConnect session and drop the pairings underneath them. Use before pairing a different wallet, or to clear out attempts that were never approved.',
375
- z.object({}),
376
- async () => {
377
- const phone = getPhoneSigner()
378
- if (!phone) {
379
- return formatResponse({ success: false, message: 'No WalletConnect project id configured — nothing to disconnect.' })
380
- }
381
-
382
- try {
383
- const before = await phone.sessions()
384
- const removed = await phone.disconnectAll()
385
-
386
- return formatResponse({
387
- success: true,
388
- disconnectedSessions: removed.sessions,
389
- droppedPairings: removed.pairings,
390
- wallets: before.map((session) => `${session.peer ?? 'unknown wallet'} (${session.accounts[0]})`),
391
- message:
392
- removed.sessions || removed.pairings
393
- ? 'Disconnected. Transactions fall back to the browser wallet until a phone is paired again.'
394
- : 'Nothing was connected.'
395
- })
396
- } catch (error) {
397
- return failure(error, 'Could not disconnect the phone wallet')
398
- }
399
- }
400
- ),
401
-
402
- wallet_status: createTool(
403
- 'Wallet Status',
404
- 'Report every signer and whether it is ready, so a signing tool can be given the right signWith.',
405
- z.object({}),
406
- async () => {
407
- // Both signers are reported, never just the first one found: signWith makes this a
408
- // choice the user owns, so the agent has to see everything available.
409
- const phone = getPhoneSigner()
410
- const phoneSession = await phone?.session().catch(() => undefined)
411
-
412
- const wallet = getWalletClient()
413
- const relayError = await wallet
414
- .connect()
415
- .then(() => undefined)
416
- .catch((error) => describeError(error))
417
-
418
- const browserReady = !relayError && wallet.isConnected()
419
- // Only raise a tab when there is no other way to sign — a status check should not
420
- // open a window at someone who is about to use their phone.
421
- if (!browserReady && !phoneSession && !relayError) wallet.openBrowser()
422
-
423
- const signers = {
424
- phone: phoneSession
425
- ? { ready: true, address: phoneSession.accounts[0], wallet: phoneSession.peer, chains: phoneSession.chains }
426
- : {
427
- ready: false,
428
- reason: phone
429
- ? 'No phone paired. Run pair_phone_wallet and scan the QR.'
430
- : 'Phone signing is not configured — set WALLETCONNECT_PROJECT_ID.'
431
- },
432
- browser: browserReady
433
- ? { ready: true, address: wallet.getAddress(), openTab: wallet.getPageUrl() }
434
- : {
435
- ready: false,
436
- reason: relayError ?? 'No signing page is open.',
437
- walletUrl: relayError ? undefined : wallet.getUrl()
438
- }
439
- }
440
-
441
- const ready = [phoneSession ? 'phone' : undefined, browserReady ? 'browser' : undefined].filter(Boolean)
442
- const message =
443
- ready.length === 2
444
- ? 'Both signers are ready. Ask the user which one to use, then pass it as signWith.'
445
- : ready.length === 1
446
- ? `Only ${ready[0]} is ready. Confirm with the user before signing there, or set the other one up.`
447
- : `No signer is ready. For a browser, give the user this link and ask them to open it and connect a wallet: ${signers.browser.walletUrl ?? '(relay unavailable)'}. For a phone, run pair_phone_wallet.`
448
-
449
- return formatResponse({ ready, signers, message })
450
- }
451
- )
452
- }