Skip to content

Commit

Permalink
refactor: move connect wallet to file
Browse files Browse the repository at this point in the history
  • Loading branch information
icfor committed Jan 15, 2024
1 parent 598bd6f commit 57268e4
Show file tree
Hide file tree
Showing 13 changed files with 291 additions and 160 deletions.
7 changes: 6 additions & 1 deletion public/locales/en/staking.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@
"rewards": "Earn Rewards",
"rewards desc": "You earn staking rewards on your tokens",
"rewardsModal": {
"button": "Claim Rewards"
"button": "Claim Rewards",
"gasFee": "Gas fee",
"success": {
"sub": "Congratulations!",
"title": "Your rewards have been claimed!"
}
},
"risks para 1": "There may be some risks when your validator is having poor performance or making critical mistakes, your funds will be slashed accordingly.",
"risks q": "What are the risks of staking?",
Expand Down
7 changes: 6 additions & 1 deletion public/locales/zh-CN/staking.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@
"rewards": "赚取收益",
"rewards desc": "可以通过质押通证赚取收益",
"rewardsModal": {
"button": "Claim Rewards"
"button": "Claim Rewards",
"gasFee": "Gas Fee",
"success": {
"sub": "Congratulations!",
"title": "Your rewards have been claimed!"
}
},
"risks para 1": "当您的验证人表现不佳或犯严重错误时,可能会存在一些风险,您的资金将被相应削减。",
"risks q": "质押有哪些风险?",
Expand Down
7 changes: 6 additions & 1 deletion public/locales/zh-HK/staking.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@
"rewards": "賺取收益",
"rewards desc": "可以透過質押通證賺取收益",
"rewardsModal": {
"button": "Claim Rewards"
"button": "Claim Rewards",
"gasFee": "Gas Fee",
"success": {
"sub": "Congratulations!",
"title": "Your rewards have been claimed!"
}
},
"risks para 1": "當您的驗證人表現不佳或犯嚴重錯誤時,可能會存在一些風險,您的資金將被相應削減。",
"risks q": "質押有哪些風險?",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
@import "src/styles/sass.scss";

.feeRow {
display: flex;
flex-direction: row;
gap: 8px;
justify-content: space-between;
margin: 16px 0;
width: 504px;

> div {
color: #25282d;
font-size: 16px;
font-style: normal;
font-weight: 600;
letter-spacing: 0.032px;
line-height: 20px; /* 125% */
text-shadow: $box-shadow-variant-3;
}
}

.wrapper {
display: flex;
flex: 1;
flex-direction: column;
gap: 24px;

@include up-laptop {
min-width: 500px;
}
}
Original file line number Diff line number Diff line change
@@ -1,63 +1,96 @@
/* eslint-disable no-console */
import type { Coin } from "@cosmjs/stargate";
import useTranslation from "next-translate/useTranslation";
import { useContext } from "react";
import { useContext, useEffect, useState } from "react";

import HighlightButton from "@src/components/highlight-button";
import { toastSuccess } from "@src/components/notification";
import {
StakingContext,
setSelectedAccount,
} from "@src/screens/staking/lib/context";
import { claimRewards } from "@src/screens/staking/lib/context/operations";
import {
claimRewards,
getClaimRewardsFee,
} from "@src/screens/staking/lib/context/operations";

import { formatDenom } from "../../lib/context/formatters";
import { displayGenericError } from "../../lib/error";
import * as styles from "./claim_rewards_modal.module.scss";
import ModalBase from "./modal_base";
import NetworksSelect from "./networks_select";

const ClaimRewardsModal = () => {
const { setState: setStakingState, state: stakingState } =
useContext(StakingContext);

const [gasFee, setGasFee] = useState<Coin | null>(null);
const [isLoading, setIsLoading] = useState(false);

const { t } = useTranslation("staking");

const { selectedAccount, selectedAction } = stakingState;

const isOpen = !!selectedAccount && selectedAction === "claim_rewards";
const { address, chainId } = selectedAccount || {};

useEffect(() => {
if (isOpen && chainId && address) {
setGasFee(null);

getClaimRewardsFee({ address, chainId }).then((fee) => {
setGasFee(fee);
});
}
}, [isOpen, chainId, address]);

return (
<ModalBase
onClose={() => setSelectedAccount(setStakingState, undefined)}
open={isOpen}
title={t("claimRewards.title")}
>
<NetworksSelect variant="accounts" />
<div>
<div>Gas Fee</div>
<div>0.002 ATOM</div>
</div>
<HighlightButton
onClick={() => {
if (!selectedAccount) return;
<div className={styles.wrapper}>
<NetworksSelect variant="accounts" />
{gasFee && (
<div className={styles.feeRow}>
<div>{t("rewardsModal.gasFee")}</div>
<div>{formatDenom(gasFee.denom, gasFee.amount)}</div>
</div>
)}
<HighlightButton
disabled={!address || !chainId || isLoading}
onClick={() => {
if (!address || !chainId || isLoading) return;

const { address, chainId } = selectedAccount;
setIsLoading(true);

claimRewards({
address,
chainId,
})
.then(() => {
toastSuccess({
title: "Rewards claimed",
});
claimRewards({
address,
chainId,
})
.catch((error) => {
console.error(error);
});
}}
pinkShadow
size="big"
>
{t("rewardsModal.button")}
</HighlightButton>
.then((claimed) => {
if (claimed) {
toastSuccess({
subtitle: `${t("rewardsModal.success.sub")} 🎉`,
title: t("rewardsModal.success.title"),
});
}
})
.catch((error) => {
console.log("debug: claim_rewards_modal.tsx: error", error);

displayGenericError(t);
})
.finally(() => {
setIsLoading(false);
});
}}
pinkShadow
size="big"
>
{t("rewardsModal.button")}
</HighlightButton>
</div>
</ModalBase>
);
};
Expand Down
104 changes: 15 additions & 89 deletions src/screens/staking/components/staking_section/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
setupStakingExtension,
} from "@cosmjs/stargate";
import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import type { AccountData, Window as KeplrWindow } from "@keplr-wallet/types";
import type { Window as KeplrWindow } from "@keplr-wallet/types";
import { Dec } from "@keplr-wallet/unit";
import { Box, Button } from "@mui/material";
import { MsgDelegate } from "cosmjs-types/cosmos/staking/v1beta1/tx";
Expand All @@ -20,19 +20,12 @@ import { useContext, useEffect, useState } from "react";
import { tooltipId } from "@src/components/tooltip";
import {
StakingContext,
addToConnectedWallets,
fetchNetworksInfo,
getConnectedWallets,
setUserWallet,
} from "@src/screens/staking/lib/context";
import type { Account, Wallet } from "@src/screens/staking/lib/context/types";
import {
ChainId,
WalletId,
keplrNetworks,
networksWithStaking,
} from "@src/screens/staking/lib/context/types";
import { ChainId, WalletId } from "@src/screens/staking/lib/context/types";

import { tryToConnectWallets } from "../../lib/context/operations";
import ClaimRewardsModal from "./claim_rewards_modal";
import * as styles from "./index.module.scss";
import StakingModal from "./staking_modal";
Expand Down Expand Up @@ -104,89 +97,18 @@ const StakingSection = () => {
sequence: "",
});

