跳到主要内容

Dapp 用法

这个库兼容NodeJS、浏览器和React-Native应用程序 (NodeJS模块需要React-Native的polyfills).

信息

关于示例实现,请参考我们的react-dapp-v2 example

创建一个会话

1. 使用您的项目ID启动您的WalletConnect客户端与中继服务器.

import SignClient from "@walletconnect/sign-client";

const signClient = await SignClient.init({
projectId: "<YOUR_PROJECT_ID>",
metadata: {
name: "Example Dapp",
description: "Example Dapp",
url: "#",
icons: ["https://walletconnect.com/walletconnect-logo.png"],
},
});

2. 为所需的SignClient事件添加监听器.

信息

要收听与配对相关的事件,请遵循配对API事件监听器的指南。

signClient.on("session_event", ({ event }) => {
// Handle session events, such as "chainChanged", "accountsChanged", etc.
});

signClient.on("session_update", ({ topic, params }) => {
const { namespaces } = params;
const _session = signClient.session.get(topic);
// Overwrite the `namespaces` of the existing session with the incoming one.
const updatedSession = { ..._session, namespaces };
// Integrate the updated session state into your dapp state.
onSessionUpdate(updatedSession);
});

signClient.on("session_delete", () => {
// Session was deleted -> reset the dapp state, clean up from user session, etc.
});

3. 连接应用程序并指定会话权限.

import QRCodeModal from "@walletconnect/qrcode-modal";

// ...

try {
const { uri, approval } = await signClient.connect({
// Optionally: pass a known prior pairing (e.g. from `signClient.core.pairing.getPairings()`) to skip the `uri` step.
pairingTopic: pairing?.topic,
// Provide the namespaces and chains (e.g. `eip155` for EVM-based chains) we want to use in this session.
requiredNamespaces: {
eip155: {
methods: [
"eth_sendTransaction",
"eth_signTransaction",
"eth_sign",
"personal_sign",
"eth_signTypedData",
],
chains: ["eip155:1"],
events: ["chainChanged", "accountsChanged"],
},
},
});

//如果返回URI,则打开QRCode模式(即我们没有连接现有的配对)。
if (uri) {
QRCodeModal.open(uri, () => {
console.log("EVENT", "QR Code Modal closed");
});
}

// 等待钱包的会话批准。
const session = await approval();
// 处理返回的会话(例如,将UI更新为“connected”状态)。
await onSessionConnected(session);
} catch (e) {
console.error(e);
} finally {
// 关闭QRCode模式,以防它是打开的。
QRCodeModal.close();
}

发出请求

一旦会话成功建立,您就可以开始发出JSON-RPC请求,由钱包批准和签名:

const result = await signClient.request({
topic: session.topic,
chainId: "eip155:1",
request: {
id: 1,
jsonrpc: "2.0",
method: "personal_sign",
params: [
"0x1d85568eEAbad713fBB5293B45ea066e552A90De",
"0x7468697320697320612074657374206d65737361676520746f206265207369676e6564",
],
},
});

有关可用的JSON-RPC请求的更多信息,请参见JSON-RPC reference