Skip to content
This repository has been archived by the owner on Feb 3, 2023. It is now read-only.

Commit

Permalink
Merge pull request #93 from ElrondNetwork/Upgrade-erdjs
Browse files Browse the repository at this point in the history
Upgrade erdjs
  • Loading branch information
danielailie authored Apr 29, 2021
2 parents a2a15fb + 60cb1cf commit 83ba5d3
Show file tree
Hide file tree
Showing 26 changed files with 230 additions and 191 deletions.
199 changes: 104 additions & 95 deletions react-delegationdashboard/package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion react-delegationdashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@elrondnetwork/erdjs": "^3.1.3",
"@elrondnetwork/erdjs": "^4.1.0",
"@fortawesome/fontawesome-svg-core": "^1.2.34",
"@fortawesome/free-solid-svg-icons": "^5.15.2",
"@fortawesome/react-fontawesome": "^0.1.12",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { useDelegation } from 'helpers';
import { DelegationTransactionType } from 'helpers/contractDataDefinitions';
import { TransactionHash } from '@elrondnetwork/erdjs/out';
import { TransactionHash } from '@elrondnetwork/erdjs';
import TransactionStatusModal from 'components/LedgerTransactionStatus';
import { useHistory } from 'react-router-dom';
import { useContext, useDispatch } from 'context';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ContractReturnData } from '@elrondnetwork/erdjs/out/smartcontracts/query';
import { decodeString } from '@elrondnetwork/erdjs';
import denominate from 'components/Denominate/formatters';
import {
yearSettings,
Expand Down Expand Up @@ -31,13 +31,16 @@ const calculateAPR = ({
stats: Stats;
networkConfig: NetworkConfig;
networkStake: NetworkStake;
blsKeys: ContractReturnData[];
blsKeys: Buffer[];
totalActiveStake: string;
}) => {
const allNodes = blsKeys.filter(
key => key.asString === 'staked' || key.asString === 'jailed' || key.asString === 'queued'
key =>
decodeString(key) === 'staked' ||
decodeString(key) === 'jailed' ||
decodeString(key) === 'queued'
).length;
const allActiveNodes = blsKeys.filter(key => key.asString === 'staked').length;
const allActiveNodes = blsKeys.filter(key => decodeString(key) === 'staked').length;
if (allActiveNodes <= 0) {
return '0.00';
}
Expand Down
58 changes: 33 additions & 25 deletions react-delegationdashboard/src/components/Layout/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { QueryResponse } from '@elrondnetwork/erdjs/out/smartcontracts/query';
import BigNumber from 'bignumber.js';
import denominate from 'components/Denominate/formatters';
import { denomination, decimals, auctionContract, network } from 'config';
Expand All @@ -17,6 +16,12 @@ import { calculateAPR } from './APRCalculation';
import Footer from './Footer';
import Navbar from './Navbar';
import axios from 'axios';
import {
QueryResponse,
decodeUnsignedNumber,
decodeBigNumber,
decodeString,
} from '@elrondnetwork/erdjs';

const getStakingSCBalance = async (): Promise<string> => {
const result = await axios.get(`${network.apiAddress}/accounts/${auctionContract}`);
Expand All @@ -40,33 +45,35 @@ const Layout = ({ children, page }: { children: React.ReactNode; page: string })
} = contractViews;

const getContractOverviewType = (value: QueryResponse) => {
let untypedResponse = value.outputUntyped();
let initialOwnerFunds = denominate({
decimals,
denomination,
input: value.returnData[3].asBigInt.toFixed(),
input: decodeBigNumber(untypedResponse[3]).toFixed(),
});
return new ContractOverview(
value.returnData[0].asHex.toString(),
(value.returnData[1].asNumber / 100).toString(),
value.returnData[2].asBigInt.toFixed(),
untypedResponse[0].toString('hex'),
(decodeUnsignedNumber(untypedResponse[1]) / 100).toString(),
decodeBigNumber(untypedResponse[2]).toFixed(),
initialOwnerFunds,
value.returnData[4]?.asString,
value.returnData[5]?.asBool,
value.returnData[6].asBool,
value.returnData[7]?.asString,
value.returnData[8].asBool,
value.returnData[9]?.asNumber * 6
decodeString(untypedResponse[4]),
decodeString(untypedResponse[5]),
decodeString(untypedResponse[6]),
decodeString(untypedResponse[7]),
decodeString(untypedResponse[8]),
decodeUnsignedNumber(untypedResponse[9]) * 6
);
};

const getAgencyMetaDataType = (value: QueryResponse) => {
if (value && value.returnData && value.returnData.length === 0) {
return emptyAgencyMetaData;
}
const untypedResponse = value.outputUntyped();
return new AgencyMetadata(
value.returnData[0]?.asString,
value.returnData[1]?.asString,
value.returnData[2]?.asString
decodeString(untypedResponse[0]),
decodeString(untypedResponse[1]),
decodeString(untypedResponse[2])
);
};
React.useEffect(() => {
Expand All @@ -87,10 +94,8 @@ const Layout = ({ children, page }: { children: React.ReactNode; page: string })
metaData,
numUsers,
contractOverview,
{
returnData: [activeStake],
},
{ returnData: blsKeys },
activeStake,
blsKeysResponse,
networkStats,
networkStake,
networkConfig,
Expand All @@ -99,11 +104,11 @@ const Layout = ({ children, page }: { children: React.ReactNode; page: string })
]) => {
dispatch({
type: 'setNumUsers',
numUsers: numUsers.returnData[0].asNumber,
numUsers: decodeUnsignedNumber(numUsers.outputUntyped()[0]),
});
dispatch({
type: 'setMinDelegationAmount',
minDelegationAmount: delegationManager.returnData[5].asNumber,
minDelegationAmount: decodeUnsignedNumber(delegationManager.outputUntyped()[0]),
});
const contract = getContractOverviewType(contractOverview);
dispatch({
Expand All @@ -116,11 +121,14 @@ const Layout = ({ children, page }: { children: React.ReactNode; page: string })
});
dispatch({
type: 'setTotalActiveStake',
totalActiveStake: activeStake.asBigInt.toFixed(),
totalActiveStake: decodeBigNumber(activeStake.outputUntyped()[0]).toFixed(),
});
dispatch({
type: 'setNumberOfActiveNodes',
numberOfActiveNodes: blsKeys.filter(key => key.asString === 'staked').length.toString(),
numberOfActiveNodes: blsKeysResponse
.outputUntyped()
.filter(key => decodeString(key) === 'staked')
.length.toString(),
});
dispatch({
type: 'setNetworkConfig',
Expand Down Expand Up @@ -151,16 +159,16 @@ const Layout = ({ children, page }: { children: React.ReactNode; page: string })
networkStake.QueueSize,
new BigNumber(stakingBalance) // Replace with the economics value from erdjs 4.x
),
blsKeys: blsKeys,
totalActiveStake: activeStake.asBigInt.toFixed(),
blsKeys: blsKeysResponse.outputUntyped(),
totalActiveStake: decodeBigNumber(activeStake.outputUntyped()[0]).toFixed(),
})
);

dispatch({
type: 'setAprPercentage',
aprPercentage: (
APR -
APR * ((contract?.serviceFee ? parseFloat(contract.serviceFee) : 15) / 100)
APR * ((contract?.serviceFee ? parseFloat(contract.serviceFee) : 0) / 100)
)
.toFixed(2)
.toString(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TransactionHash } from '@elrondnetwork/erdjs/out';
import { TransactionHash } from '@elrondnetwork/erdjs';
import { faCheck, faHourglass, faTimes } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useContext } from 'context';
Expand Down Expand Up @@ -81,7 +81,7 @@ const TransactionStatusModal = ({ show, txHash }: TransactionStatusModalType) =>
icon={txDStatus.icon}
className={`text-white ml-1 ${getStatus(txStatus.pending) && spin ? 'fa-spin' : ''}`}
/>
<StatusTxDetails txHash={txHash.hash} />
<StatusTxDetails txHash={txHash.toString()} />
</div>

<button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { decimals, denomination } from 'config';
import { useContext } from 'context';
import denominate from 'components/Denominate/formatters';
import StatCard from 'components/StatCard';
import { Address, NetworkStake } from '@elrondnetwork/erdjs/out';
import { Address, NetworkStake } from '@elrondnetwork/erdjs';
import { useState } from 'react';

import SetPercentageFeeAction from './SetPercentageFeeAction';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Address } from '@elrondnetwork/erdjs/out';
import { Address } from '@elrondnetwork/erdjs';
import { useContext, useDispatch } from 'context';
import SetAgencyMetaDataModal from './SetAgencyMetaDataModal';
import { getItem } from 'storage/session';
Expand Down
6 changes: 3 additions & 3 deletions react-delegationdashboard/src/context/state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ export const emptyContractOverview: ContractOverview = {
maxDelegationCap: '',
initialOwnerFunds: '',
automaticActivation: 'false',
withDelegationCap: false,
changeableServiceFee: false,
withDelegationCap: 'false',
changeableServiceFee: 'false',
reDelegationCap: 'false',
createdNounce: false,
createdNounce: 'false',
unBondPeriod: 0,
};

Expand Down
11 changes: 5 additions & 6 deletions react-delegationdashboard/src/contracts/ContractViews.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Address, ContractFunction, Argument } from '@elrondnetwork/erdjs/out';
import { Query } from '@elrondnetwork/erdjs/out/smartcontracts/query';
import { Address, AddressValue, ContractFunction, Query } from '@elrondnetwork/erdjs';
import { auctionContract, delegationManagerContract } from 'config';
import { DappState } from '../context/state';