const tryToConnectWallets = async (walletsIds: WalletId[]) => {
if (walletsIds.includes(WalletId.Keplr)) {
if (window.keplr) {
const chainsToConnect = Array.from(keplrNetworks);

await window.keplr?.enable(chainsToConnect);

try {
const handleError = (err: unknown) => {
console.log("debug: index.tsx: err", err);

return [] as Account[];
};

const parseAccounts =
(chainId: ChainId) =>
(accounts: readonly AccountData[]): Promise<Account[]> =>
Promise.all(
accounts.map((account) =>
Promise.all([
stakingClient.getAddressInfo(chainId, account.address),
stakingClient.getRewardsInfo(chainId, account.address),
]).then(([info, rewards]) => ({
address: account.address,
chainId,
info,
rewards,
wallet: WalletId.Keplr,
})),
),
);

const keplrAccounts = await Promise.all(
Array.from(keplrNetworks).map(async (network) => {
if (networksWithStaking.has(network)) {
const accounts = await window
.keplr!.getOfflineSigner(network)
.getAccounts()
.then(parseAccounts(network))
.catch(handleError);

return {
accounts,
chainId: network,
};
}
}),
);

addToConnectedWallets(WalletId.Keplr);

setUserWallet(
stakingState,
setStakingState,
WalletId.Keplr,
keplrAccounts.reduce((acc, networkObj) => {
if (networkObj) {
acc[networkObj.chainId] = {
accounts: networkObj.accounts,
chainId: networkObj.chainId,
};
}

return acc;
}, {} as Wallet),
);
} catch (error) {
console.log(error);
}
}
}
};

useEffect(() => {
const connectedWallets = getConnectedWallets();

fetchNetworksInfo(setStakingState);

tryToConnectWallets(connectedWallets).then(() => {
setStakingState({
hasInit: true,
});
});
tryToConnectWallets(stakingState, setStakingState, connectedWallets).then(
() => {
setStakingState({
hasInit: true,
});
},
);

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Expand Down Expand Up @@ -368,7 +290,11 @@ const StakingSection = () => {
<Button
data-tooltip-content="Test tooltip"
data-tooltip-id={tooltipId}
onClick={() => tryToConnectWallets([WalletId.Keplr])}
onClick={() =>
tryToConnectWallets(stakingState, setStakingState, [
WalletId.Keplr,
])
}
>
Get address
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,13 @@
.input {
width: 100%;
}

.amount {
color: #007fff;
font-size: 16px;
font-style: normal;
font-weight: 600;
letter-spacing: 0.08px;
line-height: normal;
text-shadow: $box-shadow-variant-3;
}
20 changes: 13 additions & 7 deletions src/screens/staking/components/staking_section/staking_modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,20 @@ const StakingModal = () => {
<div>{(networkInfo.apy * 100).toFixed(0)}%</div>
</div>
)}
{availableTokens && (
<div>
<Label>{t("stakingModal.available")}</Label>:{" "}
{formatDenom(availableTokens[0], availableTokens[1])}
</div>
)}
<div className={styles.group}>
<Label>{t("stakingModal.tokenAmount")}</Label>
<div className={styles.row}>
<Label>{t("stakingModal.tokenAmount")}</Label>
<div>
{availableTokens && (
<>
<Label>{t("stakingModal.available")}</Label>:{" "}
<span className={styles.amount}>
{formatDenom(availableTokens[0], availableTokens[1])}
</span>
</>
)}
</div>
</div>
<div className={styles.row}>
<FormInput
className={styles.input}
Expand Down
Loading

0 comments on commit 57268e4

Please sign in to comment.