import { atom } from 'jotai' ; import { atomWithStorage } from 'jotai/utils' ; import { defaultNetworks , Networks } from '@shared/constants' ; import { findMatchingNetworkKey } from '@app/common/utils' ; import { StacksMainnet , StacksNetwork , StacksTestnet } from '@stacks/network' ; import { ChainID } from '@stacks/transactions' ; import { transactionRequestNetwork } from '@app/store/transactions/requests' ; import { makeLocalDataKey } from '@app/common/store-utils' ; import { whenChainId } from '@app/common/transactions/transaction-utils' ; export const networksState = atomWithStorage < Networks > ( makeLocalDataKey ( 'networks' ) , defaultNetworks ) ; const localCurrentNetworkKeyState = atomWithStorage ( makeLocalDataKey ( 'networkKey' ) , 'mainnet' ) ; export const currentNetworkKeyState = atom < string , string > ( get => { const networks = get ( networksState ) ; const txNetwork = get ( transactionRequestNetwork ) ; if ( txNetwork ) { const newKey = findMatchingNetworkKey ( txNetwork , networks ) ; if ( newKey ) return newKey ; } return get ( localCurrentNetworkKeyState ) ; } , ( _get , set , update ) => { if ( update ) set ( localCurrentNetworkKeyState , update ) ; } ) ; export const currentNetworkState = atom ( get => get ( networksState ) [ get ( currentNetworkKeyState ) ] ) ; export const currentStacksNetworkState = atom < StacksNetwork > ( get => { const network = get ( currentNetworkState ) ; const stacksNetwork = whenChainId ( network . chainId ) ( { [ ChainID . Mainnet ] : new StacksMainnet ( { url : network . url } ) , [ ChainID . Testnet ] : new StacksTestnet ( { url : network . url } ) , } ) ; stacksNetwork . bnsLookupUrl = network . url ; return stacksNetwork ; } ) ; networksState . debugLabel = 'networksState' ; localCurrentNetworkKeyState . debugLabel = 'localCurrentNetworkKeyState' ; currentNetworkKeyState . debugLabel = 'currentNetworkKeyState' ; currentNetworkState . debugLabel = 'currentNetworkState' ; currentStacksNetworkState . debugLabel = 'currentStacksNetworkState' ;