@@ -23,16 +23,59 @@ WalletConnect 通过加密消息在钱包与 DApp 之间传递信息,确保安
2323 - 采用分布式架构,提高可用性和性能
2424 - 支持 WebSocket 长连接,实现实时通信
2525
26+ 示例配置:
27+ ``` javascript
28+ const bridge = new WalletConnectBridge ({
29+ url: " wss://bridge.walletconnect.org" ,
30+ pingInterval: 15000 ,
31+ maxAttempts: 5
32+ });
33+ ```
34+
26352 . ** Client SDK** :
2736 - 提供多语言支持(JavaScript、Swift、Kotlin等)
2837 - 封装核心协议逻辑,简化开发流程
2938 - 内置安全机制和错误处理
3039
40+ JavaScript 示例:
41+ ``` javascript
42+ import WalletConnect from " @walletconnect/client" ;
43+
44+ const connector = new WalletConnect ({
45+ bridge: " https://bridge.walletconnect.org" ,
46+ qrcodeModal: QRCodeModal,
47+ chainId: 1
48+ });
49+
50+ // 监听连接事件
51+ connector .on (" connect" , (error , payload ) => {
52+ if (error) {
53+ console .error (error);
54+ return ;
55+ }
56+ const { accounts , chainId } = payload .params [0 ];
57+ console .log (" Connected to" , accounts[0 ]);
58+ });
59+ ```
60+
31613 . ** 协议层** :
3262 - 定义标准消息格式和通信流程
3363 - 实现跨平台兼容性
3464 - 支持协议版本升级和向后兼容
3565
66+ 消息格式示例:
67+ ``` json
68+ {
69+ "id" : 1234567890 ,
70+ "jsonrpc" : " 2.0" ,
71+ "method" : " eth_sendTransaction" ,
72+ "params" : [{
73+ "from" : " 0x..." ,
74+ "to" : " 0x..." ,
75+ "value" : " 0x..."
76+ }]
77+ }
78+
3679### 连接流程
3780
38811 . DApp 创建连接请求并生成二维码
@@ -93,17 +136,157 @@ WalletConnect 通过加密消息在钱包与 DApp 之间传递信息,确保安
93136 - 支持自动重连
94137 - 优化重连流程
95138
139+ 重连实现示例:
140+ ```javascript
141+ class ConnectionManager {
142+ constructor() {
143+ this.reconnectAttempts = 0;
144+ this.maxAttempts = 5;
145+ this.baseDelay = 1000; // 1秒
146+ }
147+
148+ async reconnect() {
149+ if (this.reconnectAttempts >= this.maxAttempts) {
150+ throw new Error("重连次数超过限制");
151+ }
152+
153+ // 使用指数退避策略
154+ const delay = this.baseDelay * Math.pow(2, this.reconnectAttempts);
155+ await new Promise(resolve => setTimeout(resolve, delay));
156+
157+ try {
158+ // 尝试恢复缓存的会话
159+ const session = localStorage.getItem("walletconnect");
160+ if (session) {
161+ await connector.connect(JSON.parse(session));
162+ } else {
163+ await connector.createSession();
164+ }
165+ this.reconnectAttempts = 0;
166+ return true;
167+ } catch (error) {
168+ this.reconnectAttempts++;
169+ return this.reconnect();
170+ }
171+ }
172+ }
173+ ```
174+
961752 . ** 网络适应** :
97176 - 动态超时调整
98177 - 自动重试机制
99178 - 网络状态监控
100179
180+ 网络适应示例:
181+ ``` javascript
182+ class NetworkMonitor {
183+ constructor () {
184+ this .baseTimeout = 5000 ;
185+ this .maxTimeout = 30000 ;
186+ this .latencyHistory = [];
187+ }
188+
189+ // 计算动态超时时间
190+ calculateTimeout () {
191+ if (this .latencyHistory .length === 0 ) {
192+ return this .baseTimeout ;
193+ }
194+
195+ // 使用最近5次请求的平均延迟
196+ const recentLatencies = this .latencyHistory .slice (- 5 );
197+ const avgLatency = recentLatencies .reduce ((a , b ) => a + b, 0 ) / recentLatencies .length ;
198+
199+ // 动态超时 = 平均延迟 * 3 + 标准差
200+ const timeout = (avgLatency * 3 ) + this .calculateStdDev (recentLatencies);
201+ return Math .min (Math .max (timeout, this .baseTimeout ), this .maxTimeout );
202+ }
203+
204+ // 计算标准差
205+ calculateStdDev (values ) {
206+ const avg = values .reduce ((a , b ) => a + b, 0 ) / values .length ;
207+ const squareDiffs = values .map (value => Math .pow (value - avg, 2 ));
208+ const avgSquareDiff = squareDiffs .reduce ((a , b ) => a + b, 0 ) / squareDiffs .length ;
209+ return Math .sqrt (avgSquareDiff);
210+ }
211+
212+ // 记录请求延迟
213+ recordLatency (latency ) {
214+ this .latencyHistory .push (latency);
215+ if (this .latencyHistory .length > 10 ) {
216+ this .latencyHistory .shift ();
217+ }
218+ }
219+ }
220+ ```
221+
101222### 资源管理
102223
103224- 优化内存使用
104225- 减少网络请求
105226- 高效的状态同步
106227
228+ 资源管理示例:
229+ ``` javascript
230+ // 内存优化
231+ class ResourceManager {
232+ constructor () {
233+ this .subscriptions = new Map ();
234+ this .messageQueue = [];
235+ this .maxQueueSize = 100 ;
236+ this .processingInterval = 1000 ; // 1秒处理一次队列
237+ }
238+
239+ // 批量处理消息队列
240+ processMessageQueue () {
241+ setInterval (() => {
242+ const batch = this .messageQueue .splice (0 , 10 );
243+ if (batch .length > 0 ) {
244+ this .sendBatchMessage (batch);
245+ }
246+ }, this .processingInterval );
247+ }
248+
249+ // 清理过期订阅
250+ cleanupSubscriptions () {
251+ const now = Date .now ();
252+ for (const [key , sub ] of this .subscriptions ) {
253+ if (now - sub .lastActive > 5 * 60 * 1000 ) { // 5分钟无活动
254+ sub .unsubscribe ();
255+ this .subscriptions .delete (key);
256+ }
257+ }
258+ }
259+
260+ // 状态同步优化
261+ async syncState () {
262+ const lastSync = localStorage .getItem (" lastSync" );
263+ const now = Date .now ();
264+
265+ // 增量同步
266+ if (lastSync) {
267+ const changes = await this .getStateChangesSince (lastSync);
268+ this .applyStateChanges (changes);
269+ } else {
270+ // 全量同步
271+ const state = await this .getFullState ();
272+ this .setState (state);
273+ }
274+
275+ localStorage .setItem (" lastSync" , now .toString ());
276+ }
277+
278+ // 性能指标监控
279+ measurePerformance () {
280+ return {
281+ memoryUsage: performance .memory ? .usedJSHeapSize || 0 ,
282+ activeSubscriptions: this .subscriptions .size ,
283+ queueLength: this .messageQueue .length ,
284+ processingLatency: this .calculateProcessingLatency ()
285+ };
286+ }
287+ }
288+ ```
289+
107290## 最佳实践
108291
109292### 开发建议
@@ -113,18 +296,133 @@ WalletConnect 通过加密消息在钱包与 DApp 之间传递信息,确保安
113296 - 提供用户友好的错误提示
114297 - 记录详细的错误日志
115298
299+ 错误处理示例:
300+ ``` javascript
301+ connector .on (" error" , (error ) => {
302+ // 网络错误处理
303+ if (error .message .includes (" network" )) {
304+ showNetworkError ();
305+ attemptReconnect ();
306+ return ;
307+ }
308+
309+ // 会话过期处理
310+ if (error .message .includes (" session" )) {
311+ clearSession ();
312+ requestNewConnection ();
313+ return ;
314+ }
315+
316+ // 通用错误处理
317+ console .error (" WalletConnect错误:" , error);
318+ showUserFriendlyError (error);
319+ });
320+
321+ function showUserFriendlyError (error ) {
322+ const errorMessages = {
323+ " user_rejected" : " 用户拒绝了请求" ,
324+ " chain_not_supported" : " 当前钱包不支持该链" ,
325+ " invalid_parameters" : " 无效的交易参数"
326+ };
327+
328+ const message = errorMessages[error .code ] || " 连接出现问题,请稍后重试" ;
329+ displayError (message);
330+ }
331+ ```
332+
1163332 . ** 用户体验** :
117334 - 显示连接状态和进度
118335 - 提供清晰的操作引导
119336 - 实现平滑的断开重连
120337
338+ 状态管理示例:
339+ ``` javascript
340+ const ConnectionState = {
341+ CONNECTING : " connecting" ,
342+ CONNECTED : " connected" ,
343+ DISCONNECTED : " disconnected" ,
344+ ERROR : " error"
345+ };
346+
347+ function updateConnectionUI (state ) {
348+ const stateMessages = {
349+ [ConnectionState .CONNECTING ]: " 正在连接钱包..." ,
350+ [ConnectionState .CONNECTED ]: " 钱包已连接" ,
351+ [ConnectionState .DISCONNECTED ]: " 请连接钱包" ,
352+ [ConnectionState .ERROR ]: " 连接出错"
353+ };
354+
355+ // 更新UI状态
356+ updateStatusText (stateMessages[state]);
357+ updateConnectButton (state);
358+ updateLoadingIndicator (state === ConnectionState .CONNECTING );
359+ }
360+ ```
361+
121362### 安全建议
122363
123364- 定期更新 SDK 版本
124365- 实施请求频率限制
125366- 验证所有用户输入
126367- 实现会话超时机制
127368
369+ 安全实践示例:
370+ ``` javascript
371+ // 请求频率限制
372+ const rateLimiter = {
373+ requests: {},
374+ limit: 5 ,
375+ interval: 60000 , // 1分钟
376+
377+ checkLimit (method ) {
378+ const now = Date .now ();
379+ const recentRequests = this .requests [method] || [];
380+
381+ // 清理过期请求
382+ this .requests [method] = recentRequests .filter (
383+ time => now - time < this .interval
384+ );
385+
386+ if (this .requests [method].length >= this .limit ) {
387+ throw new Error (" 请求过于频繁,请稍后再试" );
388+ }
389+
390+ this .requests [method].push (now);
391+ }
392+ };
393+
394+ // 输入验证
395+ function validateTransactionParams (params ) {
396+ const required = [" to" , " value" ];
397+ for (const field of required) {
398+ if (! params[field]) {
399+ throw new Error (` 缺少必要参数: ${ field} ` );
400+ }
401+ }
402+
403+ // 验证地址格式
404+ if (! / ^ 0x[a-fA-F0-9 ] {40} $ / .test (params .to )) {
405+ throw new Error (" 无效的接收地址" );
406+ }
407+
408+ // 验证金额
409+ if (! / ^ [0-9 ] + $ / .test (params .value )) {
410+ throw new Error (" 无效的转账金额" );
411+ }
412+ }
413+
414+ // 会话超时检查
415+ const SESSION_TIMEOUT = 30 * 60 * 1000 ; // 30分钟
416+ function checkSessionTimeout () {
417+ const lastActivity = connector .lastActivityTime ;
418+ if (Date .now () - lastActivity > SESSION_TIMEOUT ) {
419+ connector .killSession ();
420+ return false ;
421+ }
422+ return true ;
423+ }
424+ ```
425+
128426## 未来发展
129427
130428### 技术路线
0 commit comments