Skip to content

Commit

Permalink
feat(dw): create client based on active network
Browse files Browse the repository at this point in the history
  • Loading branch information
javadkh2 committed Oct 10, 2024
1 parent f2b55c2 commit 7104e27
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 27 deletions.
59 changes: 59 additions & 0 deletions packages/apps/dev-wallet/src/modules/network/network.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { getHostUrl, INetworkOptions } from '@kadena/client';
import { INetwork } from './network.repository';

export const fetchNetworkId = async (host: string) =>
fetch(host.endsWith('/') ? `${host}info` : `${host}/info`)
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Network is not healthy');
})
.then((data) => {
return data.nodeVersion;
})
.catch(() => {
return undefined;
});

export const hostUrlGenerator = (networks: INetwork[]) => {
let healthyNetworks = networks;
let lastCheckTime = Date.now();
const checkNetworks = async () => {
lastCheckTime = Date.now();
healthyNetworks = await Promise.all(
networks.map(async (network) => {
const hosts = await Promise.all(
network.hosts.map(async (host) => {
const nodeVersion = await fetchNetworkId(host.url);
return {
...host,
isHealthy: nodeVersion !== network.networkId,
checkTime: Date.now(),
};
}),
);
return {
...network,
hosts: hosts.filter((host) => host.isHealthy),
};
}),
);
};
checkNetworks();
return ({ networkId, chainId }: INetworkOptions) => {
if (Date.now() - lastCheckTime > 30000) {
checkNetworks();
}
const network = healthyNetworks.find(
(network) => network.networkId === networkId,
);
const host = network?.hosts.find(
(host) => host.submit && host.read && host.confirm,
);
if (!host) {
throw new Error('No healthy host found');
}
return getHostUrl(host.url)({ networkId, chainId });
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export const useWallet = () => {
keysets: context.keysets || [],
keySources: context.keySources || [],
fungibles: context.fungibles || [],
client: context.client,
syncAllAccounts: () => (syncAllAccounts ? syncAllAccounts() : undefined),
};
};
21 changes: 21 additions & 0 deletions packages/apps/dev-wallet/src/modules/wallet/wallet.provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {

import { useSession } from '@/App/session';
import { throttle } from '@/utils/session';
import { IClient, createClient } from '@kadena/client';
import { setGlobalConfig } from '@kadena/client-utils';
import {
Fungible,
IAccount,
Expand All @@ -19,6 +21,7 @@ import * as AccountService from '../account/account.service';
import { dbService } from '../db/db.service';
import { keySourceManager } from '../key-source/key-source-manager';
import { INetwork, networkRepository } from '../network/network.repository';
import { hostUrlGenerator } from '../network/network.service';
import { IKeySource, IProfile, walletRepository } from './wallet.repository';

export type ExtWalletContextType = {
Expand All @@ -31,6 +34,7 @@ export type ExtWalletContextType = {
loaded?: boolean;
activeNetwork?: INetwork | undefined;
networks: INetwork[];
client: IClient;
};

export const WalletContext = createContext<
Expand All @@ -52,6 +56,7 @@ export const syncAllAccounts = throttle(AccountService.syncAllAccounts, 10000);
export const WalletProvider: FC<PropsWithChildren> = ({ children }) => {
const [contextValue, setContextValue] = useState<ExtWalletContextType>({
networks: [],
client: createClient(),
});
const session = useSession();

Expand Down Expand Up @@ -270,6 +275,22 @@ export const WalletProvider: FC<PropsWithChildren> = ({ children }) => {
}
}, [retrieveAccounts, contextValue.profile?.uuid]);

useEffect(() => {
// filter network if the id is the same but the name is different
const filteredNetworks = contextValue.networks.filter((network) => {
if (!contextValue.activeNetwork) return true;
return (
network.networkId !== contextValue.activeNetwork.networkId ||
network.name === contextValue.activeNetwork.name
);
});
const getHostUrl = hostUrlGenerator(filteredNetworks);
setGlobalConfig({
host: getHostUrl,
});
setContextValue((ctx) => ({ ...ctx, client: createClient(getHostUrl) }));
}, [contextValue.networks, contextValue.activeNetwork]);

return (
<WalletContext.Provider
value={[contextValue, setProfile, setActiveNetwork, syncAllAccountsCb]}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { INetwork } from '@/modules/network/network.repository';
import { fetchNetworkId } from '@/modules/network/network.service';
import { Label } from '@/pages/transaction/components/helpers';
import {
failureClass,
Expand Down Expand Up @@ -31,21 +32,6 @@ interface INewNetwork {
}[];
}

const fetchNetworkId = async (host: string) =>
fetch(host.endsWith('/') ? `${host}info` : `${host}/info`)
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Network is not healthy');
})
.then((data) => {
return data.nodeVersion;
})
.catch(() => {
return undefined;
});

export function NetworkForm({
network,
onSave: onDone,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '@/modules/transaction/transaction.repository';
import { useWallet } from '@/modules/wallet/wallet.hook';
import { shorten } from '@/utils/helpers';
import { ICommand, IUnsignedCommand, createClient } from '@kadena/client';
import { ICommand, IUnsignedCommand } from '@kadena/client';
import { MonoBrightness1 } from '@kadena/kode-icons/system';
import {
Button,
Expand Down Expand Up @@ -57,7 +57,7 @@ export function Transaction({ groupId }: { groupId?: string }) {
const [error, setError] = useState<string | null>(null);
const [viewStep, setViewStep] = useState<'transaction' | 'result'>('result');
const navigate = useNavigate();
const { sign } = useWallet();
const { sign, client } = useWallet();

const loadTxs = useCallback(async (groupId: string) => {
const list = await transactionRepository.getTransactionsByGroup(groupId);
Expand Down Expand Up @@ -91,7 +91,6 @@ export function Transaction({ groupId }: { groupId?: string }) {
const submitTxs = useCallback(
async (list: ITransaction[]) => {
if (!groupId) return;
const client = createClient();
if (!list.every(isSignedCommand)) return;
const preflightValidation = await Promise.all(
list.map((tx) =>
Expand Down Expand Up @@ -147,7 +146,6 @@ export function Transaction({ groupId }: { groupId?: string }) {
useEffect(() => {
async function run() {
if (step === 'submitted' && groupId) {
const client = createClient();
const listForSubmission = await loadTxs(groupId);
await Promise.all(
listForSubmission.map((tx) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,7 @@ import {
import { Button, Dialog, Stack, Text } from '@kadena/kode-ui';

import { useWallet } from '@/modules/wallet/wallet.hook';
import {
ICommand,
IUnsignedCommand,
createClient,
createTransaction,
} from '@kadena/client';
import { ICommand, IUnsignedCommand, createTransaction } from '@kadena/client';
import {
composePactCommand,
continuation,
Expand Down Expand Up @@ -41,7 +36,7 @@ export function TxList({
const [selectedTxIndex, setSelectedTxIndex] = React.useState<
number | undefined
>(undefined);
const { sign } = useWallet();
const { sign, client } = useWallet();
const signAll = async () => {
const signed = (await sign(txs)) as (IUnsignedCommand | ICommand)[];

Expand Down Expand Up @@ -79,7 +74,6 @@ export function TxList({
};

const onSubmit = async (tx: ITransaction) => {
const client = createClient();
let updatedTx = await client
.preflight({
cmd: tx.cmd,
Expand Down

0 comments on commit 7104e27

Please sign in to comment.