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

View File

@ -12,7 +12,6 @@ import {
useState,
} from "react";
import { DEFAULT_LOGGER, DEFAULT_PROJECT_ID, DEFAULT_RELAY_URL } from "../constants";
import { providers, utils } from "ethers";
import { AccountBalances, ChainNamespaces, getAllChainNamespaces } from "../helpers";
import { apiGetChainNamespace, ChainsMap } from "caip-api";
@ -28,10 +27,8 @@ interface IContext {
pairings: string[];
accounts: string[];
balances: AccountBalances;
isFetchingBalances: boolean;
chainData: ChainNamespaces;
onEnable: (chainId: string) => Promise<void>;
web3Provider?: providers.Web3Provider;
cosmosProvider?: CosmosProvider;
}
@ -49,9 +46,7 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
const [session, setSession] = useState<SessionTypes.Created>();
const [cosmosProvider, setCosmosProvider] = useState<CosmosProvider>();
const [web3Provider, setWeb3Provider] = useState<providers.Web3Provider>();
const [isFetchingBalances, setIsFetchingBalances] = useState(false);
const [isInitializing, setIsInitializing] = useState(false);
const [hasCheckedPersistedSession, setHasCheckedPersistedSession] = useState(false);
@ -84,8 +79,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
}
}),
);
console.log(chainData);
setChainData(chainData);
};
@ -146,27 +139,20 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
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: ["cosmoshub-4"],
rpc: {
custom: {
"cosmoshub-4": "https://rpc.cosmos.network/",
},
},
chains: [chainId],
client,
});
const web3Provider = new providers.Web3Provider(cosmosProvider);
console.log(cosmosProvider);
console.log(web3Provider);
setCosmosProvider(cosmosProvider);
setWeb3Provider(web3Provider);
// cosmosProvider.signer.connection.on(SIGNER_EVENTS.uri, ({ uri }) => walletClient.pair({ uri }));
try {
await cosmosProvider.connect();
@ -182,33 +168,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
setSession(_session);
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();
},
[client],
@ -259,7 +218,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
pairings,
isInitializing,
balances,
isFetchingBalances,
accounts,
chain,
client,
@ -267,14 +225,12 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect,
chainData,
onEnable,
web3Provider,
cosmosProvider,
}),
[
pairings,
isInitializing,
balances,
isFetchingBalances,
accounts,
chain,
client,
@ -282,7 +238,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac
disconnect,
chainData,
onEnable,
web3Provider,
cosmosProvider,
],
);