Skip to content
This repository has been archived by the owner on Feb 21, 2024. It is now read-only.

Commit

Permalink
Add: switchChain metamask helper
Browse files Browse the repository at this point in the history
  • Loading branch information
rdig committed Nov 30, 2021
1 parent 71029c6 commit fb07e4c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/@purser/metamask/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { hexlify, hexStripZeros } from 'ethers/utils';

import { helpers as messages } from './messages';

import {
Expand Down Expand Up @@ -140,3 +142,15 @@ export const setStateEventObserver = (
const { ethereum } = anyGlobal;
ethereum.on(observableEvent, callback);
};

export const switchChain = async (chainId: number): Promise<void> => {
const { ethereum } = anyGlobal;
return ethereum.request({
method: EthereumRequestMethods.SwitchChain,
/*
* @NOTE Need to also strip zeros since `hexlify` returns a signed hex string
* which is not something Metamask likes as a chain Id
*/
params: [{ chainId: hexStripZeros(hexlify(chainId)) }],
});
};
2 changes: 2 additions & 0 deletions packages/@purser/metamask/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,6 @@ export enum EthereumRequestMethods {
Accounts = 'eth_accounts',
RequestAccounts = 'eth_requestAccounts',
WalletPermissions = 'wallet_getPermissions',
SwitchChain = 'wallet_switchEthereumChain',
AddNewChain = 'wallet_addEthereumChain',
}

0 comments on commit fb07e4c

Please sign in to comment.