diff --git a/components/dataViews/ListMultisigTxs.tsx b/components/dataViews/ListMultisigTxs.tsx new file mode 100644 index 0000000..7f14506 --- /dev/null +++ b/components/dataViews/ListMultisigTxs.tsx @@ -0,0 +1,265 @@ +import { useChains } from "@/context/ChainsContext"; +import { ellideMiddle } from "@/lib/displayHelpers"; +import { getConnectError } from "@/lib/errorHelpers"; +import { requestJson } from "@/lib/request"; +import { msgTypeCountsFromJson } from "@/lib/txMsgHelpers"; +import { cn, toastError } from "@/lib/utils"; +import { DbNonce, DbTransaction } from "@/types"; +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 { 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; +} + +export default function ListMultisigTxs({ + multisigAddress, + multisigThreshold, +}: ListMultisigTxsProps) { + const { chain } = useChains(); + + const [loading, setLoading] = useState(false); + const [walletInfo, setWalletInfo] = useState | null>(null); + const [showBroadcasted, setShowBroadcasted] = useState(false); + const [transactions, setTransactions] = useState(null); + + const pendingTxs = transactions?.filter(({ txHash }) => !txHash) ?? null; + + const getSignature = useCallback( + async (address: string) => { + const client = await StargateClient.connect(chain.nodeAddress); + const accountOnChain = await client.getAccount(address); + + if (!accountOnChain) { + throw new Error(`Account not found on chain for ${address}`); + } + + const { nonce }: DbNonce = await requestJson( + `/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: "", + }); + + return signature; + }, + [chain.chainDisplayName, chain.chainId, chain.nodeAddress], + ); + + const fetchTransactions = useCallback( + async (address: string) => { + try { + const signature = await getSignature(address); + + const fetchedTransactions: readonly DbTransaction[] = await requestJson( + `/api/transaction/list`, + { + body: { signature, chain, multisigAddress }, + }, + ); + + setTransactions(fetchedTransactions); + } catch (e: unknown) { + console.error("Failed to fetch transactions:", e); + toastError({ + description: "Failed to fetch transactions", + fullError: e instanceof Error ? e : undefined, + }); + } + }, + [chain, getSignature, multisigAddress], + ); + + const connectWallet = useCallback(async () => { + 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 pubKey = toBase64(pubKeyArray); + + setWalletInfo({ address, pubKey }); + + await fetchTransactions(address); + } catch (e) { + const connectError = getConnectError(e); + console.error(connectError, e); + toastError({ + description: connectError, + fullError: e instanceof Error ? e : undefined, + }); + } finally { + setLoading(false); + } + }, [chain.chainId, fetchTransactions]); + + useLayoutEffect(() => { + if (!walletInfo?.address) { + return; + } + + const accountChangeKey = "keplr_keystorechange"; + window.addEventListener(accountChangeKey, connectWallet); + + return () => { + window.removeEventListener(accountChangeKey, connectWallet); + }; + }, [connectWallet, walletInfo?.address]); + + return ( + + + Transactions + + The list of transactions created by this multisig. Verify your identity with Keplr by + signing a message for free. + + + + {!walletInfo && !transactions ? ( + + ) : null} + {walletInfo && !transactions ? ( +
+ +

Loading transactions

+
+ ) : null} + {!showBroadcasted && pendingTxs && !pendingTxs.length + ? "No pending transactions found" + : null} + {showBroadcasted && transactions && !transactions.length ? "No transactions found" : null} + {transactions?.length || pendingTxs?.length ? ( + <> + {transactions?.length !== pendingTxs?.length ? ( +
+ { + setShowBroadcasted(checked); + }} + /> + +
+ ) : null} +
+ {((showBroadcasted ? transactions : pendingTxs) ?? []).map((tx) => { + const msgTypeCounts = msgTypeCountsFromJson(tx.dataJSON); + const hasSigned = Boolean( + tx.signatures.find(({ address }) => address === walletInfo?.address), + ); + + return ( + + + + + {tx.signatures.length}/{multisigThreshold} + + + +
+

signatures: {tx.signatures.length}

+

threshold: {multisigThreshold}

+

{hasSigned ? "Signed by you" : "Not signed by you"}

+

+ {tx.txHash + ? `Broadcasted with hash: ${ellideMiddle(tx.txHash, 12)}` + : "Not broadcasted"} +

+
+
+
+
+
+ {msgTypeCounts.map(({ msgType, count }) => ( + + {msgType} + {count > 1 ? ` (${count})` : ""} + + ))} +
+
+

{tx.id}

+
+
+ + + ); + })} +
+ + ) : null} +
+
+ ); +} diff --git a/components/dataViews/ListUserMultisigs.tsx b/components/dataViews/ListUserMultisigs.tsx new file mode 100644 index 0000000..54ea7be --- /dev/null +++ b/components/dataViews/ListUserMultisigs.tsx @@ -0,0 +1,234 @@ +import { useChains } from "@/context/ChainsContext"; +import { getConnectError } from "@/lib/errorHelpers"; +import { MultisigFromQuery } from "@/lib/graphqlHelpers"; +import { requestJson } from "@/lib/request"; +import { toastError } from "@/lib/utils"; +import { DbNonce } from "@/types"; +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 { 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"; + +type FetchedMultisigs = { + readonly created: readonly MultisigFromQuery[]; + readonly belonged: readonly MultisigFromQuery[]; +}; + +export default function ListUserMultisigs() { + const { chain } = useChains(); + const [loading, setLoading] = useState(false); + const [walletInfo, setWalletInfo] = useState | null>(null); + const [showBelonged, setShowBelonged] = useState(false); + const [multisigs, setMultisigs] = useState(null); + + const getSignature = useCallback( + async (address: string) => { + const client = await StargateClient.connect(chain.nodeAddress); + const accountOnChain = await client.getAccount(address); + + if (!accountOnChain) { + throw new Error(`Account not found on chain for ${address}`); + } + + const { nonce }: DbNonce = await requestJson( + `/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: "", + }); + + return signature; + }, + [chain.chainDisplayName, chain.chainId, chain.nodeAddress], + ); + + const fetchMultisigs = useCallback( + async (address: string) => { + try { + const signature = await getSignature(address); + + const newMultisigs: FetchedMultisigs = await requestJson( + `/api/chain/${chain.chainId}/multisig/list`, + { + body: { signature, chain }, + }, + ); + + setMultisigs(newMultisigs); + } catch (e: unknown) { + console.error("Failed to fetch multisigs:", e); + toastError({ + description: "Failed to fetch multisigs", + fullError: e instanceof Error ? e : undefined, + }); + } + }, + [chain, getSignature], + ); + + const connectWallet = useCallback(async () => { + 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 pubKey = toBase64(pubKeyArray); + + setWalletInfo({ address, pubKey }); + + await fetchMultisigs(address); + } catch (e) { + const connectError = getConnectError(e); + console.error(connectError, e); + toastError({ + description: connectError, + fullError: e instanceof Error ? e : undefined, + }); + } finally { + setLoading(false); + } + }, [chain.chainId, fetchMultisigs]); + + useLayoutEffect(() => { + if (!walletInfo?.address) { + return; + } + + const accountChangeKey = "keplr_keystorechange"; + window.addEventListener(accountChangeKey, connectWallet); + + return () => { + window.removeEventListener(accountChangeKey, connectWallet); + }; + }, [connectWallet, walletInfo?.address]); + + return ( + + + Multisigs + + Your list of created multisigs on {chain.chainDisplayName}. Verify your identity with + Keplr by signing a message for free. + + + + {!walletInfo && !multisigs ? ( + + ) : null} + {walletInfo && !multisigs ? ( +
+ +

Loading multisigs

+
+ ) : null} + {!showBelonged && multisigs && !multisigs.created.length + ? "You have not created any multisig" + : null} + {showBelonged && multisigs && !multisigs.belonged.length + ? "You are not a member of any multisig" + : null} + {multisigs?.created.length || multisigs?.belonged.length ? ( + <> + {multisigs.created.length !== multisigs.belonged.length ? ( +
+ { + setShowBelonged(checked); + }} + /> + +
+ ) : null} +
+ {(showBelonged ? multisigs.belonged : multisigs.created).map((multisig) => { + const pubkey: MultisigThresholdPubkey = JSON.parse(multisig.pubkeyJSON); + + return ( + + + + + {pubkey.value.threshold} / {pubkey.value.pubkeys.length} + + + +
+

threshold: {pubkey.value.threshold}

+

members: {pubkey.value.pubkeys.length}

+
+
+
+
+

{multisig.address}

+
+ + + ); + })} +
+ + ) : null} +
+
+ ); +} diff --git a/components/dataViews/MultisigView/index.tsx b/components/dataViews/MultisigView/index.tsx index 1c12641..2bb2695 100644 --- a/components/dataViews/MultisigView/index.tsx +++ b/components/dataViews/MultisigView/index.tsx @@ -19,6 +19,7 @@ import { toast } from "sonner"; import { useChains } from "../../../context/ChainsContext"; import { Button } from "../../ui/button"; import BalancesTable from "../BalancesTable"; +import ListMultisigTxs from "../ListMultisigTxs"; export default function MultisigView() { const router = useRouter(); @@ -43,11 +44,19 @@ 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); + await createMultisigFromCompressedSecp256k1Pubkeys( newHostedMultisig.accountOnChain.pubkey.value.pubkeys.map((p) => p.value), Number(newHostedMultisig.accountOnChain.pubkey.value.threshold), chain.addressPrefix, chain.chainId, + address, ); router.reload(); @@ -204,6 +213,12 @@ export default function MultisigView() { ) : null} + {hostedMultisig?.hosted === "db+chain" && multisigAddress ? ( + + ) : null} ); } diff --git a/components/dataViews/TransactionInfo/index.tsx b/components/dataViews/TransactionInfo/index.tsx index a6868b2..863e15b 100644 --- a/components/dataViews/TransactionInfo/index.tsx +++ b/components/dataViews/TransactionInfo/index.tsx @@ -1,7 +1,7 @@ import { EncodeObject } from "@cosmjs/proto-signing"; import { useChains } from "../../../context/ChainsContext"; import { printableCoins } from "../../../lib/displayHelpers"; -import { DbTransaction } from "../../../types"; +import { DbTransactionJsonObj } from "../../../types"; import { MsgTypeUrls } from "../../../types/txMsg"; import StackableContainer from "../../layout/StackableContainer"; import TxMsgBeginRedelegateDetails from "./TxMsgBeginRedelegateDetails"; @@ -65,7 +65,7 @@ const TxMsgDetails = ({ typeUrl, value: msgValue }: EncodeObject) => { }; interface TransactionInfoProps { - readonly tx: DbTransaction; + readonly tx: DbTransactionJsonObj; } const TransactionInfo = ({ tx }: TransactionInfoProps) => { diff --git a/components/forms/CreateMultisigForm/index.tsx b/components/forms/CreateMultisigForm/index.tsx index 5a91588..475e39d 100644 --- a/components/forms/CreateMultisigForm/index.tsx +++ b/components/forms/CreateMultisigForm/index.tsx @@ -91,11 +91,19 @@ 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 multisigAddress = await createMultisigFromCompressedSecp256k1Pubkeys( pubkeys, Number(threshold), chain.addressPrefix, chain.chainId, + address, ); router.push(`/${chain.registryName}/${multisigAddress}`); diff --git a/components/forms/CreateTxForm/index.tsx b/components/forms/CreateTxForm/index.tsx index 2ef46c0..4d0b05b 100644 --- a/components/forms/CreateTxForm/index.tsx +++ b/components/forms/CreateTxForm/index.tsx @@ -9,7 +9,7 @@ import { toast } from "sonner"; import { useChains } from "../../../context/ChainsContext"; import { requestJson } from "../../../lib/request"; import { exportMsgToJson, gasOfTx } from "../../../lib/txMsgHelpers"; -import { DbTransaction } from "../../../types"; +import { DbTransactionJsonObj } from "../../../types"; import { MsgTypeUrl, MsgTypeUrls } from "../../../types/txMsg"; import Button from "../../inputs/Button"; import Input from "../../inputs/Input"; @@ -82,7 +82,7 @@ const CreateTxForm = ({ router, senderAddress, accountOnChain }: CreateTxFormPro return; } - const tx: DbTransaction = { + const tx: DbTransactionJsonObj = { accountNumber: accountOnChain.accountNumber, sequence: accountOnChain.sequence, chainId: chain.chainId, @@ -92,7 +92,11 @@ const CreateTxForm = ({ router, senderAddress, accountOnChain }: CreateTxFormPro }; const { transactionID } = await requestJson("/api/transaction", { - body: { dataJSON: JSON.stringify(tx) }, + body: { + dataJSON: JSON.stringify(tx), + creator: accountOnChain.address, + chainId: chain.chainId, + }, }); toastSuccess("Transaction created with ID", transactionID); router.push(`/${chain.registryName}/${senderAddress}/transaction/${transactionID}`); diff --git a/components/forms/TransactionSigning.tsx b/components/forms/TransactionSigning.tsx index bdc4c3d..388ba3e 100644 --- a/components/forms/TransactionSigning.tsx +++ b/components/forms/TransactionSigning.tsx @@ -4,7 +4,7 @@ import { MultisigThresholdPubkey, makeCosmoshubPath } from "@cosmjs/amino"; import { createWasmAminoConverters, wasmTypes } from "@cosmjs/cosmwasm-stargate"; import { toBase64 } from "@cosmjs/encoding"; import { LedgerSigner } from "@cosmjs/ledger-amino"; -import { Registry } from "@cosmjs/proto-signing"; +import { OfflineSigner, Registry } from "@cosmjs/proto-signing"; import { AminoTypes, SigningStargateClient, @@ -18,14 +18,14 @@ import { toast } from "sonner"; import { useChains } from "../../context/ChainsContext"; import { getConnectError } from "../../lib/errorHelpers"; import { requestJson } from "../../lib/request"; -import { DbSignature, DbTransaction, WalletAccount } from "../../types"; +import { DbSignature, DbTransactionJsonObj, WalletAccount } from "../../types"; import HashView from "../dataViews/HashView"; import Button from "../inputs/Button"; import StackableContainer from "../layout/StackableContainer"; interface TransactionSigningProps { readonly signatures: DbSignature[]; - readonly tx: DbTransaction; + readonly tx: DbTransactionJsonObj; readonly pubkey: MultisigThresholdPubkey; readonly transactionID: string; readonly addSignature: (signature: DbSignature) => void; @@ -38,7 +38,7 @@ const TransactionSigning = (props: TransactionSigningProps) => { const [walletAccount, setWalletAccount] = useState(); const [signing, setSigning] = useState("not_signed"); const [walletType, setWalletType] = useState<"Keplr" | "Ledger">(); - const [ledgerSigner, setLedgerSigner] = useState({}); + const [ledgerSigner, setLedgerSigner] = useState(null); const [loading, setLoading] = useState({}); const connectKeplr = useCallback(async () => { @@ -146,7 +146,13 @@ const TransactionSigning = (props: TransactionSigningProps) => { setLoading((newLoading) => ({ ...newLoading, signing: true })); const offlineSigner = - walletType === "Keplr" ? window.getOfflineSignerOnlyAmino(chain.chainId) : ledgerSigner; + walletType === "Keplr" + ? window.keplr.getOfflineSignerOnlyAmino(chain.chainId) + : ledgerSigner; + + if (!offlineSigner) { + throw new Error("Offline signer not found"); + } const signerAddress = walletAccount?.bech32Address; assert(signerAddress, "Missing signer address"); diff --git a/db-schema.graphql b/db-schema.graphql index a376c75..23d55b3 100644 --- a/db-schema.graphql +++ b/db-schema.graphql @@ -5,12 +5,15 @@ type Multisig { # See https://dgraph.io/docs/graphql/schema/directives/search/#string chainId: String! @search(by: [hash]) address: String! @search(by: [hash]) - pubkeyJSON: String! + creator: String @search(by: [hash]) + pubkeyJSON: String! @search(by: [fulltext]) + transactions: [Transaction] @hasInverse(field: creator) } type Transaction { id: ID! txHash: String + creator: Multisig dataJSON: String signatures: [Signature] @hasInverse(field: transaction) } @@ -21,3 +24,10 @@ type Signature { signature: String! address: String! } + +type Nonce { + id: ID! + chainId: String! @search(by: [hash]) + address: String! @search(by: [hash]) + nonce: Int! +} diff --git a/lib/graphqlHelpers.ts b/lib/graphqlHelpers.ts index 836f153..9b9d1a3 100644 --- a/lib/graphqlHelpers.ts +++ b/lib/graphqlHelpers.ts @@ -1,4 +1,4 @@ -import { DbAccount, DbSignature, DbTransaction } from "../types"; +import { DbMultisig, DbNonce, DbSignature, DbTransaction, DbTransactionJsonObj } from "../types"; import { requestGraphQlJson } from "./request"; /** @@ -7,7 +7,7 @@ import { requestGraphQlJson } from "./request"; * @param {object} multisig an object with address (string), pubkey JSON and chainId * @return Returns async function that makes a request to the dgraph graphql endpoint */ -const createMultisig = async (multisig: DbAccount) => { +const createMultisig = async (multisig: DbMultisig) => { return requestGraphQlJson({ body: { query: ` @@ -16,6 +16,7 @@ const createMultisig = async (multisig: DbAccount) => { input: { chainId: "${multisig.chainId}" address: "${multisig.address}" + creator: "${multisig.creator}" pubkeyJSON: ${JSON.stringify(multisig.pubkeyJSON)} } ) { @@ -38,7 +39,7 @@ const createMultisig = async (multisig: DbAccount) => { * we return the full object in the API. Right now address and chainId * are somewhat unnecessary to query but still nice for debgging. */ -interface MultisigFromQuery { +export interface MultisigFromQuery { address: string; chainId: string; pubkeyJSON: string; @@ -51,10 +52,7 @@ interface MultisigFromQuery { * @param {string} chainId The chainId the multisig belongs to. * @return Returns async function that makes a request to the dgraph graphql endpoint */ -async function getMultisig( - address: string, - chainId: string, -): Promise { +async function getMultisig(address: string, chainId: string): Promise { const result = await requestGraphQlJson({ body: { query: ` @@ -68,9 +66,95 @@ async function getMultisig( `, }, }); - const elements: [MultisigFromQuery] = result.data.queryMultisig; - const first = elements.find(() => true); - return first; + + const elements: readonly MultisigFromQuery[] = result.data.queryMultisig; + return elements.length ? elements[0] : null; +} + +/** + * Gets multisig id from DB + * + * @param {string} address A multisig address. + * @param {string} chainId The chainId the multisig belongs to. + * @return Returns async function that makes a request to the dgraph graphql endpoint + */ +async function getMultisigId(address: string, chainId: string): Promise { + const result = await requestGraphQlJson({ + body: { + query: ` + query MultisigsByAddressAndChainId { + queryMultisig(filter: {address: {eq: "${address}"}, chainId: {eq: "${chainId}"}}) { + id + } + } + `, + }, + }); + + const elements: readonly (MultisigFromQuery & { id: string })[] = result.data.queryMultisig; + return elements.length ? elements[0].id : null; +} + +/** + * Gets list of multisigs from DB + * + * @param {string} chainId The chainId the multisig belongs to. + * @param {string} creator The address of the creator of the multisig. + * @return Returns async function that makes a request to the dgraph graphql endpoint + */ +async function getCreatedMultisigs(chainId: string, creator: string) { + const result = await requestGraphQlJson({ + body: { + query: ` + query MultisigsByChainIdAndCreator { + queryMultisig(filter: {chainId: {eq: "${chainId}"}, creator: {eq: "${creator}"}}) { + address + chainId + pubkeyJSON + } + } + `, + }, + }); + + const elements: readonly MultisigFromQuery[] = result.data.queryMultisig.filter( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (el: MultisigFromQuery | null, i: number, arr: any) => + el !== null && i === arr.findIndex((el2: MultisigFromQuery) => el2.address === el.address), + ); + + return elements; +} + +/** + * Gets list of multisigs from DB + * + * @param {string} chainId The chainId the multisig belongs to. + * @param {string} creator The address of a member of the multisig. + * @return Returns async function that makes a request to the dgraph graphql endpoint + */ +async function getBelongedMultisigs(chainId: string, memberPubkey: string) { + const result = await requestGraphQlJson({ + body: { + query: ` + query MultisigsByChainIdAndCreator { + queryMultisig(filter: {chainId: {eq: "${chainId}"}, pubkeyJSON: {alloftext: "${memberPubkey}"}}) { + address + chainId + pubkeyJSON + } + } + `, + }, + }); + + const elements: readonly MultisigFromQuery[] = result.data.queryMultisig.filter( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (el: MultisigFromQuery | null, i: number, arr: any) => + el !== null && i === arr.findIndex((el2: MultisigFromQuery) => el2.address === el.address), + ); + + return elements; } /** @@ -79,12 +163,14 @@ async function getMultisig( * @param {object} transaction The base transaction * @return Returns async function that makes a request to the dgraph graphql endpoint */ -const createTransaction = async (transaction: DbTransaction) => { +const createTransaction = async (transaction: DbTransactionJsonObj, creator: string) => { return requestGraphQlJson({ body: { query: ` mutation AddTransaction { - addTransaction(input: { dataJSON: ${JSON.stringify(transaction)} }) { + addTransaction(input: { dataJSON: ${JSON.stringify( + transaction, + )}, creator: {id: "${creator}"}}) { transaction { id } @@ -121,6 +207,31 @@ const findTransactionByID = async (id: string) => { }); }; +const getTransactions = async (creator: string): Promise => { + const result = await requestGraphQlJson({ + body: { + query: ` + query GetTransactionsByCreator { + getMultisig(id: "${creator}") { + transactions { + id + txHash + dataJSON + signatures { + bodyBytes + signature + address + } + } + } + } + `, + }, + }); + + return result.data.getMultisig.transactions; +}; + /** * Updates txHash of transaction on dgraph * @@ -186,11 +297,88 @@ const createSignature = async (signature: DbSignature, transactionId: string) => }); }; +const nonceFromDbNonces = (dbNonces: readonly DbNonce[]): DbNonce | null => { + const elements: readonly DbNonce[] = dbNonces.filter((el: DbNonce | null) => el !== null); + const dbNonce = elements.length ? elements[0] : null; + return dbNonce; +}; + +async function createNonce(chainId: string, address: string): Promise { + const result = await requestGraphQlJson({ + body: { + query: ` + mutation AddNonce { + addNonce(input: {chainId: "${chainId}", address: "${address}", nonce: 0}) { + nonce { + chainId + address + nonce + } + } + } + `, + }, + }); + + return nonceFromDbNonces(result.data.addNonce.nonce); +} + +async function getNonce(chainId: string, address: string): Promise { + const result = await requestGraphQlJson({ + body: { + query: ` + query NonceByChainIdAndAddress { + queryNonce(filter: {chainId: {eq: "${chainId}"}, address: {eq: "${address}"}}) { + chainId + address + nonce + } + } + `, + }, + }); + + console.log({ result }); + + return nonceFromDbNonces(result.data.queryNonce); +} + +async function updateNonce( + chainId: string, + address: string, + newNonce: number, +): Promise { + const result = await requestGraphQlJson({ + body: { + query: ` + mutation UpdateNonce { + updateNonce(input: {filter: {chainId: {eq: "${chainId}"}, address: {eq: "${address}"}}, set: {nonce: ${newNonce}}}) { + nonce { + chainId + address + nonce + } + } + } + `, + }, + }); + + return nonceFromDbNonces(result.data.updateNonce.nonce); +} + export { createMultisig, + createNonce, createSignature, createTransaction, findTransactionByID, + getBelongedMultisigs, + getCreatedMultisigs, getMultisig, + getMultisigId, + getNonce, + getTransactions, + updateNonce, updateTxHash, }; diff --git a/lib/multisigHelpers.ts b/lib/multisigHelpers.ts index 58afc8e..8314161 100644 --- a/lib/multisigHelpers.ts +++ b/lib/multisigHelpers.ts @@ -27,6 +27,7 @@ export const createMultisigFromCompressedSecp256k1Pubkeys = async ( threshold: number, addressPrefix: string, chainId: string, + creator: string, ): Promise => { const pubkeys = compressedPubkeys.map((compressedPubkey) => { return { @@ -41,6 +42,7 @@ export const createMultisigFromCompressedSecp256k1Pubkeys = async ( const multisig = { address: multisigAddress, pubkeyJSON: JSON.stringify(multisigPubkey), + creator, chainId, }; diff --git a/lib/txMsgHelpers.ts b/lib/txMsgHelpers.ts index bb23f8f..03c0a7d 100644 --- a/lib/txMsgHelpers.ts +++ b/lib/txMsgHelpers.ts @@ -1,5 +1,5 @@ import { EncodeObject } from "@cosmjs/proto-signing"; -import { DbTransaction } from "../types"; +import { DbTransactionJsonObj } from "../types"; import { MsgCodecs, MsgTypeUrl, MsgTypeUrls } from "../types/txMsg"; const gasOfMsg = (msgType: MsgTypeUrl): number => { @@ -74,9 +74,9 @@ const importMsgFromJson = (msg: EncodeObject): EncodeObject => { throw new Error("Unknown msg type"); }; -export const dbTxFromJson = (txJson: string): DbTransaction | null => { +export const dbTxFromJson = (txJson: string): DbTransactionJsonObj | null => { try { - const dbTx: DbTransaction = JSON.parse(txJson); + const dbTx: DbTransactionJsonObj = JSON.parse(txJson); dbTx.msgs = dbTx.msgs.map(importMsgFromJson); return dbTx; @@ -90,3 +90,31 @@ export const dbTxFromJson = (txJson: string): DbTransaction | null => { return null; } }; + +interface MsgTypeCount { + readonly msgType: string; + readonly count: number; +} + +export const msgTypeCountsFromJson = (txJson: string): readonly MsgTypeCount[] => { + const tx = dbTxFromJson(txJson); + if (!tx) { + return []; + } + + const msgTypeCounts: { msgType: string; count: number }[] = []; + + const msgTypes = tx.msgs.map(({ typeUrl }) => typeUrl.split(".Msg")[1]); + + for (const msgType of msgTypes) { + const foundIndex = msgTypeCounts.findIndex((msgTypeCount) => msgTypeCount.msgType === msgType); + + if (foundIndex !== -1) { + msgTypeCounts[foundIndex].count++; + } else { + msgTypeCounts.push({ msgType, count: 1 }); + } + } + + return msgTypeCounts; +}; diff --git a/package-lock.json b/package-lock.json index 701c087..bc2c5c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "@cosmjs/tendermint-rpc": "^0.32.2", "@cosmjs/utils": "^0.32.2", "@hookform/resolvers": "^3.3.1", + "@keplr-wallet/cosmos": "^0.12.101", "@keplr-wallet/types": "^0.12.76", "@ledgerhq/hw-transport-webusb": "^6.27.19", "@radix-ui/react-accordion": "^1.1.2", @@ -1193,6 +1194,119 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@ethersproject/address": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/address/-/address-5.7.0.tgz", + "integrity": "sha512-9wYhYt7aghVGo758POM5nqcOMaE168Q6aRLJZwUmiqSrAungkG74gSSeKEIR7ukixesdRZGPgVqme6vmxs1fkA==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/bignumber": "^5.7.0", + "@ethersproject/bytes": "^5.7.0", + "@ethersproject/keccak256": "^5.7.0", + "@ethersproject/logger": "^5.7.0", + "@ethersproject/rlp": "^5.7.0" + } + }, + "node_modules/@ethersproject/bignumber": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/bignumber/-/bignumber-5.7.0.tgz", + "integrity": "sha512-n1CAdIHRWjSucQO3MC1zPSVgV/6dy/fjL9pMrPP9peL+QxEg9wOsVqwD4+818B6LUEtaXzVHQiuivzRoxPxUGw==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/bytes": "^5.7.0", + "@ethersproject/logger": "^5.7.0", + "bn.js": "^5.2.1" + } + }, + "node_modules/@ethersproject/bytes": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/bytes/-/bytes-5.7.0.tgz", + "integrity": "sha512-nsbxwgFXWh9NyYWo+U8atvmMsSdKJprTcICAkvbBffT75qDocbuggBU0SJiVK2MuTrp0q+xvLkTnGMPK1+uA9A==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/logger": "^5.7.0" + } + }, + "node_modules/@ethersproject/keccak256": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/keccak256/-/keccak256-5.7.0.tgz", + "integrity": "sha512-2UcPboeL/iW+pSg6vZ6ydF8tCnv3Iu/8tUmLLzWWGzxWKFFqOBQFLo6uLUv6BDrLgCDfN28RJ/wtByx+jZ4KBg==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/bytes": "^5.7.0", + "js-sha3": "0.8.0" + } + }, + "node_modules/@ethersproject/logger": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/logger/-/logger-5.7.0.tgz", + "integrity": "sha512-0odtFdXu/XHtjQXJYA3u9G0G8btm0ND5Cu8M7i5vhEcE8/HmF4Lbdqanwyv4uQTr2tx6b7fQRmgLrsnpQlmnig==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ] + }, + "node_modules/@ethersproject/rlp": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/@ethersproject/rlp/-/rlp-5.7.0.tgz", + "integrity": "sha512-rBxzX2vK8mVF7b0Tol44t5Tb8gomOHkj5guL+HhzQ1yBh/ydjGnpw6at+X6Iw0Kp3OzzzkcKp8N9r0W4kYSs9w==", + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "dependencies": { + "@ethersproject/bytes": "^5.7.0", + "@ethersproject/logger": "^5.7.0" + } + }, "node_modules/@floating-ui/core": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.4.1.tgz", @@ -1704,14 +1818,82 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@keplr-wallet/common": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/common/-/common-0.12.101.tgz", + "integrity": "sha512-aRiusWbKmQ/Ct00HsjxH+BbKxaFBoE/SsJ4FlRDx0AyGo4P3a+eYPiOxqYZneCALfnNhQdCG9/EJZ4J4kxkJmg==", + "dependencies": { + "@keplr-wallet/crypto": "0.12.101", + "@keplr-wallet/types": "0.12.101", + "buffer": "^6.0.3", + "delay": "^4.4.0" + } + }, + "node_modules/@keplr-wallet/cosmos": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/cosmos/-/cosmos-0.12.101.tgz", + "integrity": "sha512-XrNevDPY9rEpDRq/0L2U7WdUvrhKhmb9f34peV8Jw78P/fTzUz5oGaizqotmrUABDQqe1tM/71OWl6AtwFguJQ==", + "dependencies": { + "@ethersproject/address": "^5.6.0", + "@keplr-wallet/common": "0.12.101", + "@keplr-wallet/crypto": "0.12.101", + "@keplr-wallet/proto-types": "0.12.101", + "@keplr-wallet/simple-fetch": "0.12.101", + "@keplr-wallet/types": "0.12.101", + "@keplr-wallet/unit": "0.12.101", + "bech32": "^1.1.4", + "buffer": "^6.0.3", + "long": "^4.0.0", + "protobufjs": "^6.11.2" + } + }, + "node_modules/@keplr-wallet/crypto": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/crypto/-/crypto-0.12.101.tgz", + "integrity": "sha512-rtGqIY80C1El5AxJgOckxnyGRzXEpOozfB2h2hCV0QjK2wScSwk9e1mQgrWQRgRrCtdKLovbPzDw9YCUFjzH+Q==", + "dependencies": { + "@ethersproject/keccak256": "^5.5.0", + "bip32": "^2.0.6", + "bip39": "^3.0.3", + "bs58check": "^2.1.2", + "buffer": "^6.0.3", + "crypto-js": "^4.0.0", + "elliptic": "^6.5.3", + "sha.js": "^2.4.11" + } + }, + "node_modules/@keplr-wallet/proto-types": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/proto-types/-/proto-types-0.12.101.tgz", + "integrity": "sha512-+nsJIDCjBGrMPh/9lYoqrEBkkJCJGVU1I9HNuxOVzkLz8ozKgvvvTjHFmH5RHM9yfb0lRB5VAI8GUazpiJGagg==", + "dependencies": { + "long": "^4.0.0", + "protobufjs": "^6.11.2" + } + }, + "node_modules/@keplr-wallet/simple-fetch": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/simple-fetch/-/simple-fetch-0.12.101.tgz", + "integrity": "sha512-7Rc8o6WyH2C1WPeQaj292kA2/GUjDQbT7fOw6cLKj/Izv3+5VN4CXiS2zFPiZQ1I5jrh843q7odGAiVxiV38oA==" + }, "node_modules/@keplr-wallet/types": { - "version": "0.12.76", - "resolved": "https://registry.npmjs.org/@keplr-wallet/types/-/types-0.12.76.tgz", - "integrity": "sha512-N2KRh1xCJ3gqZUWEi803RwpeCVrFCxFTZyUgFgIUt/fg0qPyd/F6okjcpvu6dj9BNDppuJntqYUpOUdWA7mY9Q==", + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/types/-/types-0.12.101.tgz", + "integrity": "sha512-gQbmEursW0FP/1RTebWMo2mYLulgoDz3ynpGu3T46wg3qHuPSgooKFNvT5xsLiVHPJlhHo+IKC/9pjKimllM/Q==", "dependencies": { "long": "^4.0.0" } }, + "node_modules/@keplr-wallet/unit": { + "version": "0.12.101", + "resolved": "https://registry.npmjs.org/@keplr-wallet/unit/-/unit-0.12.101.tgz", + "integrity": "sha512-2T6HkJP6XbBCYktaN+hYGroDl9K3lUX+3A4HVwSlpCAIT6Jnj5tMo4uSHub6Yk3f5bstp7ZR0Wj6wSPkx8yzvw==", + "dependencies": { + "@keplr-wallet/types": "0.12.101", + "big-integer": "^1.6.48", + "utility-types": "^3.10.0" + } + }, "node_modules/@ledgerhq/devices": { "version": "8.0.7", "resolved": "https://registry.npmjs.org/@ledgerhq/devices/-/devices-8.0.7.tgz", @@ -4882,6 +5064,14 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "node_modules/base-x": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.9.tgz", + "integrity": "sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -4906,6 +5096,14 @@ "resolved": "https://registry.npmjs.org/bech32/-/bech32-1.1.4.tgz", "integrity": "sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ==" }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "engines": { + "node": ">=0.6" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -4914,6 +5112,44 @@ "node": ">=8" } }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bip32": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/bip32/-/bip32-2.0.6.tgz", + "integrity": "sha512-HpV5OMLLGTjSVblmrtYRfFFKuQB+GArM0+XP8HGWfJ5vxYBqo+DesvJwOdC2WJ3bCkZShGf0QIfoIpeomVzVdA==", + "dependencies": { + "@types/node": "10.12.18", + "bs58check": "^2.1.1", + "create-hash": "^1.2.0", + "create-hmac": "^1.1.7", + "tiny-secp256k1": "^1.1.3", + "typeforce": "^1.11.5", + "wif": "^2.0.6" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/bip32/node_modules/@types/node": { + "version": "10.12.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.18.tgz", + "integrity": "sha512-fh+pAqt4xRzPfqA6eh3Z2y6fyZavRIumvjhaCL753+TVkGKGhpPeyrJG2JftD0T9q4GF00KjefsQ+PQNDdWQaQ==" + }, + "node_modules/bip39": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bip39/-/bip39-3.1.0.tgz", + "integrity": "sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A==", + "dependencies": { + "@noble/hashes": "^1.2.0" + } + }, "node_modules/bn.js": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", @@ -4975,6 +5211,24 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/bs58": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz", + "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==", + "dependencies": { + "base-x": "^3.0.2" + } + }, + "node_modules/bs58check": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-2.1.2.tgz", + "integrity": "sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==", + "dependencies": { + "bs58": "^4.0.0", + "create-hash": "^1.1.0", + "safe-buffer": "^5.1.2" + } + }, "node_modules/bser": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", @@ -4983,6 +5237,29 @@ "node-int64": "^0.4.0" } }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -5128,6 +5405,15 @@ "node": ">=8" } }, + "node_modules/cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/cjs-module-lexer": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", @@ -5543,6 +5829,31 @@ "resolved": "https://registry.npmjs.org/cosmjs-types/-/cosmjs-types-0.9.0.tgz", "integrity": "sha512-MN/yUe6mkJwHnCFfsNPeCfXVhyxHYW6c/xDUzrSbBycYzw++XvWDMJArXp2pLdgD6FQ8DW79vkPjeNKVrXaHeQ==" }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dependencies": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, "node_modules/crelt": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", @@ -5561,6 +5872,11 @@ "node": ">= 8" } }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==" + }, "node_modules/css-tree": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.3.1.tgz", @@ -5858,6 +6174,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delay": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/delay/-/delay-4.4.1.tgz", + "integrity": "sha512-aL3AhqtfhOlT/3ai6sWXeqwnw63ATNpnUiN4HL7x9q+My5QtHlO3OIkasmug9LKzpheLdmUKGRKnYXYAS7FQkQ==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -6749,6 +7076,11 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==" + }, "node_modules/fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", @@ -7258,6 +7590,25 @@ "node": ">=0.10.0" } }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/ignore": { "version": "5.2.4", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", @@ -8396,6 +8747,11 @@ "node": ">= 0.6.0" } }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -8752,6 +9108,16 @@ "tmpl": "1.0.5" } }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, "node_modules/mdn-data": { "version": "2.0.30", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.30.tgz", @@ -8866,6 +9232,11 @@ "thenify-all": "^1.0.0" } }, + "node_modules/nan": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.19.0.tgz", + "integrity": "sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw==" + }, "node_modules/nanoid": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", @@ -10360,6 +10731,18 @@ "node": ">=10" } }, + "node_modules/sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -10871,6 +11254,27 @@ "node": ">=0.8" } }, + "node_modules/tiny-secp256k1": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/tiny-secp256k1/-/tiny-secp256k1-1.1.6.tgz", + "integrity": "sha512-FmqJZGduTyvsr2cF3375fqGHUovSwDi/QytexX1Se4BPuPZpTE5Ftp5fg+EFSuEf3lhZqgCRjEG3ydUQ/aNiwA==", + "hasInstallScript": true, + "dependencies": { + "bindings": "^1.3.0", + "bn.js": "^4.11.8", + "create-hmac": "^1.1.7", + "elliptic": "^6.4.0", + "nan": "^2.13.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tiny-secp256k1/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==" + }, "node_modules/tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", @@ -11048,6 +11452,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typeforce": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/typeforce/-/typeforce-1.18.0.tgz", + "integrity": "sha512-7uc1O8h1M1g0rArakJdf0uLRSSgFcYexrVoKo+bzJd32gd4gDy2L/Z+8/FjPnU9ydY3pEnVPtr9FyscYY60K1g==" + }, "node_modules/typescript": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", @@ -11187,6 +11596,14 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, + "node_modules/utility-types": { + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz", + "integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==", + "engines": { + "node": ">= 4" + } + }, "node_modules/v8-to-istanbul": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", @@ -11447,6 +11864,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/wif": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/wif/-/wif-2.0.6.tgz", + "integrity": "sha512-HIanZn1zmduSF+BQhkE+YXIbEiH0xPr1012QbFEGB0xsKqJii0/SqJjyn8dFv6y36kOznMgMB+LGcbZTJ1xACQ==", + "dependencies": { + "bs58check": "<3.0.0" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", diff --git a/package.json b/package.json index 486c3e6..3db288d 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@cosmjs/tendermint-rpc": "^0.32.2", "@cosmjs/utils": "^0.32.2", "@hookform/resolvers": "^3.3.1", + "@keplr-wallet/cosmos": "^0.12.101", "@keplr-wallet/types": "^0.12.76", "@ledgerhq/hw-transport-webusb": "^6.27.19", "@radix-ui/react-accordion": "^1.1.2", diff --git a/pages/[chainName]/index.tsx b/pages/[chainName]/index.tsx index 60269e3..21ed8e3 100644 --- a/pages/[chainName]/index.tsx +++ b/pages/[chainName]/index.tsx @@ -1,3 +1,4 @@ +import ListUserMultisigs from "@/components/dataViews/ListUserMultisigs"; import FindMultisigForm from "@/components/forms/FindMultisigForm"; import Head from "@/components/head"; import { useChains } from "@/context/ChainsContext"; @@ -9,6 +10,7 @@ const FindMultisigPage = () => {
+
); }; diff --git a/pages/api/chain/[chainId]/multisig/index.ts b/pages/api/chain/[chainId]/multisig/index.ts index f56654c..a18f63f 100644 --- a/pages/api/chain/[chainId]/multisig/index.ts +++ b/pages/api/chain/[chainId]/multisig/index.ts @@ -1,5 +1,5 @@ +import { createMultisig } from "@/lib/graphqlHelpers"; import type { NextApiRequest, NextApiResponse } from "next"; -import { createMultisig } from "../../../../../lib/graphqlHelpers"; export default async function multisigApi(req: NextApiRequest, res: NextApiResponse) { switch (req.method) { diff --git a/pages/api/chain/[chainId]/multisig/list/index.ts b/pages/api/chain/[chainId]/multisig/list/index.ts new file mode 100644 index 0000000..11376c6 --- /dev/null +++ b/pages/api/chain/[chainId]/multisig/list/index.ts @@ -0,0 +1,78 @@ +import { ChainInfo } from "@/context/ChainsContext/types"; +import { + getBelongedMultisigs, + getCreatedMultisigs, + getNonce, + updateNonce, +} from "@/lib/graphqlHelpers"; +import { decodeSignature, pubkeyToAddress } from "@cosmjs/amino"; +import { toBase64 } from "@cosmjs/encoding"; +import { StargateClient } from "@cosmjs/stargate"; +import { verifyADR36Amino } from "@keplr-wallet/cosmos"; +import { StdSignature } from "@keplr-wallet/types"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function multisigsApi(req: NextApiRequest, res: NextApiResponse) { + switch (req.method) { + case "POST": + try { + const { signature, chain }: { signature: StdSignature; chain: ChainInfo } = req.body; + + const chainId = typeof req.query.chainId === "string" ? req.query.chainId : ""; + if (chainId !== chain.chainId) { + throw new Error(`Tried connecting to ${chainId} with data from ${chain.chainId}`); + } + + const address = pubkeyToAddress(signature.pub_key, chain.addressPrefix); + + const client = await StargateClient.connect(chain.nodeAddress); + const accountOnChain = await client.getAccount(address); + + if (!accountOnChain) { + throw new Error("Account not found on chain for: " + address); + } + + const dbNonce = await getNonce(chainId, address); + + if (!dbNonce) { + throw new Error(`Nonce not found on ${chainId} for ${address}`); + } + + const { pubkey: decodedPubKey, signature: decodedSignature } = decodeSignature(signature); + const data = JSON.stringify({ + title: `Keplr Login to ${chain.chainDisplayName}`, + description: "Sign this no fee transaction to login with your Keplr wallet", + nonce: dbNonce.nonce, + }); + + await updateNonce(chainId, address, dbNonce.nonce + 1); + + const verified = verifyADR36Amino( + chain.addressPrefix, + address, + data, + decodedPubKey, + decodedSignature, + ); + + if (verified) { + console.log("Function `getMultisigs` invoked", chainId, address); + const created = await getCreatedMultisigs(chainId, address); + const belonged = await getBelongedMultisigs(chainId, toBase64(decodedPubKey)); + console.log("success", { created, belonged }); + res.status(200).send({ created, belonged }); + return; + } + + throw new Error("Signature failed for querying multisigs"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (err: any) { + console.log(err); + res.status(400).send(err.message); + return; + } + } + // no route matched + res.status(405).end(); + return; +} diff --git a/pages/api/chain/[chainId]/nonce/[address]/index.tsx b/pages/api/chain/[chainId]/nonce/[address]/index.tsx new file mode 100644 index 0000000..56696e2 --- /dev/null +++ b/pages/api/chain/[chainId]/nonce/[address]/index.tsx @@ -0,0 +1,37 @@ +import { createNonce, getNonce } from "@/lib/graphqlHelpers"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function nonceApi(req: NextApiRequest, res: NextApiResponse) { + switch (req.method) { + case "GET": + try { + const chainId = req.query.chainId?.toString() || ""; + const address = req.query.address?.toString() || ""; + + console.log("Function `getNonce` invoked", chainId, address); + let nonce = await getNonce(chainId, address); + if (nonce) { + console.log("success", nonce); + res.status(200).send(nonce); + return; + } + + nonce = await createNonce(chainId, address); + if (!nonce) { + throw new Error(`Nonce could not be created on ${chainId} for ${address}`); + } + + console.log("success", nonce); + res.status(200).send(nonce); + return; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (err: any) { + console.log(err); + res.status(400).send(err.message); + return; + } + } + // no route matched + res.status(405).end(); + return; +} diff --git a/pages/api/transaction/index.ts b/pages/api/transaction/index.ts index e0294cf..4501082 100644 --- a/pages/api/transaction/index.ts +++ b/pages/api/transaction/index.ts @@ -1,5 +1,5 @@ import type { NextApiRequest, NextApiResponse } from "next"; -import { createTransaction } from "../../../lib/graphqlHelpers"; +import { createTransaction, getMultisigId } from "../../../lib/graphqlHelpers"; export default async function transactionApi(req: NextApiRequest, res: NextApiResponse) { switch (req.method) { @@ -7,7 +7,13 @@ export default async function transactionApi(req: NextApiRequest, res: NextApiRe try { const data = req.body; console.log("Function `createTransaction` invoked", data); - const createTransactionResult = await createTransaction(data.dataJSON); + + const multisigId = await getMultisigId(data.creator, data.chainId); + if (!multisigId) { + throw new Error("Multisig not found"); + } + + const createTransactionResult = await createTransaction(data.dataJSON, multisigId); console.log("createTransactionResult:", createTransactionResult); res .status(200) diff --git a/pages/api/transaction/list/index.ts b/pages/api/transaction/list/index.ts new file mode 100644 index 0000000..1cd58b6 --- /dev/null +++ b/pages/api/transaction/list/index.ts @@ -0,0 +1,91 @@ +import { ChainInfo } from "@/context/ChainsContext/types"; +import { + getMultisig, + getMultisigId, + getNonce, + getTransactions, + updateNonce, +} from "@/lib/graphqlHelpers"; +import { decodeSignature, pubkeyToAddress } from "@cosmjs/amino"; +import { toBase64 } from "@cosmjs/encoding"; +import { StargateClient } from "@cosmjs/stargate"; +import { verifyADR36Amino } from "@keplr-wallet/cosmos"; +import { StdSignature } from "@keplr-wallet/types"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function transactionsApi(req: NextApiRequest, res: NextApiResponse) { + switch (req.method) { + case "POST": + try { + const { + signature, + chain, + multisigAddress, + }: { signature: StdSignature; chain: ChainInfo; multisigAddress: string } = req.body; + + const multisig = await getMultisig(multisigAddress, chain.chainId); + if (!multisig) { + throw new Error("Multisig not found"); + } + + const { pubkey: decodedPubKey, signature: decodedSignature } = decodeSignature(signature); + + if (!multisig.pubkeyJSON.includes(toBase64(decodedPubKey))) { + throw new Error("You don't belong to the multisig"); + } + + const address = pubkeyToAddress(signature.pub_key, chain.addressPrefix); + + const client = await StargateClient.connect(chain.nodeAddress); + const accountOnChain = await client.getAccount(address); + + if (!accountOnChain) { + throw new Error("Account not found on chain for: " + address); + } + + const dbNonce = await getNonce(chain.chainId, address); + + if (!dbNonce) { + throw new Error(`Nonce not found on ${chain.chainId} for ${address}`); + } + + const data = JSON.stringify({ + title: `Keplr Login to ${chain.chainDisplayName}`, + description: "Sign this no fee transaction to login with your Keplr wallet", + nonce: dbNonce.nonce, + }); + + await updateNonce(chain.chainId, address, dbNonce.nonce + 1); + + const verified = verifyADR36Amino( + chain.addressPrefix, + address, + data, + decodedPubKey, + decodedSignature, + ); + + if (verified) { + const multisigId = await getMultisigId(multisigAddress, chain.chainId); + if (!multisigId) { + throw new Error("Multisig not found"); + } + console.log("Function `getTransactions` invoked", chain.chainId, address); + const transactions = (await getTransactions(multisigId)).toReversed(); + console.log("success", transactions); + res.status(200).send(transactions); + return; + } + + throw new Error("Signature failed for querying multisigs"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (err: any) { + console.log(err); + res.status(400).send(err.message); + return; + } + } + // no route matched + res.status(405).end(); + return; +} diff --git a/types/index.ts b/types/index.ts index e7aaa2b..4c28749 100644 --- a/types/index.ts +++ b/types/index.ts @@ -1,18 +1,10 @@ import { StdFee } from "@cosmjs/amino"; import { EncodeObject } from "@cosmjs/proto-signing"; +import { Keplr } from "@keplr-wallet/types"; declare global { interface Window { - keplr: { - defaultOptions: { - sign: { preferNoSetFee: boolean; preferNoSetMemo: boolean; disableBalanceCheck: boolean }; - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - enable: (chainId: string) => any; - getKey: (chainId: string) => Promise; - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - getOfflineSignerOnlyAmino: any; + keplr: Keplr; } } @@ -23,6 +15,13 @@ export interface DbSignature { } export interface DbTransaction { + id: string; + txHash: string; + dataJSON: string; + signatures: DbSignature[]; +} + +export interface DbTransactionJsonObj { accountNumber: number; sequence: number; chainId: string; @@ -31,12 +30,19 @@ export interface DbTransaction { memo: string; } -export interface DbAccount { - address: string; - pubkeyJSON: string; +export interface DbMultisig { chainId: string; + address: string; + creator: string; + pubkeyJSON: string; } +export type DbNonce = { + readonly chainId: string; + readonly address: string; + readonly nonce: number; +}; + export interface WalletAccount { address?: Uint8Array; pubKey: Uint8Array;