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

Added Dpos contract calls to new sdk package #583

Open
wants to merge 19 commits into
base: feat/sdk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion packages/taraxa-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"author": "Taraxa",
"peerDependencies": {
"react": "^18.1.0",
"react-dom": "^18.1.0"
"react-dom": "^18.1.0",
"ethers": "^5.4.7"
},
"dependencies": {
"@rollup/plugin-commonjs": "^17.0.0",
Expand Down
99 changes: 99 additions & 0 deletions packages/taraxa-sdk/src/context/TaraxaDposClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ethers } from 'ethers';
import { Network, networks } from '../utils/networks';

export class TaraxaDposClient {
public mainnetProvider: ethers.providers.JsonRpcProvider;
Malak67 marked this conversation as resolved.
Show resolved Hide resolved

public browserProvider: ethers.providers.Web3Provider | null = null;

public signer: ethers.Signer | null = null;

public chainId: number;

public network: Network;

public mainnetDpos: ethers.Contract | null = null;

public browserDpos: ethers.Contract | null = null;

constructor(networkIdOrName: number | string) {
this.network = this.lookupNetwork(networkIdOrName);

if (!this.network) {
throw new Error('Invalid network ID or name');
}

this.mainnetProvider = new ethers.providers.JsonRpcProvider(
this.network.rpcUrl
);
this.chainId = this.getChainIdFromNetwork(this.network);

if (window.ethereum) {
this.browserProvider = new ethers.providers.Web3Provider(
window.ethereum,
'any'
);
this.signer = this.browserProvider.getSigner();
}

this.initializeContracts();
}

private initializeContracts() {
const abi = [
'function cancelUndelegate(address validator)',
'function claimCommissionRewards(address validator)',
'function claimRewards(address validator)',
'function confirmUndelegate(address validator)',
'function delegate(address validator) payable',
'function getDelegations(address delegator, uint32 batch) view returns (tuple(address account, tuple(uint256 stake, uint256 rewards) delegation)[] delegations, bool end)',
'function getTotalEligibleVotesCount() view returns (uint64)',
'function getUndelegations(address delegator, uint32 batch) view returns (tuple(uint256 stake, uint64 block, address validator, bool validator_exists)[] undelegations, bool end)',
'function getValidator(address validator) view returns (tuple(uint256 total_stake, uint256 commission_reward, uint16 commission, uint64 last_commission_change, address owner, string description, string endpoint) validator_info)',
'function getValidatorEligibleVotesCount(address validator) view returns (uint64)',
'function getValidators(uint32 batch) view returns (tuple(address account, tuple(uint256 total_stake, uint256 commission_reward, uint16 commission, uint64 last_commission_change, address owner, string description, string endpoint) info)[] validators, bool end)',
'function getValidatorsFor(address owner, uint32 batch) view returns (tuple(address account, tuple(uint256 total_stake, uint256 commission_reward, uint16 commission, uint64 last_commission_change, address owner, string description, string endpoint) info)[] validators, bool end)',
'function isValidatorEligible(address validator) view returns (bool)',
'function reDelegate(address validator_from, address validator_to, uint256 amount)',
'function registerValidator(address validator, bytes proof, bytes vrf_key, uint16 commission, string description, string endpoint) payable',
'function setCommission(address validator, uint16 commission)',
'function setValidatorInfo(address validator, string description, string endpoint)',
'function undelegate(address validator, uint256 amount)',
];

if (this.mainnetProvider) {
this.mainnetDpos = new ethers.Contract(
'0x00000000000000000000000000000000000000fe',
abi,
this.mainnetProvider
);
}

if (this.browserProvider && this.signer) {
const contract = new ethers.Contract(
'0x00000000000000000000000000000000000000fe',
abi,
this.browserProvider
);
this.browserDpos = contract.connect(this.signer);
}
}

private lookupNetwork(networkIdOrName: number | string): Network {
if (typeof networkIdOrName === 'number') {
return networks[networkIdOrName];
}
const network = Object.values(networks).find(
(network) =>
network.chainName.toLowerCase() === networkIdOrName.toLowerCase()
)!;
return network;
}

private getChainIdFromNetwork(network: Network): number {
const chainId = Object.keys(networks).find(
(key) => networks[parseInt(key, 10)] === network
);
return chainId ? parseInt(chainId, 10) : 0;
}
}
50 changes: 50 additions & 0 deletions packages/taraxa-sdk/src/context/TaraxaDposContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, {
createContext,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { ethers } from 'ethers';
import { TaraxaDposClient } from './TaraxaDposClient';

interface TaraxaDposContextProps {
mainnetDpos: ethers.Contract | null;
browserDpos: ethers.Contract | null;
}

const TaraxaDposContext = createContext<TaraxaDposContextProps>({
mainnetDpos: null,
browserDpos: null,
});

export const TaraxaDposProvider = ({
networkIdOrName,
children,
}: {
networkIdOrName: number | string;
children: React.ReactNode;
}): JSX.Element => {
const [mainnetDpos, setMainnetDpos] = useState<ethers.Contract | null>(null);
const [browserDpos, setBrowserDpos] = useState<ethers.Contract | null>(null);

useEffect(() => {
const taraxaDposClient = new TaraxaDposClient(networkIdOrName);
setMainnetDpos(taraxaDposClient.mainnetDpos);
setBrowserDpos(taraxaDposClient.browserDpos);
}, [networkIdOrName]);

const value = useMemo(() => {
return { mainnetDpos, browserDpos };
}, [mainnetDpos, browserDpos]);

return (
<TaraxaDposContext.Provider value={value}>
{children}
</TaraxaDposContext.Provider>
);
};

export const useTaraxaDpos = (): TaraxaDposContextProps => {
return useContext(TaraxaDposContext);
};
3 changes: 3 additions & 0 deletions packages/taraxa-sdk/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
interface Window {
ethereum?: any;
}
11 changes: 10 additions & 1 deletion packages/taraxa-sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { networks } from './utils/networks';
import { NetworkName, NetworkGraphQLEndpoints } from './utils/enums';
import type { Network, Networks } from './utils/networks';
import { TaraxaDposClient } from './context/TaraxaDposClient';
import { TaraxaDposProvider, useTaraxaDpos } from './context/TaraxaDposContext';

export { networks, NetworkName, NetworkGraphQLEndpoints };
export {
networks,
NetworkName,
NetworkGraphQLEndpoints,
TaraxaDposClient,
TaraxaDposProvider,
useTaraxaDpos,
};
export type { Network, Networks };
49 changes: 28 additions & 21 deletions services/community-site/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BrowserRouter, Switch, Route, useLocation } from 'react-router-dom';
import { MetaMaskProvider } from 'metamask-react';
import { useMediaQuery } from 'react-responsive';
import { Notification, TaraxaThemeProvider } from '@taraxa_project/taraxa-ui';
import { TaraxaDposProvider } from '@taraxa_project/taraxa-sdk';

