Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: updated withdrawal UI #909

Merged
merged 9 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ yarn playwright tests/dappstaking-transactions.spec.ts
- Run the following

```bash
yarn playwright:ci
BASE_URL='http://localhost:8080' yarn playwright:ci
```

### Write test cases
Expand Down
29 changes: 2 additions & 27 deletions src/boot/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,8 @@ let $api: ApiPromise | undefined;
const $web3 = ref<Web3>();

export default boot(async ({ store }) => {
const {
NETWORK_IDX,
CUSTOM_ENDPOINT,
SELECTED_ENDPOINT,
SELECTED_ADDRESS,
SELECTED_WALLET,
IS_APPLIED_RANDOM_ENDPOINT,
DEFAULT_CURRENCY,
} = LOCAL_STORAGE;
const { NETWORK_IDX, CUSTOM_ENDPOINT, SELECTED_ENDPOINT, SELECTED_ADDRESS, SELECTED_WALLET } =
LOCAL_STORAGE;

const networkIdxStore = localStorage.getItem(NETWORK_IDX);
const customEndpoint = localStorage.getItem(CUSTOM_ENDPOINT);
Expand Down Expand Up @@ -80,24 +73,6 @@ export default boot(async ({ store }) => {
endpoint = providerEndpoints[networkIdx.value].endpoints[0].endpoint;
}

// Memo: Temporary solution to reset selected endpoints for users who connected to Astar WSS before implementing the random selection method.
// Todo: Remove this code in middle of July'23
const isAppliedRandomEndpoint = localStorage.getItem(IS_APPLIED_RANDOM_ENDPOINT) === 'true';
if (!isAppliedRandomEndpoint) {
const astarWss = providerEndpoints[endpointKey.ASTAR].endpoints[0].endpoint;
const isResetEndpoint =
selectedEndpoint.hasOwnProperty(endpointKey.ASTAR) &&
selectedEndpoint[endpointKey.ASTAR] === astarWss;
if (isResetEndpoint) {
localStorage.removeItem(SELECTED_ENDPOINT);
localStorage.removeItem(NETWORK_IDX);
localStorage.removeItem(DEFAULT_CURRENCY);
localStorage.setItem(IS_APPLIED_RANDOM_ENDPOINT, 'true');
window.location.reload();
}
localStorage.setItem(IS_APPLIED_RANDOM_ENDPOINT, 'true');
}

// set metadata header
const favicon = providerEndpoints[Number(networkIdx.value)].defaultLogo;
const displayName = providerEndpoints[Number(networkIdx.value)].displayName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@
<li>{{ $t('dappStaking.unbondingEra', { unbondingPeriod }) }}</li>
</div>

<div
v-if="isBelowThanMinStaking"
class="row--box-error box--error"
data-testid="warning-unstake-all-balance"
>
<span class="color--white">
{{
$t('dappStaking.willUnstakeAll', {
minStakingAmount: $n(truncate(minStakingAmount)),
symbol: nativeTokenSymbol,
})
}}
</span>
</div>

<astar-button class="unbond-button" :disabled="!amount" @click="unbound()"
>{{ $t('dappStaking.modals.startUnbonding') }}
</astar-button>
Expand All @@ -73,6 +88,7 @@ import SpeedConfiguration from 'src/components/common/SpeedConfiguration.vue';
import ModalWrapper from 'src/components/common/ModalWrapper.vue';
import { fadeDuration } from '@astar-network/astar-ui';
import { wait } from '@astar-network/astar-sdk-core';
import { useStore } from 'src/store';

export default defineComponent({
components: {
Expand Down Expand Up @@ -100,6 +116,17 @@ export default defineComponent({
const nativeTokenImg = computed<string>(() =>
getTokenImage({ isNativeToken: true, symbol: nativeTokenSymbol.value })
);
const store = useStore();

const minStakingAmount = computed<number>(() => {
const amt = store.getters['dapps/getMinimumStakingAmount'];
return Number(ethers.utils.formatEther(amt));
});

const isBelowThanMinStaking = computed<boolean>(() => {
return minStakingAmount.value > Number(maxAmount.value) - Number(amount.value);
});

const maxAmount = computed<string>(() => {
if (!props.dapp?.yourStake) {
return '0';
Expand Down Expand Up @@ -127,7 +154,8 @@ export default defineComponent({

const unbound = async (): Promise<void> => {
await closeModal();
await handleUnbound(props.dapp?.dappAddress, amount.value);
const unstakeAmount = isBelowThanMinStaking.value ? maxAmount.value : amount.value;
await handleUnbound(props.dapp?.dappAddress, unstakeAmount);
};

return {
Expand All @@ -138,14 +166,16 @@ export default defineComponent({
selectedTip,
nativeTipPrice,
unbondingPeriod,
isBelowThanMinStaking,
minStakingAmount,
isClosingModal,
setSelectedTip,
close,
toMaxAmount,
truncate,
inputHandler,
unbound,
closeModal,
isClosingModal,
};
},
});
Expand Down Expand Up @@ -207,17 +237,26 @@ export default defineComponent({
padding: 8px;
margin-top: 20px;
margin-bottom: 40px;
margin-bottom: 20px;
width: 344px;
@media (min-width: $md) {
width: 400px;
}
}

.box--error {
width: 344px !important;
@media (min-width: $md) {
width: 400px !important;
}
}

.unbond-button {
width: 340px;
font-size: 22px;
font-weight: 600;
height: 44px;
margin-top: 20px;
@media (min-width: $md) {
width: 400px;
}
Expand Down
1 change: 0 additions & 1 deletion src/config/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export enum LOCAL_STORAGE {
BALLOON_NATIVE_TOKEN = 'balloonNativeToken',
THEME_COLOR = 'themeColor',
IS_LEDGER = 'isLedger',
IS_APPLIED_RANDOM_ENDPOINT = 'isAppliedRandomEndpoint', // Todo: Remove this line in middle of July'23
MULTISIG = 'multisig',
}

Expand Down
2 changes: 2 additions & 0 deletions src/i18n/en-US/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ export default {
claim: 'Claim',
withdraw: 'Withdraw',
unbondingEra: 'Unbonding takes {unbondingPeriod} eras before you can withdraw',
willUnstakeAll:
'It will unstake all of your staked balance because the minimum staking amount is {minStakingAmount} {symbol}',
turnOn: 'Turn on',
turnOff: 'Turn off',
on: 'ON',
Expand Down
20 changes: 20 additions & 0 deletions tests/common-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { GeneralStakerInfo, getDappAddressEnum } from '@astar-network/astar-sdk-core';
import { ApiPromise, Keyring, WsProvider } from '@polkadot/api';
import { Option, u32 } from '@polkadot/types';
import { AccountLedger } from 'src/hooks';
Expand Down Expand Up @@ -51,6 +52,25 @@ export const getStakedAmount = async (address: string): Promise<bigint> => {
return eraStake.isSome ? BigInt(eraStake.unwrap().total.toString()) : BigInt(0);
};

export const fetchAccountStakingAmount = async (
currentAccount: string,
dappAddress: string
): Promise<bigint> => {
const api = await getApi();
const stakerInfo = await api.query.dappsStaking.generalStakerInfo<GeneralStakerInfo>(
currentAccount,
getDappAddressEnum(dappAddress)
);
const balance = stakerInfo.stakes.length && stakerInfo.stakes.slice(-1)[0].staked.toString();

return BigInt(balance);
};

export const fetchMinimumStakingAmount = async (): Promise<string> => {
const api = await getApi();
return String(api.consts.dappsStaking.minimumStakingAmount);
};

export const getAccountLedger = async (address: string): Promise<AccountLedger> => {
const api = await getApi();
const ledger = await api.query.dappsStaking.ledger<AccountLedger>(address);
Expand Down
51 changes: 46 additions & 5 deletions tests/test_specs/dappstaking-transactions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,36 @@ import {
import { test } from '../fixtures';
import {
chainDecimals,
forceNewEra,
fetchAccountStakingAmount,
fetchMinimumStakingAmount,
// forceNewEra,
getAccountLedger,
getBalance,
getStakedAmount,
setRewardDestination,
} from '../common-api';
import { ethers } from 'ethers';

// Memo: Astar Core Contributors
const TEST_DAPP_ADDRESS = '0xa602d021da61ec4cc44dedbd4e3090a05c97a435';

const stake = async (page: Page, context: BrowserContext, amount: bigint): Promise<void> => {
await page.goto(`/custom-node/dapp-staking/stake?dapp=${TEST_DAPP_ADDRESS}`);
const stake = async (
page: Page,
context: BrowserContext,
amount: bigint,
dapp = TEST_DAPP_ADDRESS
): Promise<void> => {
await page.goto(`/custom-node/dapp-staking/stake?dapp=${dapp}`);
await selectAccount(page, ALICE_ACCOUNT_NAME);
await page.getByPlaceholder('0.0').fill(amount.toString());
await page.getByRole('button', { name: 'Confirm' }).click();

const stakedAmountBefore = await getStakedAmount(TEST_DAPP_ADDRESS);
const stakedAmountBefore = await getStakedAmount(dapp);
await signTransaction(context);
await page.waitForSelector('.four', { state: 'hidden' });

await expect(page.getByText('Success', { exact: true })).toBeVisible();
const stakedAmountAfter = await getStakedAmount(TEST_DAPP_ADDRESS);
const stakedAmountAfter = await getStakedAmount(dapp);
expect(stakedAmountAfter - stakedAmountBefore).toEqual(
amount * BigInt(Math.pow(10, chainDecimals))
);
Expand Down Expand Up @@ -116,6 +124,39 @@ test.describe('dApp staking transactions', () => {
);
});

test('unstake all the staking balance if the resulting staking amount is less than minimum staking amount', async ({
page,
context,
}) => {
// Memo:Stake first
await stake(page, context, BigInt(1000));
await page.goto('/custom-node/dapp-staking/discover');
const minimumStakingAmount = await fetchMinimumStakingAmount();
const stakingAmount = ethers.utils.formatEther(
(await fetchAccountStakingAmount(ALICE_ADDRESS, TEST_DAPP_ADDRESS)).toString()
);
const unstakeAmount =
Number(stakingAmount) - Number(ethers.utils.formatEther(minimumStakingAmount)) + 1;
await page.goto('/custom-node/dapp-staking/discover');
await page.getByText('My dApps').click();
await page.getByRole('button', { name: 'Unbond' }).click();
await page.getByPlaceholder('0.0').fill(unstakeAmount.toString());

const warningMsg = page.getByTestId('warning-unstake-all-balance');
await expect(warningMsg).toBeVisible();

await page.getByRole('button', { name: 'Start unbonding' }).click();
await signTransaction(context);
await page.waitForSelector('.four', { state: 'hidden' });

await expect(page.getByText('Success', { exact: true })).toBeVisible();

const latestStakingAmount = ethers.utils.formatEther(
(await fetchAccountStakingAmount(ALICE_ADDRESS, TEST_DAPP_ADDRESS)).toString()
);
expect(Number(latestStakingAmount)).toEqual(0);
});

// Test case: DS005
// test('user should be able to claim rewards', async ({ page, context }) => {
// await stake(page, context, BigInt(1000));
Expand Down