import { Core } from '@walletconnect/core';
import { WalletKit } from '@walletconnect/walletkit';
import { getSdkError } from '@walletconnect/utils';
// Initialize Core and WalletKit
const core = new Core({ projectId: 'fgu234234njbhvhv23525bj' });
const initWalletKit = async () => {
return await WalletKit.init({
core: core,
metadata: {
name: 'Example WalletConnect Wallet',
description: 'Example WalletConnect Integration',
url: 'myexamplewallet.com',
icons: [],
},
});
};
// Function to handle pairing
const onConnect = async (walletKit, uri) => {
await walletKit.core.pairing.pair({ uri });
};
// Function to handle session proposals
const handleSessionProposal = async (walletKit, proposal) => {
// Example accounts in the wallet state
const substrateAccounts = [
'5CK8D1sKNwF473wbuBP6NuhQfPaWUetNsWUNAAzVwTfxqjfr',
'5F3sa2TJAWMqDhXG6jhV4N8ko9SxwGy8TpaNS1repo5EYjQX',
];
const walletConnectAccounts = substrateAccounts.map(
(account) => `polkadot:91b171bb158e2d3848fa23a9f1c25182:${account}`
);
// Simulate user approval
const session = await walletKit.approveSession({
id: proposal.id,
namespaces: {
polkadot: {
accounts: walletConnectAccounts,
methods: ['polkadot_signTransaction', 'polkadot_signMessage'],
chains: ['polkadot:91b171bb158e2d3848fa23a9f1c25182'],
events: ['chainChanged', 'accountsChanged'],
},
},
});
// Respond to the dapp
const response = { id: proposal.id, result: 'session approved', jsonrpc: '2.0' };
await walletKit.respondSessionRequest({ topic: session.topic, response });
};
// Function to handle session requests
const handleSessionRequest = async (walletKit, requestEvent) => {
const { params, id } = requestEvent;
const { request } = params;
switch (request.method) {
case 'polkadot_signMessage':
const signature = await yourwallet.signMessage(request.params.message);
await walletKit.respondSessionRequest({
topic: requestEvent.topic,
response: { id, result: { signature }, jsonrpc: '2.0' },
});
break;
case 'polkadot_signTransaction':
const txSignature = await
yourwallet.signTransaction(request.params.transactionPayload);
await walletKit.respondSessionRequest({
topic: requestEvent.topic,
response: { id, result: { signature: txSignature }, jsonrpc: '2.0' },
});
break;
default:
throw new Error(getSdkError('INVALID_METHOD').message);
}
};
// Function to handle session rejection
const rejectSessionProposal = async (walletKit, proposal) => {
await walletKit.rejectSession({
id: proposal.id,
reason: getSdkError('USER_REJECTED'),
});
};
// Wallet setup and event listeners
(async () => {
const walletKit = await initWalletKit();
walletKit.on('session_proposal', async (proposal) => {
try {
// Approve the session
await handleSessionProposal(walletKit, proposal);
} catch (error) {
// Reject if necessary
await rejectSessionProposal(walletKit, proposal);
}
});
walletKit.on('session_request', async (requestEvent) => {
try {
await handleSessionRequest(walletKit, requestEvent);
} catch (error) {
console.error('Session request error:', error);
}
});
})();