Skip to content

Upgrade wallet connect #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions examples/react-headless/src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { useState } from 'react';
const APP_NAME = 'Polkadot Demo';

const App = () => {
let injectedWalletProvider = new InjectedWalletProvider(extensionConfig, APP_NAME);
let walletConnectParams: WalletConnectConfiguration = {
const injectedWalletProvider = new InjectedWalletProvider(extensionConfig, APP_NAME);
const walletConnectParams: WalletConnectConfiguration = {
projectId: '4fae85e642724ee66587fa9f37b997e2',
relayUrl: 'wss://relay.walletconnect.com',
metadata: {
Expand All @@ -22,10 +22,16 @@ const App = () => {
icons: ['https://walletconnect.com/walletconnect-logo.png'],
},
chainIds: ['polkadot:e143f23803ac50e8f6f8e62695d1ce9e', 'polkadot:91b171bb158e2d3848fa23a9f1c25182'],
optionalChainIds: ['polkadot:67f9723393ef76214df0118c34bbbd3d', 'polkadot:7c34d42fc815d392057c78b49f2755c7'],
onSessionDelete: () => {
// do something when session is removed
}
};
let walletConnectProvider = new WalletConnectProvider(walletConnectParams, APP_NAME);
let walletAggregator = new WalletAggregator([injectedWalletProvider, walletConnectProvider]);
let [showWallets, setShowWallets] = useState(false);

const walletConnectProvider = new WalletConnectProvider(walletConnectParams, APP_NAME);
const walletAggregator = new WalletAggregator([injectedWalletProvider, walletConnectProvider]);
const [showWallets, setShowWallets] = useState(false);

return (
<PolkadotWalletsContextProvider walletAggregator={walletAggregator}>
<button
Expand Down
4 changes: 4 additions & 0 deletions examples/react-next/components/ConnectContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const ConnectContainer = () => {
icons: ['/images/wallet-connect.svg'],
},
chainIds: ['polkadot:e143f23803ac50e8f6f8e62695d1ce9e', 'polkadot:91b171bb158e2d3848fa23a9f1c25182'],
optionalChainIds: ['polkadot:67f9723393ef76214df0118c34bbbd3d', 'polkadot:7c34d42fc815d392057c78b49f2755c7'],
onSessionDelete: () => {
// do something when session is removed
}
};
let walletConnectProvider = new WalletConnectProvider(walletConnectParams, APP_NAME);
let walletAggregator = new WalletAggregator([injectedWalletProvider, walletConnectProvider]);
Expand Down
6 changes: 3 additions & 3 deletions packages/wallet-connect/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
},
"dependencies": {
"@polkadot-onboard/core": "0.1.0",
"@walletconnect/qrcode-modal": "1.8.0",
"@walletconnect/sign-client": "2.9.1"
"@walletconnect/modal": "2.6.1",
"@walletconnect/sign-client": "2.9.2"
},
"devDependencies": {
"@polkadot/types": "10.9.1",
"@walletconnect/types": "2.7.7",
"@walletconnect/types": "2.9.2",
"prettier": "3.0.0",
"typescript": "5.1.6"
}
Expand Down
25 changes: 12 additions & 13 deletions packages/wallet-connect/src/signer.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import type { HexString } from '@polkadot/util/types';
import { TypeRegistry } from '@polkadot/types';
import type { Signer, SignerResult } from '@polkadot/types/types';
import type { SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
import type { SessionTypes } from '@walletconnect/types';

import { TypeRegistry } from '@polkadot/types';
import type { HexString } from '@polkadot/util/types';
import SignClient from '@walletconnect/sign-client';
import type { SessionTypes } from '@walletconnect/types';

import { POLKADOT_CHAIN_ID } from './wallet-connect';
import { POLKADOT_CHAIN_ID } from './wallet-connect.js';

interface Signature {
signature: HexString;
Expand All @@ -24,9 +23,8 @@ export class WalletConnectSigner implements Signer {
this.registry = new TypeRegistry();
}

// this method is set this way to be bound to this class.
signPayload = async (payload: SignerPayloadJSON): Promise<SignerResult> => {
let request = {
const request = {
topic: this.session.topic,
chainId: `polkadot:${payload.genesisHash.replace('0x', '').substring(0, 32)}`,
request: {
Expand All @@ -36,15 +34,14 @@ export class WalletConnectSigner implements Signer {
params: { address: payload.address, transactionPayload: payload },
},
};
let { signature } = await this.client.request<Signature>(request);

const { signature } = await this.client.request<Signature>(request);

return { id: ++this.id, signature };
};

// this method is set this way to be bound to this class.
// It might be used outside of the object context to sign messages.
// ref: https://polkadot.js.org/docs/extension/cookbook#sign-a-message
signRaw = async (raw: SignerPayloadRaw): Promise<SignerResult> => {
let request = {
const request = {
topic: this.session.topic,
chainId: POLKADOT_CHAIN_ID,
request: {
Expand All @@ -54,7 +51,9 @@ export class WalletConnectSigner implements Signer {
params: { address: raw.address, message: raw.data },
},
};
let { signature } = await this.client.request<Signature>(request);

const { signature } = await this.client.request<Signature>(request);

return { id: ++this.id, signature };
};
}
7 changes: 7 additions & 0 deletions packages/wallet-connect/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { SignClientTypes } from '@walletconnect/types';

export type WcAccount = `${string}:${string}:${string}`;

export type PolkadotNamespaceChainId = `polkadot:${string}`;

export interface WalletConnectConfiguration extends SignClientTypes.Options {
// ToDo: Remove ```projectId``` when the following issue is resolved:
// https://github.com/WalletConnect/walletconnect-monorepo/pull/3435
projectId: string;
chainIds?: PolkadotNamespaceChainId[];
optionalChainIds?: PolkadotNamespaceChainId[];
onSessionDelete?: () => void;
}
93 changes: 67 additions & 26 deletions packages/wallet-connect/src/wallet-connect.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
import type { Account, BaseWallet, BaseWalletProvider, WalletMetadata } from '@polkadot-onboard/core';
import { WalletType } from '@polkadot-onboard/core';
import type { Signer } from '@polkadot/types/types';
import { WalletConnectModal } from '@walletconnect/modal';
import Client, { SignClient } from '@walletconnect/sign-client';
import type { SessionTypes } from '@walletconnect/types';
import type { WalletConnectConfiguration, WcAccount } from './types.js';

import { WalletType } from '@polkadot-onboard/core';
import SignClient from '@walletconnect/sign-client';
import QRCodeModal from '@walletconnect/qrcode-modal';
import { WalletConnectSigner } from './signer.js';
import type { WalletConnectConfiguration, WcAccount } from './types.js';

export const POLKADOT_CHAIN_ID = 'polkadot:91b171bb158e2d3848fa23a9f1c25182';
export const WC_VERSION = '2.0';

const toWalletAccount = (wcAccount: WcAccount) => {
let address = wcAccount.split(':')[2];
return { address };
};
const toWalletAccount = (wcAccount: WcAccount) => ({ address: wcAccount.split(':')[2] });

interface ModalState {
open: boolean;
}

class WalletConnectWallet implements BaseWallet {
type = WalletType.WALLET_CONNECT;
appName: string;
metadata: WalletMetadata;
config: WalletConnectConfiguration;
client: SignClient | undefined;
client: Client | undefined;
signer: Signer | undefined;
session: SessionTypes.Struct | undefined;
walletConnectModal: WalletConnectModal;

constructor(config: WalletConnectConfiguration, appName: string) {
if (!config.chainIds || config.chainIds.length === 0) config.chainIds = [POLKADOT_CHAIN_ID];
Expand All @@ -37,6 +39,10 @@ class WalletConnectWallet implements BaseWallet {
iconUrl: config.metadata?.icons[0] || '',
version: WC_VERSION,
};
this.walletConnectModal = new WalletConnectModal({
projectId: config.projectId,
chains: config.chainIds,
});
}

reset(): void {
Expand All @@ -47,50 +53,84 @@ class WalletConnectWallet implements BaseWallet {

async getAccounts(): Promise<Account[]> {
let accounts: Account[] = [];

if (this.session) {
let wcAccounts = Object.values(this.session.namespaces)
const wcAccounts = Object.values(this.session.namespaces)
.map((namespace) => namespace.accounts)
.flat();

accounts = wcAccounts.map((wcAccount) => toWalletAccount(wcAccount as WcAccount));
}

return accounts;
}

async connect() {
// reset the client
this.reset();

// init the client
let client = await SignClient.init(this.config);
let params = {
this.client = await SignClient.init(this.config);

this.client.on('session_delete', () => {
this.reset();

if (this.config.onSessionDelete) {
this.config.onSessionDelete();
}
});

const namespaces = {
requiredNamespaces: {
polkadot: {
methods: ['polkadot_signTransaction', 'polkadot_signMessage'],
chains: this.config.chainIds,
methods: ['polkadot_signTransaction', 'polkadot_signMessage'],
events: [],
},
},
optionalNamespaces: {
polkadot: {
chains: this.config.optionalChainIds,
methods: ['polkadot_signTransaction', 'polkadot_signMessage'],
events: [],
},
},
};

const { uri, approval } = await client.connect(params);
const lastKeyIndex = this.client.session.getAll().length - 1;
const lastSession = this.client.session.getAll()[lastKeyIndex];

if (lastSession) {
return new Promise<void>((resolve) => {
this.session = lastSession;
this.signer = new WalletConnectSigner(this.client!, lastSession);
resolve();
});
}

const { uri, approval } = await this.client.connect(namespaces);

return new Promise<void>((resolve, reject) => {
// Open QRCode modal if a URI was returned (i.e. we're not connecting an existing pairing).
if (uri) {
QRCodeModal.open(uri, () => {
reject(new Error('Canceled pairing. QR Code Modal closed.'));
});
this.walletConnectModal.openModal({ uri });
}
// Await session approval from the wallet.

const unsubscribeModal = this.walletConnectModal.subscribeModal((state: ModalState) => {
if (state.open === false) {
unsubscribeModal();
resolve();
}
});

approval()
.then((session) => {
// setup the client
this.client = client;
this.session = session;
this.signer = new WalletConnectSigner(client, session);
this.signer = new WalletConnectSigner(this.client!, session);

resolve();
})
.catch(reject)
.finally(() => QRCodeModal.close());
.catch((error) => {
reject(error);
})
.finally(() => this.walletConnectModal.closeModal());
});
}

Expand All @@ -104,6 +144,7 @@ class WalletConnectWallet implements BaseWallet {
},
});
}

this.reset();
}

Expand Down
Loading