Skip to content

Commit

Permalink
Merge pull request #220 from cosmos/hkeep/keplr-utils
Browse files Browse the repository at this point in the history
Extract keplr to helpers
  • Loading branch information
abefernan authored Jun 19, 2024
2 parents 3ca6c1d + b88916e commit 1201522
Show file tree
Hide file tree
Showing 16 changed files with 159 additions and 223 deletions.
27 changes: 4 additions & 23 deletions components/dataViews/AccountView/ButtonConnectWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getKeplrKey, useKeplrReconnect } from "@/lib/keplr";
import { cn, toastError } from "@/lib/utils";
import { LoadingStates, WalletInfo, WalletType } from "@/types/signing";
import { makeCosmoshubPath } from "@cosmjs/amino";
Expand All @@ -6,7 +7,7 @@ import { LedgerSigner } from "@cosmjs/ledger-amino";
import TransportWebUSB from "@ledgerhq/hw-transport-webusb";
import { Loader2, Unplug } from "lucide-react";
import Image from "next/image";
import { Dispatch, SetStateAction, useCallback, useLayoutEffect, useState } from "react";
import { Dispatch, SetStateAction, useCallback, useState } from "react";
import { useChains } from "../../../context/ChainsContext";
import { getConnectError } from "../../../lib/errorHelpers";
import { Button } from "../../ui/button";
Expand All @@ -30,16 +31,8 @@ export default function ButtonConnectWallet({
try {
setLoading((oldLoading) => ({ ...oldLoading, keplr: true }));

await window.keplr.enable(chain.chainId);
window.keplr.defaultOptions = {
sign: { preferNoSetFee: true, preferNoSetMemo: true, disableBalanceCheck: true },
};

const { bech32Address: address, pubKey: pubKeyArray } = await window.keplr.getKey(
chain.chainId,
);
const { bech32Address: address, pubKey: pubKeyArray } = await getKeplrKey(chain.chainId);
const pubKey = toBase64(pubKeyArray);

setWalletInfo({ type: "Keplr", address, pubKey });
} catch (e) {
const connectError = getConnectError(e);
Expand All @@ -53,19 +46,7 @@ export default function ButtonConnectWallet({
}
}, [chain.chainId, setWalletInfo]);

useLayoutEffect(() => {
if (!walletInfo?.address) {
return;
}

const accountChangeKey = "keplr_keystorechange";

if (walletInfo.type === "Keplr") {
window.addEventListener(accountChangeKey, connectKeplr);
} else {
window.removeEventListener(accountChangeKey, connectKeplr);
}
}, [connectKeplr, walletInfo]);
useKeplrReconnect(!!walletInfo?.address, connectKeplr);

const connectLedger = async () => {
try {
Expand Down
61 changes: 7 additions & 54 deletions components/dataViews/ListMultisigTxs.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
import { useChains } from "@/context/ChainsContext";
import { ellideMiddle } from "@/lib/displayHelpers";
import { getConnectError } from "@/lib/errorHelpers";
import { getKeplrKey, getKeplrVerifySignature, useKeplrReconnect } from "@/lib/keplr";
import { requestJson } from "@/lib/request";
import { msgTypeCountsFromJson } from "@/lib/txMsgHelpers";
import { cn, toastError } from "@/lib/utils";
import { DbNonce, DbTransaction } from "@/types";
import { DbNonce, DbTransaction } from "@/types/db";
import { WalletInfo } from "@/types/signing";
import { toBase64 } from "@cosmjs/encoding";
import { StargateClient } from "@cosmjs/stargate";
import { Loader2, MoveRightIcon } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useCallback, useLayoutEffect, useState } from "react";
import { useCallback, useState } from "react";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
import { Label } from "../ui/label";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";

// Show pending default. Toggle con show already broadcasted too

interface ListMultisigTxsProps {
readonly multisigAddress: string;
readonly multisigThreshold: number;
Expand Down Expand Up @@ -52,36 +51,10 @@ export default function ListMultisigTxs({
`/api/chain/${chain.chainId}/nonce/${accountOnChain.address}`,
);

const { signature } = await window.keplr.signAmino(chain.chainId, accountOnChain.address, {
chain_id: "",
account_number: "0",
sequence: "0",
fee: { gas: "0", amount: [] },
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: accountOnChain.address,
data: toBase64(
new Uint8Array(
Buffer.from(
JSON.stringify({
title: `Keplr Login to ${chain.chainDisplayName}`,
description: "Sign this no fee transaction to login with your Keplr wallet",
nonce,
}),
),
),
),
},
},
],
memo: "",
});

const signature = await getKeplrVerifySignature(accountOnChain.address, chain, nonce);
return signature;
},
[chain.chainDisplayName, chain.chainId, chain.nodeAddress],
[chain],
);