import { AuthProvider, useAuth } from './services/useAuth';
import { LoadingProvider } from './services/useLoading';
Expand Down Expand Up @@ -31,6 +32,7 @@ import './App.scss';
import { ValidatorWeeklyStatsProvider } from './services/useValidatorsWeeklyStats';
import { ValidatorsProvider } from './services/useAllValidators';
import { RedelegationProvider } from './services/useRedelegation';
import useMainnet from './services/useMainnet';

declare global {
interface Window {
Expand All @@ -40,6 +42,7 @@ declare global {

const Root = () => {
const { modal, setIsOpen, setContent, signIn } = useModal();

const auth = useAuth();
const { status, account } = useCMetamask();
const location = useLocation();
Expand Down Expand Up @@ -136,30 +139,34 @@ const Root = () => {
};

function App() {
const { chainId: mainnetChainId } = useMainnet();

return (
<MetaMaskProvider>
<GoogleReCaptchaProvider reCaptchaKey="6LdLJXAaAAAAAAipA9gQ8gpbvVs6b9Jq64Lmr9dl">
<LoadingProvider>
<AuthProvider>
<BrowserRouter>
<TaraxaThemeProvider>
<ModalProvider>
<WalletPopupProvider>
<SidebarProvider>
<ValidatorWeeklyStatsProvider>
<ValidatorsProvider>
<RedelegationProvider>
<Root />
</RedelegationProvider>
</ValidatorsProvider>
</ValidatorWeeklyStatsProvider>
</SidebarProvider>
</WalletPopupProvider>
</ModalProvider>
</TaraxaThemeProvider>
</BrowserRouter>
</AuthProvider>
</LoadingProvider>
<TaraxaDposProvider networkIdOrName={mainnetChainId}>
<LoadingProvider>
<AuthProvider>
<BrowserRouter>
<TaraxaThemeProvider>
<ModalProvider>
<WalletPopupProvider>
<SidebarProvider>
<ValidatorWeeklyStatsProvider>
<ValidatorsProvider>
<RedelegationProvider>
<Root />
</RedelegationProvider>
</ValidatorsProvider>
</ValidatorWeeklyStatsProvider>
</SidebarProvider>
</WalletPopupProvider>
</ModalProvider>
</TaraxaThemeProvider>
</BrowserRouter>
</AuthProvider>
</LoadingProvider>
</TaraxaDposProvider>
</GoogleReCaptchaProvider>
</MetaMaskProvider>
);
Expand Down
7 changes: 6 additions & 1 deletion services/community-site/src/services/useAllValidators.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useContext, createContext, useEffect } from 'react';
import { useTaraxaDpos } from '@taraxa_project/taraxa-sdk';
import { Validator } from '../interfaces/Validator';
import useValidators from './useValidators';
import useExplorerStats from './useExplorerStats';
Expand All @@ -17,6 +18,7 @@ const ValidatorsContext = createContext<Context>(initialState);
const useProvideValidators = () => {
const [allValidatorsWithStats, setAllValidatorsWithStats] = useState<Validator[]>([]);
const { getValidators } = useValidators();
const { mainnetDpos } = useTaraxaDpos();
const { updateValidatorsRank, updateValidatorsStats } = useExplorerStats();
const { startLoading, finishLoading } = useLoading();

Expand All @@ -33,8 +35,11 @@ const useProvideValidators = () => {
};

useEffect(() => {
if (!mainnetDpos) {
return;
}
fetchValidators();
}, []);
}, [mainnetDpos]);

return {
allValidatorsWithStats,
Expand Down
4 changes: 2 additions & 2 deletions services/community-site/src/services/useDelegation.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { useCallback, useMemo } from 'react';
import { ethers } from 'ethers';
import { useTaraxaDpos } from '@taraxa_project/taraxa-sdk';

import Delegation, { ContractDelegation } from '../interfaces/Delegation';
import Undelegation, { ContractUndelegation } from '../interfaces/Undelegation';

import { useLoading } from './useLoading';
import useDpos from './useDpos';

export default () => {
const { startLoading, finishLoading } = useLoading();
const { mainnetDpos, browserDpos } = useDpos();
const { mainnetDpos, browserDpos } = useTaraxaDpos();

const getDelegations = useCallback(
async (address: string): Promise<Delegation[]> => {
Expand Down
4 changes: 2 additions & 2 deletions services/community-site/src/services/useValidators.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback, useMemo } from 'react';
import { ethers } from 'ethers';
import { useTaraxaDpos } from '@taraxa_project/taraxa-sdk';

import {
ContractValidator,
Expand All @@ -8,12 +9,11 @@ import {
ValidatorType,
} from '../interfaces/Validator';
import { useLoading } from './useLoading';
import useDpos from './useDpos';

export default () => {
const { startLoading, finishLoading } = useLoading();

const { mainnetDpos, browserDpos } = useDpos();
const { mainnetDpos, browserDpos } = useTaraxaDpos();

const maxDelegation = ethers.BigNumber.from(80000000).mul(ethers.BigNumber.from(10).pow(18));
const contractToValidator = (contractValidator: ContractValidator) => ({
Expand Down