From e390bce5456cf3eeb3ff469c2ea9ca7520b35664 Mon Sep 17 00:00:00 2001 From: brusher_ru Date: Tue, 25 Jun 2024 18:17:12 +0300 Subject: [PATCH] feat: add default networks --- src/store/useNetworks.ts | 28 ++++++++++++++++++++++++++-- src/utils/defaultNetworks.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 src/utils/defaultNetworks.ts diff --git a/src/store/useNetworks.ts b/src/store/useNetworks.ts index d9cebd8..26fe98e 100644 --- a/src/store/useNetworks.ts +++ b/src/store/useNetworks.ts @@ -4,6 +4,7 @@ import { createJSONStorage, persist } from 'zustand/middleware'; import { A, O, pipe } from '@mobily/ts-belt'; import { Network } from '../types/networks'; +import DEFAULT_NETWORKS from '../utils/defaultNetworks'; type NetworkState = { selectedIndex: null | number; @@ -25,8 +26,8 @@ const NETWORKS_STORE_KEY = 'networks'; const useNetworks = create( persist( (set, get) => ({ - selectedIndex: null, - networks: [], + selectedIndex: 0, + networks: [...DEFAULT_NETWORKS], // Actions addNetwork: (net: Network) => { const state = get(); @@ -37,6 +38,9 @@ const useNetworks = create( set(newState); if (state.selectedIndex === null) { set({ selectedIndex: 0 }); + } else { + const i = newState.networks.findIndex((n) => n === net); + set({ selectedIndex: i }); } }, switchNetwork: (idx: number) => { @@ -62,6 +66,26 @@ const useNetworks = create( { name: NETWORKS_STORE_KEY, storage: createJSONStorage(() => localStorage), + partialize: (state) => ({ + ...state, + networks: state.networks.filter((n) => !DEFAULT_NETWORKS.includes(n)), + }), + merge: (persisted, current) => { + const persistedNetworks = + persisted && + Object.hasOwn(persisted, 'networks') && + (persisted as NetworkState).networks instanceof Array + ? (persisted as NetworkState).networks + : []; + return { + ...current, + ...(persisted || {}), + networks: [ + ...DEFAULT_NETWORKS, + ...persistedNetworks.filter((n) => !DEFAULT_NETWORKS.includes(n)), + ], + }; + }, } ) ); diff --git a/src/utils/defaultNetworks.ts b/src/utils/defaultNetworks.ts new file mode 100644 index 0000000..71ab6a8 --- /dev/null +++ b/src/utils/defaultNetworks.ts @@ -0,0 +1,26 @@ +import { Network } from '../types/networks'; + +const DEFAULT_NETWORKS: Network[] = [ + { + name: 'MainNet', + jsonRPC: 'https://wallet-api.spacemesh.network', + explorerUrl: 'https://explorer.spacemesh.io', + hrp: 'sm', + genesisID: '9eebff023abb17ccb775c602daade8ed708f0a50', + genesisTime: 1689310800000, + layerDuration: 300, + layersPerEpoch: 4032, + }, + { + name: 'TestNet 13', + jsonRPC: 'https://testnet-13-api.spacemesh.network', + explorerUrl: 'https://testnet-13-explorer.spacemesh.network', + hrp: 'stest', + genesisID: 'cd97832ec3ae9851e6277d8bd88bc17b4508e2b2', + genesisTime: 1718964000000, + layerDuration: 300, + layersPerEpoch: 288, + }, +]; + +export default DEFAULT_NETWORKS;