Expand All @@ -8,23 +7,23 @@ export const contractViews = {
const query = new Query({
address: new Address(delegationContract),
func: new ContractFunction('getUserActiveStake'),
args: [Argument.fromPubkey(new Address(address))],
args: [new AddressValue(new Address(address))],
});
return dapp.proxy.queryContract(query);
},
getUserUnDelegatedList: (dapp: DappState, address: string, delegationContract?: string) => {
const query = new Query({
address: new Address(delegationContract),
func: new ContractFunction('getUserUnDelegatedList'),
args: [Argument.fromPubkey(new Address(address))],
args: [new AddressValue(new Address(address))],
});
return dapp.proxy.queryContract(query);
},
getClaimableRewards: (dapp: DappState, address: string, delegationContract?: string) => {
const query = new Query({
address: new Address(delegationContract),
func: new ContractFunction('getClaimableRewards'),
args: [Argument.fromPubkey(new Address(address))],
args: [new AddressValue(new Address(address))],
});
return dapp.proxy.queryContract(query);
},
Expand Down Expand Up @@ -67,7 +66,7 @@ export const contractViews = {
const query = new Query({
address: new Address(auctionContract),
func: new ContractFunction('getBlsKeysStatus'),
args: [Argument.fromPubkey(new Address(delegationContract))],
args: [new AddressValue(new Address(delegationContract))],
});
return dapp.proxy.queryContract(query);
},
Expand Down
4 changes: 2 additions & 2 deletions react-delegationdashboard/src/contracts/Delegation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default class Delegation {
console.warn('invalid signerProvider');
}

