Skip to content

Commit

Permalink
fix: remove console log (#88)
Browse files Browse the repository at this point in the history
* fix: remove console log

* fix: add claim reward method
  • Loading branch information
abdulhakim2902 committed Jan 31, 2023
1 parent 9db7c13 commit 5c64f94
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 65 deletions.
2 changes: 1 addition & 1 deletion src/components/molecules/CardInstance/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ interface CardInstanceInterface {
accountId: string,
instance: ServerListProps,
) => Promise<void>;
onWithdrawReward?: (accountId: string) => Promise<void>;
onWithdrawReward?: (accountId: string, instanceId: number) => Promise<void>;
type: InstanceType;
}

Expand Down
5 changes: 4 additions & 1 deletion src/components/molecules/Staked/Deregister.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import CardStaked from '../../atoms/CardStaked';
import ModalComponent from '../Modal';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import { PolkadotAccountList } from '../PolkadotAccountList';
import { BN_ZERO } from '@polkadot/util';

interface DeregisterProps {
instance: ServerListProps;
Expand Down Expand Up @@ -81,7 +82,9 @@ export const Deregister = (props: DeregisterProps) => {
onClick={handleOpenModal}
label={
Boolean(instance.unstakedAt)
? 'Waiting To Unstaked'
? instance.stakedAmount.lte(BN_ZERO)
? 'Unstaked'
: 'Waiting for Unstaked'
: 'De-Register Instance'
}
isFullWidth
Expand Down
9 changes: 5 additions & 4 deletions src/components/molecules/Staked/TotalStaked.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,8 @@ export const TotalStaked = (props: TotalStakedProps) => {
let fixedValue = Number(inputValue[0]).toLocaleString() + inputDecimal;

if (inputValue[1]?.length > 10) return;
console.log(fixedValue);

const valueDecimal = inputValue[1]?.length ?? 0;
const updatedDecimal = new BN((10 ** (18 - valueDecimal)).toString());
console.log(+updatedDecimal);
let value = +fixedValue.replace(/,/gi, '').replace(/\./gi, '');
if (+value >= 100000 * 10 ** valueDecimal) {
value = 100000 * 10 ** valueDecimal;
Expand Down Expand Up @@ -214,7 +211,11 @@ export const TotalStaked = (props: TotalStakedProps) => {
<ShowIf condition={Boolean(instance.unstakedAt)}>
<Button
onClick={null}
label={'Waiting To Unstaked'}
label={
instance.stakedAmount.lte(BN_ZERO)
? 'Unstaked'
: 'Waiting for Unstaked'
}
primary
isFullWidth
disable
Expand Down
7 changes: 5 additions & 2 deletions src/components/molecules/Staked/UnclaimReward.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { PolkadotAccountList } from '../PolkadotAccountList';

interface UnclaimRewardProps {
instance: ServerListProps;
onWithdrawReward?: (accountId: string) => Promise<void>;
onWithdrawReward?: (accountId: string, instanceId: number) => Promise<void>;
}

export const UnclaimReward = (props: UnclaimRewardProps) => {
Expand All @@ -26,6 +26,8 @@ export const UnclaimReward = (props: UnclaimRewardProps) => {
const [extensionInstalled, setExtensionInstalled] = useState(false);
const [showAccountList, setShowAccountList] = useState<boolean>(false);

const hasReward = instance.rewards && instance.rewards.length > 0;

const handleOpenModal = () => {
setOpenModal(!openModal);
};
Expand Down Expand Up @@ -54,7 +56,7 @@ export const UnclaimReward = (props: UnclaimRewardProps) => {
) => {
if (!onWithdrawReward) return;
try {
await onWithdrawReward(account.address);
await onWithdrawReward(account.address, instance.id);
onCloseAccountList();
} catch (err) {
console.log(err);
Expand Down Expand Up @@ -90,6 +92,7 @@ export const UnclaimReward = (props: UnclaimRewardProps) => {
label={'Claim Rewards'}
primary
isFullWidth
disable={!hasReward}
/>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/organisms/Instance/InstanceList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ type InstanceListProps = {
accountId: string,
instance: ServerListProps,
) => Promise<void>;
onWithdrawReward?: (accountId: string) => Promise<void>;
onWithdrawReward?: (accountId: string, instanceId: number) => Promise<void>;
};

export const InstanceList: React.FC<InstanceListProps> = ({
Expand Down
16 changes: 14 additions & 2 deletions src/hooks/use-instances.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ export const useInstances = (

let totalStakedAmount = BN_ZERO;

const [result, balance] = await Promise.all([
const [result, rewards, balance] = await Promise.all([
provider.serverListByOwner(accountId),
provider.rewardBalance(accountId, 0),
provider.accountBalance(accountId),
]);

Expand All @@ -108,6 +109,7 @@ export const useInstances = (

return {
...server,
rewards,
detail: data,
};
}),
Expand Down Expand Up @@ -266,13 +268,23 @@ export const useInstances = (
}
};

const withdrawReward = async (accountId: string): Promise<void> => {
const withdrawReward = async (
accountId: string,
instanceId: number,
): Promise<void> => {
try {
if (!provider || !accountId) return;

await provider.withdrawReward(accountId, async (signerOpened) => {
if (signerOpened) setLoading(true);
});

const newServerList = serverList.map((e) => {
if (e.id === instanceId) return { ...e, rewards: [] };
return e;
});

setServerList([...newServerList]);
} catch (err) {
console.log(err);
} finally {
Expand Down
6 changes: 6 additions & 0 deletions src/interface/RewardBalanceInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { BN } from '@polkadot/util';

export interface RewardBalance {
ftIdentifier: string;
amount: BN;
}
2 changes: 2 additions & 0 deletions src/interface/ServerListInterface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { BN } from '@polkadot/util';
import { RewardBalance } from './RewardBalanceInterface';

export interface ServerListProps {
id: number;
owner: string;
apiUrl: string;
stakedAmount: BN;
unstakedAt?: number;
rewards?: RewardBalance[];
detail?: ServerDetail;
}

Expand Down
146 changes: 93 additions & 53 deletions src/lib/services/polkadot-js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import { BN, numberToHex } from '@polkadot/util';

import { ServerListProps } from 'src/interface/ServerListInterface';
import { RewardBalance } from '../../interface/RewardBalanceInterface';

const { publicRuntimeConfig } = getConfig();

Expand Down Expand Up @@ -332,6 +333,65 @@ export class PolkadotJs implements IProvider {
}
}

async withdrawReward(
accountId: string,
callback?: (signerOpened?: boolean) => void,
): Promise<string | undefined> {
try {
const { web3FromSource } = await import('@polkadot/extension-dapp');

const signer = await this.signer(accountId);
const injector = await web3FromSource(signer.meta.source);

callback && callback(true);

const extrinsic = this.provider.tx.tipping.withdrawReward();
const txInfo = await extrinsic.signAsync(signer.address, {
signer: injector.signer,
nonce: -1,
});

const txHash: string = await new Promise((resolve, reject) => {
txInfo
.send(({ status, isError, dispatchError }) => {
if (status.isInBlock) {
console.log(`\tBlock hash : ${status.asInBlock.toHex()}`);
} else if (status.isFinalized) {
console.log(`\tFinalized : ${status.asFinalized.toHex()}`);
resolve(status.asFinalized.toHex());
} else if (isError) {
console.log(`\tFinalized : null`);
reject('FailedToSendTip');
}

if (dispatchError) {
if (dispatchError.isModule) {
const { name } = this.provider.registry.findMetaError(
dispatchError.asModule,
);

reject(new Error(name));
} else {
const dispatchErrorType = dispatchError.toString();
const parseDispatch = JSON.parse(dispatchErrorType);

const values: string[] = Object.values(parseDispatch);

reject(new Error(values[0] ?? 'ExtrinsicFailed'));
}
}
})
.catch((err) => {
reject(err);
});
});

return txHash;
} catch (err) {
throw err;
}
}

async totalServer(): Promise<number> {
try {
const result = await this.provider.query.server.serverCount();
Expand Down Expand Up @@ -416,62 +476,33 @@ export class PolkadotJs implements IProvider {
}
}

async withdrawReward(
async rewardBalance(
accountId: string,
callback?: (signerOpened?: boolean) => void,
): Promise<string | undefined> {
serverId: number,
startKey?: string,
pageSize = 10,
): Promise<RewardBalance[]> {
try {
const { web3FromSource } = await import('@polkadot/extension-dapp');

const signer = await this.signer(accountId);
const injector = await web3FromSource(signer.meta.source);

callback && callback(true);

const extrinsic = this.provider.tx.tipping.withdrawReward();
const txInfo = await extrinsic.signAsync(signer.address, {
signer: injector.signer,
nonce: -1,
});

const txHash: string = await new Promise((resolve, reject) => {
txInfo
.send(({ status, isError, dispatchError, events }) => {
if (status.isInBlock) {
console.log(`\tBlock hash : ${status.asInBlock.toHex()}`);
} else if (status.isFinalized) {
console.log(`\tFinalized : ${status.asFinalized.toHex()}`);
resolve(status.asFinalized.toHex());
} else if (isError) {
console.log(`\tFinalized : null`);
reject('FailedToSendTip');
}

if (dispatchError) {
if (dispatchError.isModule) {
const { name } = this.provider.registry.findMetaError(
dispatchError.asModule,
);

reject(new Error(name));
} else {
const dispatchErrorType = dispatchError.toString();
const parseDispatch = JSON.parse(dispatchErrorType);
const result =
await this.provider.query.tipping.rewardBalance.entriesPaged({
args: [accountId],
pageSize,
startKey,
});

const values: string[] = Object.values(parseDispatch);
const data = result.map((list) => {
const key = list[0].toHuman() as string[];
const reward = list[1].toHuman() as string;

reject(new Error(values[0] ?? 'ExtrinsicFailed'));
}
}
})
.catch((err) => {
reject(err);
});
return {
ftIdentifier: key[1],
amount: new BN(reward.replace(/,/gi, '')),
};
});

return txHash;
} catch (err) {
throw err;
return data;
} catch {
return [];
}
}

Expand All @@ -495,6 +526,7 @@ export interface IProvider {

signer: (accountId: string) => Promise<InjectedAccountWithMeta>;

// Call
createServer: (
owner: string,
apiURL: string,
Expand All @@ -516,6 +548,12 @@ export interface IProvider {
callback?: (server?: ServerListProps, signerOpened?: boolean) => void,
) => Promise<string | null>;

withdrawReward: (
accountId: string,
callback?: (signerOpened?: boolean) => void,
) => Promise<string | void>;

// View
totalServer: () => Promise<number>;

serverList: (
Expand All @@ -529,10 +567,12 @@ export interface IProvider {
pageSize?: number,
) => Promise<ServerListProps[]>;

withdrawReward: (
rewardBalance: (
accountId: string,
callback?: (signerOpened?: boolean) => void,
) => Promise<string | void>;
serverId: number,
startKey?: string,
pageSize?: number,
) => Promise<RewardBalance[]>;

accountBalance: (accountId: string) => Promise<BN>;

Expand Down
2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const getServerSideProps = async (
const server = cookies?.session;

let signIn = false;
let address;
let address = null;

try {
const data = JSON.parse(server);
Expand Down

0 comments on commit 5c64f94

Please sign in to comment.