refactor(cosmos): handle RPC requests via cosmosProvider

This commit is contained in:
Ben Kremer 2022-02-23 16:22:32 +01:00
parent a9be9fc4e9
commit cc39f1c52b
2 changed files with 45 additions and 81 deletions

View File

@ -7,14 +7,8 @@ import Blockchain from "./components/Blockchain";
import Column from "./components/Column"; import Column from "./components/Column";
import Header from "./components/Header"; import Header from "./components/Header";
import Modal from "./components/Modal"; import Modal from "./components/Modal";
import { DEFAULT_MAIN_CHAINS, DEFAULT_TEST_CHAINS } from "./constants"; import { DEFAULT_MAIN_CHAINS } from "./constants";
import { import { AccountAction } from "./helpers";
AccountAction,
formatTestTransaction,
getLocalStorageTestnetFlag,
setLocaleStorageTestnetFlag,
} from "./helpers";
import Toggle from "./components/Toggle";
import RequestModal from "./modals/RequestModal"; import RequestModal from "./modals/RequestModal";
import PingModal from "./modals/PingModal"; import PingModal from "./modals/PingModal";
import { import {
@ -24,7 +18,6 @@ import {
SContent, SContent,
SLanding, SLanding,
SLayout, SLayout,
SToggleContainer,
} from "./components/app"; } from "./components/app";
import { useWalletConnectClient } from "./contexts/ClientContext"; import { useWalletConnectClient } from "./contexts/ClientContext";
@ -36,7 +29,6 @@ interface IFormattedRpcResponse {
} }
export default function App() { export default function App() {
const [isTestnet, setIsTestnet] = useState(getLocalStorageTestnetFlag());
const [isRpcRequestPending, setIsRpcRequestPending] = useState(false); const [isRpcRequestPending, setIsRpcRequestPending] = useState(false);
const [rpcResult, setRpcResult] = useState<IFormattedRpcResponse | null>(); const [rpcResult, setRpcResult] = useState<IFormattedRpcResponse | null>();
@ -55,10 +47,8 @@ export default function App() {
accounts, accounts,
balances, balances,
chainData, chainData,
isFetchingBalances,
isInitializing, isInitializing,
onEnable, onEnable,
web3Provider,
cosmosProvider, cosmosProvider,
} = useWalletConnectClient(); } = useWalletConnectClient();
@ -90,9 +80,6 @@ export default function App() {
}; };
const testSignDirect: () => Promise<IFormattedRpcResponse> = async () => { const testSignDirect: () => Promise<IFormattedRpcResponse> = async () => {
if (!web3Provider) {
throw new Error("web3Provider not connected");
}
if (!cosmosProvider) { if (!cosmosProvider) {
throw new Error("cosmosProvider not connected"); throw new Error("cosmosProvider not connected");
} }
@ -147,7 +134,38 @@ export default function App() {
}; };
}; };
// const testSignAmino = null; const testSignAmino: () => Promise<IFormattedRpcResponse> = async () => {
if (!cosmosProvider) {
throw new Error("cosmosProvider not connected");
}
// 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;
// cosmos_signAmino params
const params = { signerAddress: address, signDoc };
const signature = (await cosmosProvider.request({
method: "cosmos_signAmino",
params,
})) as string;
// const valid = utils.verifyMessage(msg, signature) === address;
return {
method: "cosmos_signAmino",
address,
valid: true,
result: signature,
};
};
const getCosmosActions = (): AccountAction[] => { const getCosmosActions = (): AccountAction[] => {
const wrapRpcRequest = (rpcRequest: () => Promise<IFormattedRpcResponse>) => async () => { const wrapRpcRequest = (rpcRequest: () => Promise<IFormattedRpcResponse>) => async () => {
@ -163,14 +181,10 @@ export default function App() {
} }
}; };
return [{ method: "cosmos_signDirect", callback: wrapRpcRequest(testSignDirect) }]; return [
}; { method: "cosmos_signDirect", callback: wrapRpcRequest(testSignDirect) },
{ method: "cosmos_signAmino", callback: wrapRpcRequest(testSignAmino) },
// Toggle between displaying testnet or mainnet chains as selection options. ];
const toggleTestnets = () => {
const nextIsTestnetState = !isTestnet;
setIsTestnet(nextIsTestnetState);
setLocaleStorageTestnetFlag(nextIsTestnetState);
}; };
// Renders the appropriate model for the given request that is currently in-flight. // Renders the appropriate model for the given request that is currently in-flight.
@ -186,7 +200,7 @@ export default function App() {
}; };
const renderContent = () => { const renderContent = () => {
const chainOptions = isTestnet ? DEFAULT_TEST_CHAINS : DEFAULT_MAIN_CHAINS; const chainOptions = DEFAULT_MAIN_CHAINS;
return !accounts.length && !Object.keys(balances).length ? ( return !accounts.length && !Object.keys(balances).length ? (
<SLanding center> <SLanding center>
<Banner /> <Banner />
@ -194,11 +208,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 an Ethereum chain:</h6> <h6>Select Cosmos chain:</h6>
<SToggleContainer>
<p>Testnets Only?</p>
<Toggle active={isTestnet} onClick={toggleTestnets} />
</SToggleContainer>
{chainOptions.map(chainId => ( {chainOptions.map(chainId => (
<Blockchain key={chainId} chainId={chainId} chainData={chainData} onClick={onEnable} /> <Blockchain key={chainId} chainId={chainId} chainData={chainData} onClick={onEnable} />
))} ))}
@ -214,7 +224,6 @@ export default function App() {
key={account} key={account}
active={true} active={true}
chainData={chainData} chainData={chainData}
fetching={isFetchingBalances}
address={account} address={account}
chainId={chain} chainId={chain}
balances={balances} balances={balances}

View File

@ -12,7 +12,6 @@ import {
useState, useState,
} from "react"; } from "react";
import { DEFAULT_LOGGER, DEFAULT_PROJECT_ID, DEFAULT_RELAY_URL } from "../constants"; import { DEFAULT_LOGGER, DEFAULT_PROJECT_ID, DEFAULT_RELAY_URL } from "../constants";
import { providers, utils } from "ethers";
import { AccountBalances, ChainNamespaces, getAllChainNamespaces } from "../helpers"; import { AccountBalances, ChainNamespaces, getAllChainNamespaces } from "../helpers";
import { apiGetChainNamespace, ChainsMap } from "caip-api"; import { apiGetChainNamespace, ChainsMap } from "caip-api";
@ -28,10 +27,8 @@ interface IContext {
pairings: string[]; pairings: string[];
accounts: string[]; accounts: string[];
balances: AccountBalances; balances: AccountBalances;
isFetchingBalances: boolean;
chainData: ChainNamespaces; chainData: ChainNamespaces;
onEnable: (chainId: string) => Promise<void>; onEnable: (chainId: string) => Promise<void>;
web3Provider?: providers.Web3Provider;
cosmosProvider?: CosmosProvider; cosmosProvider?: CosmosProvider;
} }
@ -49,9 +46,7 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
const [session, setSession] = useState<SessionTypes.Created>(); const [session, setSession] = useState<SessionTypes.Created>();
const [cosmosProvider, setCosmosProvider] = useState<CosmosProvider>(); const [cosmosProvider, setCosmosProvider] = useState<CosmosProvider>();
const [web3Provider, setWeb3Provider] = useState<providers.Web3Provider>();
const [isFetchingBalances, setIsFetchingBalances] = useState(false);
const [isInitializing, setIsInitializing] = useState(false); const [isInitializing, setIsInitializing] = useState(false);
const [hasCheckedPersistedSession, setHasCheckedPersistedSession] = useState(false); const [hasCheckedPersistedSession, setHasCheckedPersistedSession] = useState(false);
@ -84,8 +79,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
} }
}), }),
); );
console.log(chainData);
setChainData(chainData); setChainData(chainData);
}; };
@ -146,27 +139,20 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
const chainId = caipChainId.split(":").pop(); const chainId = caipChainId.split(":").pop();
if (!chainId) {
throw new Error("Could not derive chainId from CAIP chainId");
}
console.log("Enabling cosmosProvider for chainId: ", chainId); console.log("Enabling cosmosProvider for chainId: ", chainId);
// Create WalletConnect Provider // Create WalletConnect Provider
const cosmosProvider = new CosmosProvider({ const cosmosProvider = new CosmosProvider({
chains: ["cosmoshub-4"], chains: [chainId],
rpc: {
custom: {
"cosmoshub-4": "https://rpc.cosmos.network/",
},
},
client, client,
}); });
const web3Provider = new providers.Web3Provider(cosmosProvider);
console.log(cosmosProvider); console.log(cosmosProvider);
console.log(web3Provider);
setCosmosProvider(cosmosProvider); setCosmosProvider(cosmosProvider);
setWeb3Provider(web3Provider);
// cosmosProvider.signer.connection.on(SIGNER_EVENTS.uri, ({ uri }) => walletClient.pair({ uri }));
try { try {
await cosmosProvider.connect(); await cosmosProvider.connect();
@ -182,33 +168,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
setSession(_session); setSession(_session);
setChain(caipChainId); setChain(caipChainId);
// TODO:
// try {
// setIsFetchingBalances(true);
// const _balances = await Promise.all(
// _accounts.map(async account => {
// const balance = await web3Provider.getBalance(account);
// return {
// account,
// symbol: "ETH",
// balance: utils.formatEther(balance),
// contractAddress: "",
// };
// }),
// );
// const balancesByAccount = _balances.reduce((obj, balance) => {
// obj[balance.account] = balance;
// return obj;
// }, {} as AccountBalances);
// setBalances(balancesByAccount);
// } catch (error: any) {
// throw new Error(error);
// } finally {
// setIsFetchingBalances(false);
// }
QRCodeModal.close(); QRCodeModal.close();
}, },
[client], [client],
@ -259,7 +218,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
pairings, pairings,
isInitializing, isInitializing,
balances, balances,
isFetchingBalances,
accounts, accounts,
chain, chain,
client, client,
@ -267,14 +225,12 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect, disconnect,
chainData, chainData,
onEnable, onEnable,
web3Provider,
cosmosProvider, cosmosProvider,
}), }),
[ [
pairings, pairings,
isInitializing, isInitializing,
balances, balances,
isFetchingBalances,
accounts, accounts,
chain, chain,
client, client,
@ -282,7 +238,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect, disconnect,
chainData, chainData,
onEnable, onEnable,
web3Provider,
cosmosProvider, cosmosProvider,
], ],
); );