feat(dapp-with-solana): sets up client and sol_signTransaction test

This commit is contained in:
Ben Kremer 2022-03-11 18:15:56 +01:00
parent c418007c24
commit ae2a3d2d60
2 changed files with 104 additions and 134 deletions

View File

@ -1,6 +1,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { version } from "@walletconnect/client/package.json"; import { version } from "@walletconnect/client/package.json";
import { formatDirectSignDoc, stringifySignDocValues } from "cosmos-wallet"; import { Keypair, SystemProgram, Transaction } from "@solana/web3.js";
import bs58 from "bs58";
import Banner from "./components/Banner"; import Banner from "./components/Banner";
import Blockchain from "./components/Blockchain"; import Blockchain from "./components/Blockchain";
@ -19,7 +20,7 @@ import {
SLanding, SLanding,
SLayout, SLayout,
} from "./components/app"; } from "./components/app";
import { useWalletConnectClient } from "./contexts/ClientContext"; import { SolanaRpcMethod, useWalletConnectClient } from "./contexts/ClientContext";
interface IFormattedRpcResponse { interface IFormattedRpcResponse {
method?: string; method?: string;
@ -28,14 +29,6 @@ interface IFormattedRpcResponse {
result: string; result: string;
} }
interface CosmosRpcResponse {
pub_key: {
type: string;
value: string;
};
signature: string;
}
export default function App() { export default function App() {
const [isRpcRequestPending, setIsRpcRequestPending] = useState(false); const [isRpcRequestPending, setIsRpcRequestPending] = useState(false);
const [rpcResult, setRpcResult] = useState<IFormattedRpcResponse | null>(); const [rpcResult, setRpcResult] = useState<IFormattedRpcResponse | null>();
@ -53,11 +46,11 @@ export default function App() {
disconnect, disconnect,
chain, chain,
accounts, accounts,
publicKey,
balances, balances,
chainData, chainData,
isInitializing, isInitializing,
onEnable, onEnable,
cosmosProvider,
} = useWalletConnectClient(); } = useWalletConnectClient();
const ping = async () => { const ping = async () => {
@ -87,90 +80,55 @@ export default function App() {
await ping(); await ping();
}; };
const testSignDirect: () => Promise<IFormattedRpcResponse> = async () => { const testSignTransaction = async (): Promise<IFormattedRpcResponse> => {
if (!cosmosProvider) { if (!client || !publicKey || !session) {
throw new Error("cosmosProvider not connected"); throw new Error("WalletConnect Client not initialized properly.");
} }
// test direct sign doc inputs const transaction = new Transaction({ feePayer: publicKey }).add(
const inputs = { SystemProgram.transfer({
fee: [{ amount: "2000", denom: "ucosm" }], fromPubkey: publicKey,
pubkey: "AgSEjOuOr991QlHCORRmdE5ahVKeyBrmtgoYepCpQGOW", toPubkey: Keypair.generate().publicKey,
gasLimit: 200000, lamports: 1,
accountNumber: 1, }),
sequence: 1,
bodyBytes:
"0a90010a1c2f636f736d6f732e62616e6b2e763162657461312e4d736753656e6412700a2d636f736d6f7331706b707472653766646b6c366766727a6c65736a6a766878686c63337234676d6d6b38727336122d636f736d6f7331717970717870713971637273737a673270767871367273307a716733797963356c7a763778751a100a0575636f736d120731323334353637",
authInfoBytes:
"0a500a460a1f2f636f736d6f732e63727970746f2e736563703235366b312e5075624b657912230a21034f04181eeba35391b858633a765c4a0c189697b40d216354d50890d350c7029012040a020801180112130a0d0a0575636f736d12043230303010c09a0c",
};
// format sign doc
const signDoc = formatDirectSignDoc(
inputs.fee,
inputs.pubkey,
inputs.gasLimit,
inputs.accountNumber,
inputs.sequence,
inputs.bodyBytes,
"cosmoshub-4",
); );
const [address] = cosmosProvider.accounts; try {
const signature = await client.request({
// cosmos_signDirect params topic: session.topic,
const params = { request: {
signerAddress: address, method: SolanaRpcMethod.SOL_SIGN_TRANSACTION,
signDoc: stringifySignDocValues(signDoc), params: {
}; feePayer: transaction.feePayer!.toBase58(),
instructions: transaction.instructions.map(i => ({
const result = await cosmosProvider.request<CosmosRpcResponse>({ programId: i.programId.toBase58(),
method: "cosmos_signDirect", data: bs58.encode(i.data),
params, keys: i.keys.map(k => ({
isSigner: k.isSigner,
isWritable: k.isWritable,
pubkey: k.pubkey.toBase58(),
})),
})),
recentBlockhash: transaction.recentBlockhash,
},
},
}); });
return { // @ts-expect-error
method: "cosmos_signDirect", transaction.addSignature(publicKey, bs58.decode(signature));
address,
valid: true,
result: result.signature,
};
};
const testSignAmino: () => Promise<IFormattedRpcResponse> = async () => { return {
if (!cosmosProvider) { method: SolanaRpcMethod.SOL_SIGN_TRANSACTION,
throw new Error("cosmosProvider not connected"); // address,
valid: true,
result: signature,
};
} catch (error: any) {
throw new Error(error);
} }
// test amino sign doc
const signDoc = {
msgs: [],
fee: { amount: [], gas: "23" },
chain_id: "foochain",
memo: "hello, world",
account_number: "7",
sequence: "54",
}; };
const [address] = cosmosProvider.accounts; const getSolanaActions = (): AccountAction[] => {
// cosmos_signAmino params
const params = { signerAddress: address, signDoc };
const result = await cosmosProvider.request<CosmosRpcResponse>({
method: "cosmos_signAmino",
params,
});
return {
method: "cosmos_signAmino",
address,
valid: true,
result: result.signature,
};
};
const getCosmosActions = (): AccountAction[] => {
const wrapRpcRequest = (rpcRequest: () => Promise<IFormattedRpcResponse>) => async () => { const wrapRpcRequest = (rpcRequest: () => Promise<IFormattedRpcResponse>) => async () => {
openRequestModal(); openRequestModal();
try { try {
@ -186,8 +144,10 @@ export default function App() {
}; };
return [ return [
{ method: "cosmos_signDirect", callback: wrapRpcRequest(testSignDirect) }, {
{ method: "cosmos_signAmino", callback: wrapRpcRequest(testSignAmino) }, method: SolanaRpcMethod.SOL_SIGN_TRANSACTION,
callback: wrapRpcRequest(testSignTransaction),
},
]; ];
}; };
@ -212,7 +172,7 @@ export default function App() {
<span>{`Using v${version || "2.0.0-beta"}`}</span> <span>{`Using v${version || "2.0.0-beta"}`}</span>
</h6> </h6>
<SButtonContainer> <SButtonContainer>
<h6>Select Cosmos chain:</h6> <h6>Select chain:</h6>
{chainOptions.map(chainId => ( {chainOptions.map(chainId => (
<Blockchain key={chainId} chainId={chainId} chainData={chainData} onClick={onEnable} /> <Blockchain key={chainId} chainId={chainId} chainData={chainData} onClick={onEnable} />
))} ))}
@ -231,7 +191,7 @@ export default function App() {
address={account} address={account}
chainId={chain} chainId={chain}
balances={balances} balances={balances}
actions={getCosmosActions()} actions={getSolanaActions()}
/> />
); );
})} })}

