From d714cf3c8ca30b4372b6b138305f227a14f24506 Mon Sep 17 00:00:00 2001 From: Nikaru Date: Sat, 23 Nov 2024 13:29:52 +0000 Subject: [PATCH] feat: add chain change subscribe to evm namespace --- wallets/core/src/namespaces/evm/actions.ts | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/wallets/core/src/namespaces/evm/actions.ts b/wallets/core/src/namespaces/evm/actions.ts index 6156f77e8..076b8e58d 100644 --- a/wallets/core/src/namespaces/evm/actions.ts +++ b/wallets/core/src/namespaces/evm/actions.ts @@ -95,3 +95,35 @@ export function changeAccountSubscriber( }, ]; } + +export function changeChainSubscriber( + instance: () => ProviderAPI +): [Subscriber, SubscriberCleanUp] { + let eventCallback: EIP1193EventMap['chainChanged']; + + return [ + (context) => { + const evmInstance = instance(); + + if (!evmInstance) { + throw new Error( + 'Trying to subscribe to your EVM wallet, but seems its instance is not available.' + ); + } + + const [, setState] = context.state(); + + eventCallback = async (chainId: string) => { + setState('network', chainId); + }; + evmInstance.on('chainChanged', eventCallback); + }, + () => { + const evmInstance = instance(); + + if (eventCallback && evmInstance) { + evmInstance.removeListener('chainChanged', eventCallback); + } + }, + ]; +}