Subscribe to session proposal event for user approval and session created when successful
import { CLIENT_EVENTS } from"@walletconnect/client";import { SessionTypes } from"@walletconnect/types";client.on(CLIENT_EVENTS.session.proposal,async (proposal:SessionTypes.Proposal) => {// user should be prompted to approve the proposed session permissions displaying also dapp metadataconst { proposer,permissions } = proposal;const { metadata } = proposer;let approved:boolean;handleSessionUserApproval(approved, proposal); // described in the step 4 });client.on(CLIENT_EVENTS.session.created,async (session:SessionTypes.Created) => {// session created succesfully });
Pair with shared URI from dapp
client.pair({ uri });
Handle user approval for proposed session
functionhandleSessionUserApproval( approved:boolean, proposal:SessionTypes.Proposal) {if (userApproved) {// if user approved then include response with accounts matching the chains and wallet metadataconstresponse:SessionTypes.Response= { state: { accounts: ["0x1d85568eEAbad713fBB5293B45ea066e552A90De@eip155:1"], }, };awaitclient.approve({ proposal, response }); } else {// if user didn't approve then reject with no responseawaitclient.reject({ proposal }); }}
JSON-RPC Payloads
Given that session has settled succesfully since user approved the session on the wallet side, then the Wallet should subscribe to session payload events on the client
import { CLIENT_EVENTS } from"@walletconnect/client";import { SessionTypes } from"@walletconnect/types";import { JsonRpcResponse } from"@json-rpc-tools/utils";client.on(CLIENT_EVENTS.session.request,async (requestEvent:SessionTypes.RequestEvent) => {// WalletConnect client can track multiple sessions// assert the topic from which application requestedconst { topic,request } = requestEvent;constsession=awaitclient.session.get(requestEvent.topic);// now you can display to the user for approval using the stored metadataconst { metadata } =session.peer;// after user has either approved or not the request it should be formatted// as response with either the result or the error messagelet result:any;constresponse= approved? { topic, response: { id:request.id, jsonrpc:"2.0", result, }, }: { topic, response: { id:request.id, jsonrpc:"2.0", error: { code:-32000, message:"User rejected JSON-RPC request", }, }, };awaitclient.respond(response); });