return new Transaction();
throw new Error('invalid signerProvider');
}

private async sendTransactionBasedOnType(
Expand All @@ -77,7 +77,7 @@ export default class Delegation {
let transaction = new Transaction({
chainID: delegationTransactionType.chainId,
receiver: this.contract.getAddress(),
value: Balance.eGLD(delegationTransactionType.value),
value: Balance.egld(delegationTransactionType.value),
gasLimit: new GasLimit(delegationContract.gasLimit),
data: payload,
nonce: this.account?.nonce,
Expand Down
12 changes: 6 additions & 6 deletions react-delegationdashboard/src/helpers/contractDataDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@ export class ContractOverview {
maxDelegationCap: string;
initialOwnerFunds?: string;
automaticActivation: string;
withDelegationCap?: boolean;
changeableServiceFee?: boolean;
withDelegationCap?: string;
changeableServiceFee?: string;
reDelegationCap: string;
createdNounce?: boolean;
createdNounce?: string;
unBondPeriod?: number;
public constructor(
ownerAddress: string = '',
serviceFee?: string,
maxDelegationCap: string = '',
initialOwnerFunds?: string,
automaticActivation: string = 'false',
withDelegationCap: boolean = false,
changeableServiceFee?: boolean,
withDelegationCap: string = 'false',
changeableServiceFee?: string,
reDelegationCap: string = 'false',
createdNounce?: boolean,
createdNounce?: string,
unBondPeriod?: number
) {
this.ownerAddress = ownerAddress;
Expand Down
3 changes: 1 addition & 2 deletions react-delegationdashboard/src/helpers/decodePem.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Address } from '@elrondnetwork/erdjs/out';
import { BLS, ValidatorSecretKey } from '@elrondnetwork/erdjs/out/walletcore/validatorKeys';
import { Address, BLS, ValidatorSecretKey } from '@elrondnetwork/erdjs';

function hexStringToByte(str: string) {
if (!str) {
Expand Down
4 changes: 2 additions & 2 deletions react-delegationdashboard/src/helpers/useDelegation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TransactionHash } from '@elrondnetwork/erdjs/out';
import { TransactionHash } from '@elrondnetwork/erdjs';
import { useContext } from 'context';
import { Delegation } from 'contracts';
import { DelegationTransactionType } from './contractDataDefinitions';
Expand All @@ -16,7 +16,7 @@ export default function useDelegation({ handleClose, setLedgerDataError }: UseDe
delegation
.sendTransaction(transactionArguments)
.then(transaction => {
handleClose(transaction.hash);
handleClose(transaction.getHash());
})
.catch(e => {
if (e.statusCode in ledgerErrorCodes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const DelegateModal = ({ show, balance, handleClose, handleContinue }: DelegateM
};

const getAvailableToDelegate = () => {
if (contractOverview?.withDelegationCap) {
if (contractOverview && contractOverview.withDelegationCap === 'true') {
const bnAvailable = new BigNumber(entireBalanceMinusDust);
const totalActive = denominate({
input: totalActiveStake,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ClaimRewardsAction from '../Actions/ClaimRewardsAction';
import { faCircleNotch } from '@fortawesome/free-solid-svg-icons';
import State from 'components/State';
import { denomination, decimals } from 'config';
import { decodeBigNumber, decodeUnsignedNumber } from '@elrondnetwork/erdjs';

const MyDelegation = () => {
const { dapp, address, egldLabel, delegationContract, loading } = useContext();
Expand All @@ -23,29 +24,31 @@ const MyDelegation = () => {
dispatch({ type: 'loading', loading: true });
getClaimableRewards(dapp, address, delegationContract)
.then(value => {
if (value.returnData.length > 0 && value.returnData[0]?.asNumber !== 0) {
const untypedResponse = value.outputUntyped();
if (untypedResponse.length > 0 && decodeUnsignedNumber(untypedResponse[0]) !== 0) {
setDisplayRewards(true);
}
setClaimableRewards(
denominate({
denomination,
decimals: 4,
input: value.returnData[0]?.asBigInt.toFixed(),
input: decodeBigNumber(untypedResponse[0]).toFixed(),
}) || ''
);
})
.catch(e => console.error('getClaimableRewards error', e));
getUserActiveStake(dapp, address, delegationContract)
.then(value => {
const untypedResponse = value.outputUntyped();
setUserActiveStake(
denominate({
denomination,
decimals,
input: value.returnData[0]?.asBigInt.toFixed(),
input: decodeBigNumber(untypedResponse[0]).toFixed(),
}) || ''
);
setUserActiveNominatedStake(value.returnData[0]?.asBigInt.toFixed());
if (value.returnData.length > 0 && value.returnData[0]?.asNumber !== 0) {
setUserActiveNominatedStake(decodeBigNumber(untypedResponse[0]).toFixed());
if (untypedResponse.length > 0 && decodeUnsignedNumber(untypedResponse[0]) !== 0) {
setDisplayUndelegate(true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ const UndelegatedValueRow = ({
<ConfirmOnLedgerModal
show={showCheckYourLedgerModal}
transactionArguments={transactionArguments}
handleClose={() => {}}
handleClose={() => {
setShowCheckYourLedgerModal(false);
}}
/>
</>
);
Expand Down
Loading

0 comments on commit 83ba5d3

Please sign in to comment.