const fetchTransactions = useCallback(
Expand Down Expand Up @@ -112,17 +85,8 @@ export default function ListMultisigTxs({
try {
setLoading(true);

await window.keplr.enable(chain.chainId);
window.keplr.defaultOptions = {
sign: { preferNoSetFee: true, preferNoSetMemo: true, disableBalanceCheck: true },
};

const { bech32Address: address, pubKey: pubKeyArray } = await window.keplr.getKey(
chain.chainId,
);

const { bech32Address: address, pubKey: pubKeyArray } = await getKeplrKey(chain.chainId);
const pubKey = toBase64(pubKeyArray);

setWalletInfo({ address, pubKey });

await fetchTransactions(address);
Expand All @@ -138,18 +102,7 @@ export default function ListMultisigTxs({
}
}, [chain.chainId, fetchTransactions]);

useLayoutEffect(() => {
if (!walletInfo?.address) {
return;
}

const accountChangeKey = "keplr_keystorechange";
window.addEventListener(accountChangeKey, connectWallet);

return () => {
window.removeEventListener(accountChangeKey, connectWallet);
};
}, [connectWallet, walletInfo?.address]);
useKeplrReconnect(!!walletInfo?.address, connectWallet);

return (
<Card>
Expand Down
59 changes: 7 additions & 52 deletions components/dataViews/ListUserMultisigs.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { useChains } from "@/context/ChainsContext";
import { getConnectError } from "@/lib/errorHelpers";
import { MultisigFromQuery } from "@/lib/graphqlHelpers";
import { getKeplrKey, getKeplrVerifySignature, useKeplrReconnect } from "@/lib/keplr";
import { requestJson } from "@/lib/request";
import { toastError } from "@/lib/utils";
import { DbNonce } from "@/types";
import { DbNonce } from "@/types/db";
import { WalletInfo } from "@/types/signing";
import { MultisigThresholdPubkey } from "@cosmjs/amino";
import { toBase64 } from "@cosmjs/encoding";
import { StargateClient } from "@cosmjs/stargate";
import { Loader2, MoveRightIcon } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useCallback, useLayoutEffect, useState } from "react";
import { useCallback, useState } from "react";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
Expand Down Expand Up @@ -44,36 +45,10 @@ export default function ListUserMultisigs() {
`/api/chain/${chain.chainId}/nonce/${accountOnChain.address}`,
);

const { signature } = await window.keplr.signAmino(chain.chainId, accountOnChain.address, {
chain_id: "",
account_number: "0",
sequence: "0",
fee: { gas: "0", amount: [] },
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: accountOnChain.address,
data: toBase64(
new Uint8Array(
Buffer.from(
JSON.stringify({
title: `Keplr Login to ${chain.chainDisplayName}`,
description: "Sign this no fee transaction to login with your Keplr wallet",
nonce,
}),
),
),
),
},
},
],
memo: "",
});

const signature = await getKeplrVerifySignature(accountOnChain.address, chain, nonce);
return signature;
},
[chain.chainDisplayName, chain.chainId, chain.nodeAddress],
[chain],
);