View File

@ -1,6 +1,6 @@
import Client, { CLIENT_EVENTS } from "@walletconnect/client"; import Client, { CLIENT_EVENTS } from "@walletconnect/client";
import { PairingTypes, SessionTypes } from "@walletconnect/types"; import { PairingTypes, SessionTypes } from "@walletconnect/types";
import CosmosProvider from "@walletconnect/cosmos-provider"; import { ERROR } from "@walletconnect/utils";
import QRCodeModal from "@walletconnect/qrcode-modal"; import QRCodeModal from "@walletconnect/qrcode-modal";
import { import {
createContext, createContext,
@ -11,13 +11,24 @@ import {
useMemo, useMemo,
useState, useState,
} from "react"; } from "react";
import { apiGetChainNamespace, ChainsMap } from "caip-api";
import { PublicKey } from "@solana/web3.js";
import { DEFAULT_LOGGER, DEFAULT_PROJECT_ID, DEFAULT_RELAY_URL } from "../constants"; import { DEFAULT_LOGGER, DEFAULT_PROJECT_ID, DEFAULT_RELAY_URL } from "../constants";
import { AccountBalances, ChainNamespaces, getAllChainNamespaces } from "../helpers"; import { AccountBalances, ChainNamespaces, getAllChainNamespaces } from "../helpers";
import { apiGetChainNamespace, ChainsMap } from "caip-api";
/** /**
* Types * Types
*/ */
export enum SolanaChainId {
Mainnet = "solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",
Devnet = "solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K",
}
export enum SolanaRpcMethod {
SOL_SIGN_TRANSACTION = "sol_signTransaction",
}
interface IContext { interface IContext {
client: Client | undefined; client: Client | undefined;
session: SessionTypes.Created | undefined; session: SessionTypes.Created | undefined;
@ -25,11 +36,11 @@ interface IContext {
isInitializing: boolean; isInitializing: boolean;
chain: string; chain: string;
pairings: string[]; pairings: string[];
publicKey?: PublicKey;
accounts: string[]; accounts: string[];
balances: AccountBalances; balances: AccountBalances;
chainData: ChainNamespaces; chainData: ChainNamespaces;
onEnable: (chainId: string) => Promise<void>; onEnable: (chainId: string) => Promise<void>;
cosmosProvider?: CosmosProvider;
} }
/** /**
@ -45,13 +56,12 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
const [pairings, setPairings] = useState<string[]>([]); const [pairings, setPairings] = useState<string[]>([]);
const [session, setSession] = useState<SessionTypes.Created>(); const [session, setSession] = useState<SessionTypes.Created>();
const [cosmosProvider, setCosmosProvider] = useState<CosmosProvider>();
const [isInitializing, setIsInitializing] = useState(false); const [isInitializing, setIsInitializing] = useState(false);
const [hasCheckedPersistedSession, setHasCheckedPersistedSession] = useState(false); const [hasCheckedPersistedSession, setHasCheckedPersistedSession] = useState(false);
const [balances, setBalances] = useState<AccountBalances>({}); const [balances, setBalances] = useState<AccountBalances>({});
const [accounts, setAccounts] = useState<string[]>([]); const [accounts, setAccounts] = useState<string[]>([]);
const [publicKey, setPublicKey] = useState<PublicKey>();
const [chainData, setChainData] = useState<ChainNamespaces>({}); const [chainData, setChainData] = useState<ChainNamespaces>({});
const [chain, setChain] = useState<string>(""); const [chain, setChain] = useState<string>("");
@ -59,6 +69,7 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
setPairings([]); setPairings([]);
setSession(undefined); setSession(undefined);
setBalances({}); setBalances({});
setPublicKey(undefined);
setAccounts([]); setAccounts([]);
setChain(""); setChain("");
}; };
@ -83,11 +94,17 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
}; };
const disconnect = useCallback(async () => { const disconnect = useCallback(async () => {
if (typeof cosmosProvider === "undefined") { if (typeof client === "undefined") {
throw new Error("cosmosProvider is not initialized"); throw new Error("WalletConnect is not initialized");
} }
await cosmosProvider.disconnect(); if (typeof session === "undefined") {
}, [cosmosProvider]); throw new Error("Session is not connected");
}
await client.disconnect({
topic: session.topic,
reason: ERROR.USER_DISCONNECTED.format(),
});
}, [client, session]);
const _subscribeToClientEvents = useCallback(async (_client: Client) => { const _subscribeToClientEvents = useCallback(async (_client: Client) => {
if (typeof _client === "undefined") { if (typeof _client === "undefined") {
@ -131,46 +148,41 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
} }
}, [_subscribeToClientEvents]); }, [_subscribeToClientEvents]);
const onSessionConnected = useCallback(async (_session: SessionTypes.Settled) => {
const account = _session.state.accounts[0].split(":").pop();
if (!account) {
throw new Error("Could not derive account address from `session.state.accounts`.");
}
const _publicKey = new PublicKey(account);
setSession(_session);
setChain(_session.permissions.blockchain.chains[0]);
setAccounts(_session.state.accounts);
setPublicKey(_publicKey);
}, []);
const onEnable = useCallback( const onEnable = useCallback(
async (caipChainId: string) => { async (caipChainId: string) => {
if (!client) { if (!client) {
throw new ReferenceError("WalletConnect Client is not initialized."); throw new ReferenceError("WalletConnect Client is not initialized.");
} }
const chainId = caipChainId.split(":").pop();
if (!chainId) {
throw new Error("Could not derive chainId from CAIP chainId");
}
console.log("Enabling cosmosProvider for chainId: ", chainId);
// Create WalletConnect Provider
const cosmosProvider = new CosmosProvider({
chains: [chainId],
client,
});
console.log(cosmosProvider);
setCosmosProvider(cosmosProvider);
try { try {
await cosmosProvider.connect(); const _session = await client.connect({
permissions: {
blockchain: { chains: [caipChainId] },
jsonrpc: { methods: [SolanaRpcMethod.SOL_SIGN_TRANSACTION] },
},
});
onSessionConnected(_session);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
return; } finally {
}
const _accounts = cosmosProvider.accounts;
const _session = await client.session.get(client.session.topics[0]);
setAccounts(_accounts);
setSession(_session);
setChain(caipChainId);
QRCodeModal.close(); QRCodeModal.close();
}
}, },
[client], [client, onSessionConnected],
); );
const _checkForPersistedSession = useCallback( const _checkForPersistedSession = useCallback(
@ -184,12 +196,10 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
// populates existing session to state (assume only the top one) // populates existing session to state (assume only the top one)
if (_client.session.topics.length) { if (_client.session.topics.length) {
const _session = await _client.session.get(_client.session.topics[0]); const _session = await _client.session.get(_client.session.topics[0]);
const [namespace, chainId] = _session.state.accounts[0].split(":"); onSessionConnected(_session);
const caipChainId = `${namespace}:${chainId}`;
onEnable(caipChainId);
} }
}, },
[session, onEnable], [session, onSessionConnected],
); );
useEffect(() => { useEffect(() => {
@ -218,6 +228,7 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
pairings, pairings,
isInitializing, isInitializing,
balances, balances,
publicKey,
accounts, accounts,
chain, chain,
client, client,
@ -225,12 +236,12 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect, disconnect,
chainData, chainData,
onEnable, onEnable,
cosmosProvider,
}), }),
[ [
pairings, pairings,
isInitializing, isInitializing,
balances, balances,
publicKey,
accounts, accounts,
chain, chain,
client, client,
@ -238,7 +249,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect, disconnect,
chainData, chainData,
onEnable, onEnable,
cosmosProvider,
], ],
); );