Skip to content

Commit

Permalink
Merge branch 'develop' into preview
Browse files Browse the repository at this point in the history
  • Loading branch information
leduyhien152 committed Apr 19, 2024
2 parents fce8b64 + 1650658 commit ee48dd2
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 97 deletions.
6 changes: 3 additions & 3 deletions components/overview/FlexibleStakingCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const FlexibleStakingCard = (props: Props) => {
stakingToken,
rewardToken,
autoStaking,
finishTime,
rewardClaimableDate,
poolContract,
setValues,
updateValues,
Expand Down Expand Up @@ -331,8 +331,8 @@ export const FlexibleStakingCard = (props: Props) => {
hidden,
}}
footerExtra={
!stakedAmount.isZero() && !unclaimedRewards.isZero() && finishTime ? (
<Countdown finishTime={finishTime}>
!unclaimedRewards.isZero() && rewardClaimableDate ? (
<Countdown finishTime={rewardClaimableDate}>
<Button variant="outline" disabled={isClaiming} onClick={onClaim}>
{isClaiming && <Spinner className="w-4 h-4" />}
{isClaiming ? "Claiming" : "Claim"}
Expand Down
7 changes: 3 additions & 4 deletions components/stake/flexible/flexible-stake-response.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ interface Props {
export const FlexibleStakeResponse = (props: Props) => {
const { onClose } = props;
const {
startTime,
finishTime,
rewardClaimableDate,
autoStaking,
latestStaking,
stakingToken,
Expand Down Expand Up @@ -69,7 +68,7 @@ export const FlexibleStakeResponse = (props: Props) => {
<Typography level="h9">Value date</Typography>
</div>
<Typography level="p5">
{formatUnixTimestampToDateTime(startTime)}
{formatUnixTimestampToDateTime(stakeDate)}
</Typography>
</div>
<div className="flex items-center justify-between relative">
Expand All @@ -81,7 +80,7 @@ export const FlexibleStakeResponse = (props: Props) => {
<Typography level="h9">Interest distribution date</Typography>
</div>
<Typography level="p5">
{formatUnixTimestampToDateTime(finishTime)}
{formatUnixTimestampToDateTime(rewardClaimableDate)}
</Typography>
</div>
</div>
Expand Down
99 changes: 28 additions & 71 deletions services/contracts/Pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const getPoolKey = (
return `${type}-${stakingTokenSymbol}-${rewardTokenSymbol}`;
};

export const YEAR_IN_SECONDS = 31556926;

export class StakingPool {
private static instances: Map<string, StakingPool> = new Map();
private provider: ChainProvider;
Expand Down Expand Up @@ -79,40 +81,19 @@ export class StakingPool {
return this.address;
}

async getPeriodFinishDate(): Promise<number> {
try {
const response: BigNumber[] = await this.provider.read({
abi: this.abi,
method: "periodFinish",
args: [],
to: this.address,
});

if (response?.length && BigNumber.isBigNumber(response[0])) {
console.log("getPeriodFinishDate", response[0].toNumber());
return response[0].toNumber();
}

console.error("cannot get periodFinish");
return 0;
} catch (error) {
console.error(error);
return 0;
}
}

async getPeriodStartDate(): Promise<number> {
async getRewardClaimableDate(): Promise<number> {
try {
const response: BigNumber[] = await this.provider.read({
abi: this.abi,
method: "lastUpdateTime",
args: [],
method: "lastDepositOrWithdrawTimestamp",
args: [this.sender],
to: this.address,
});

if (response?.length && BigNumber.isBigNumber(response[0])) {
console.log("getLastRewardUpdateDate", response[0].toBigInt());
return response[0].toNumber();
console.log("lastDepositOrWithdrawTimestamp", response[0].toBigInt());
return response[0].add(43200).toNumber();
}

console.error("cannot get lastUpdateTime");
Expand All @@ -123,46 +104,6 @@ export class StakingPool {
}
}

async getRewardDuration(): Promise<number> {
try {
const response: BigNumber[] = await this.provider.read({
abi: this.abi,
method: "rewardsDuration",
args: [],
to: this.address,
});

if (response?.length && BigNumber.isBigNumber(response[0])) {
console.log("getRewardDuration", response[0].toNumber());
return response[0].toNumber();
}

console.error("cannot get getRewardDuration");
return 0;
} catch (error) {
console.error(error);
return 0;
}
}

async getRewardPerTokenStaked(): Promise<BigNumber | undefined> {
try {
const response: BigNumber[] = await this.provider.read({
abi: this.abi,
method: "rewardPerToken",
args: [],
to: this.address,
});

console.log("getRewardPerTokenStaked:", response);
if (response?.length && BigNumber.isBigNumber(response[0])) {
return response[0];
}
} catch (error) {
console.error(error);
}
}

async getSenderStakedAmount(): Promise<BigNumber | undefined> {
try {
const response: BigNumber[] = await this.provider.read({
Expand Down Expand Up @@ -251,11 +192,9 @@ export class StakingPool {

// assume you staked 1 token
async calculateRealtimeAPR(): Promise<BigNumber> {
const daysInYear = 365;
const rewardRate = await this.getCurrentRewardRate();
const rewardDuration = await this.getRewardDuration();
if (rewardRate && rewardDuration) {
const estimateAPR = rewardRate.mul(rewardDuration).mul(daysInYear / 7 * 100);
if (rewardRate) {
const estimateAPR = rewardRate.mul(YEAR_IN_SECONDS * 100);
return estimateAPR;
}
return constants.Zero;
Expand All @@ -282,6 +221,24 @@ export class StakingPool {
}

async unstake(): Promise<string | undefined> {
try {
const stakedAmount = await this.getSenderStakedAmount();
if (!stakedAmount) return;
const txHash = await this.provider.write({
abi: this.abi,
method: "withdraw",
args: [stakedAmount.toString()],
to: this.address,
from: this.sender,
});
if (txHash) return txHash;
} catch (error) {
console.error(error);
return;
}
}

async unstakeWithReward(): Promise<string | undefined> {
try {
const txHash = await this.provider.write({
abi: this.abi,
Expand All @@ -301,7 +258,7 @@ export class StakingPool {
try {
const txHash = await this.provider.write({
abi: this.abi,
method: "getReward",
method: "claimReward",
args: [],
to: this.address,
from: this.sender,
Expand Down
28 changes: 9 additions & 19 deletions store/flexible-staking.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ERC20TokenInteraction, StakingPool } from "@/services";
import { ERC20TokenInteraction, StakingPool, YEAR_IN_SECONDS } from "@/services";
import { ChainProvider } from "@mochi-web3/login-widget";
import { create } from "zustand";
import { Pool, Token, useTokenStaking } from "./token-staking";
Expand All @@ -24,8 +24,7 @@ interface State {
> | null;
stakingToken: Token | null;
rewardToken: Token | null;
startTime: number; // in seconds
finishTime: number; // in seconds
rewardClaimableDate: number; // in seconds
autoStaking: boolean;
latestStaking: {
txHash: string;
Expand Down Expand Up @@ -57,8 +56,7 @@ const initialState: State = {
stakingPool: null,
stakingToken: null,
rewardToken: null,
startTime: 0,
finishTime: 0,
rewardClaimableDate: 0,
autoStaking: true,
latestStaking: null,
};
Expand Down Expand Up @@ -100,22 +98,17 @@ export const useFlexibleStaking = create<State & Action>((set, get) => ({

const results = await Promise.allSettled([
contract.rewardRate(),
contract.rewardsDuration(),
contract.totalSupply(),
]);
const [rewardRateRes, rewardDurationRes, totalSupplyRes] = results.map(
const [rewardRateRes, totalSupplyRes] = results.map(
(r) => (r.status === "fulfilled" ? r.value : null)
);

// get apr
const daysInYear = 365;
const rewardRate = BigNumber.isBigNumber(rewardRateRes)
? rewardRateRes
: constants.Zero;
const rewardDuration = BigNumber.isBigNumber(rewardDurationRes)
? rewardDurationRes
: constants.Zero;
const apr = rewardRate.mul(rewardDuration).mul((daysInYear / 7) * 100);
const apr = rewardRate.mul(YEAR_IN_SECONDS * 100);

//get pool staked amount
const poolStakedAmount = BigNumber.isBigNumber(totalSupplyRes)
Expand Down Expand Up @@ -160,8 +153,7 @@ export const useFlexibleStaking = create<State & Action>((set, get) => ({
getPoolStakedAmount,
getUnclaimedRewards,
getClaimedRewards,
getStartDate,
getFinishDate,
getLastInteractionDate,
] = await Promise.allSettled([
stakingTokenContract.getTokenBalance(),
stakingTokenContract.getAllowance(
Expand All @@ -172,8 +164,7 @@ export const useFlexibleStaking = create<State & Action>((set, get) => ({
poolContract.getPoolTotalStakedAmount(),
poolContract.getRewardAvailableForClaim(),
poolContract.getClaimedRewardsForAddress(),
poolContract.getPeriodStartDate(),
poolContract.getPeriodFinishDate(),
poolContract.getRewardClaimableDate(),
]);
const [
balance,
Expand All @@ -194,7 +185,7 @@ export const useFlexibleStaking = create<State & Action>((set, get) => ({
].map((r) =>
r.status === "fulfilled" ? r.value || constants.Zero : constants.Zero
);
const [startTime, finishTime] = [getStartDate, getFinishDate].map((r) =>
const [rewardClaimableDate] = [getLastInteractionDate].map((r) =>
r.status === "fulfilled" ? r.value || 0 : 0
);
get().setValues({
Expand All @@ -205,8 +196,7 @@ export const useFlexibleStaking = create<State & Action>((set, get) => ({
poolStakedAmount,
unclaimedRewards,
totalEarnedRewards,
startTime,
finishTime,
rewardClaimableDate,
});
},
}));

0 comments on commit ee48dd2

Please sign in to comment.