const fetchMultisigs = useCallback(
Expand Down Expand Up @@ -104,17 +79,8 @@ export default function ListUserMultisigs() {
try {
setLoading(true);

await window.keplr.enable(chain.chainId);
window.keplr.defaultOptions = {
sign: { preferNoSetFee: true, preferNoSetMemo: true, disableBalanceCheck: true },
};

const { bech32Address: address, pubKey: pubKeyArray } = await window.keplr.getKey(
chain.chainId,
);

const { bech32Address: address, pubKey: pubKeyArray } = await getKeplrKey(chain.chainId);
const pubKey = toBase64(pubKeyArray);

setWalletInfo({ address, pubKey });

await fetchMultisigs(address);
Expand All @@ -130,18 +96,7 @@ export default function ListUserMultisigs() {
}
}, [chain.chainId, fetchMultisigs]);

useLayoutEffect(() => {
if (!walletInfo?.address) {
return;
}

const accountChangeKey = "keplr_keystorechange";
window.addEventListener(accountChangeKey, connectWallet);

return () => {
window.removeEventListener(accountChangeKey, connectWallet);
};
}, [connectWallet, walletInfo?.address]);
useKeplrReconnect(!!walletInfo?.address, connectWallet);

return (
<Card>
Expand Down
8 changes: 2 additions & 6 deletions components/dataViews/MultisigView/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { isChainInfoFilled } from "@/context/ChainsContext/helpers";
import { checkAddress } from "@/lib/displayHelpers";
import { getKeplrKey } from "@/lib/keplr";
import {
HostedMultisig,
createMultisigFromCompressedSecp256k1Pubkeys,
Expand Down Expand Up @@ -44,12 +45,7 @@ export default function MultisigView() {
"Pubkey on chain is not of type MultisigThreshold",
);

await window.keplr.enable(chain.chainId);
window.keplr.defaultOptions = {
sign: { preferNoSetFee: true, preferNoSetMemo: true, disableBalanceCheck: true },
};

const { bech32Address: address } = await window.keplr.getKey(chain.chainId);
const { bech32Address: address } = await getKeplrKey(chain.chainId);

await createMultisigFromCompressedSecp256k1Pubkeys(
newHostedMultisig.accountOnChain.pubkey.value.pubkeys.map((p) => p.value),
Expand Down
2 changes: 1 addition & 1 deletion components/dataViews/ThresholdInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DbSignature } from "@/types/db";
import { MultisigThresholdPubkey } from "@cosmjs/amino";
import { useEffect, useState } from "react";
import { DbSignature } from "../../types";
import StackableContainer from "../layout/StackableContainer";
import CopyAndPaste from "./CopyAndPaste";

Expand Down
4 changes: 2 additions & 2 deletions components/dataViews/TransactionInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { DbTransactionJsonObj } from "@/types/db";
import { MsgTypeUrls } from "@/types/txMsg";
import { EncodeObject } from "@cosmjs/proto-signing";
import { useChains } from "../../../context/ChainsContext";
import { printableCoins } from "../../../lib/displayHelpers";
import { DbTransactionJsonObj } from "../../../types";
import { MsgTypeUrls } from "../../../types/txMsg";
import StackableContainer from "../../layout/StackableContainer";
import TxMsgBeginRedelegateDetails from "./TxMsgBeginRedelegateDetails";
import TxMsgCreateVestingAccountDetails from "./TxMsgCreateVestingAccountDetails";
Expand Down
8 changes: 2 additions & 6 deletions components/forms/CreateMultisigForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { getKeplrKey } from "@/lib/keplr";
import { toastError } from "@/lib/utils";
import { StargateClient } from "@cosmjs/stargate";
import { zodResolver } from "@hookform/resolvers/zod";
Expand Down Expand Up @@ -91,12 +92,7 @@ export default function CreateMultisigForm() {
);

try {
await window.keplr.enable(chain.chainId);
window.keplr.defaultOptions = {
sign: { preferNoSetFee: true, preferNoSetMemo: true, disableBalanceCheck: true },
};

const { bech32Address: address } = await window.keplr.getKey(chain.chainId);
const { bech32Address: address } = await getKeplrKey(chain.chainId);

const multisigAddress = await createMultisigFromCompressedSecp256k1Pubkeys(
pubkeys,
Expand Down
4 changes: 2 additions & 2 deletions components/forms/CreateTxForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { loadValidators } from "@/context/ChainsContext/helpers";
import { toastError, toastSuccess } from "@/lib/utils";
import { DbTransactionJsonObj } from "@/types/db";
import { MsgTypeUrl, MsgTypeUrls } from "@/types/txMsg";
import { EncodeObject } from "@cosmjs/proto-signing";
import { Account, calculateFee } from "@cosmjs/stargate";
import { assert, sleep } from "@cosmjs/utils";
Expand All @@ -9,8 +11,6 @@ import { toast } from "sonner";
import { useChains } from "../../../context/ChainsContext";
import { requestJson } from "../../../lib/request";
import { exportMsgToJson, gasOfTx } from "../../../lib/txMsgHelpers";
import { DbTransactionJsonObj } from "../../../types";
import { MsgTypeUrl, MsgTypeUrls } from "../../../types/txMsg";
import Button from "../../inputs/Button";
import Input from "../../inputs/Input";
import StackableContainer from "../../layout/StackableContainer";
Expand Down
Loading

0 comments on commit 1201522

Please sign in to comment.