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

Commit

Permalink
Add: addChain metamask helper
Browse files Browse the repository at this point in the history
  • Loading branch information
rdig committed Nov 30, 2021
1 parent fb07e4c commit fb562a1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/@purser/metamask/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ObservableEvents,
MetamaskEthereumGlobal,
EthereumRequestMethods,
EthereumChain,
} from './types';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -154,3 +155,33 @@ export const switchChain = async (chainId: number): Promise<void> => {
params: [{ chainId: hexStripZeros(hexlify(chainId)) }],
});
};

export const addChain = async (chainDetails: EthereumChain): Promise<void> => {
const { ethereum } = anyGlobal;
const {
chainId,
chainName,
nativeCurrency = {},
rpcUrls,
blockExplorerUrls,
} = chainDetails;
return ethereum.request({
method: EthereumRequestMethods.AddNewChain,
params: [
{
/*
* @NOTE Need to also strip zeros since `hexlify` returns a signed hex string
* which is not something Metamask likes as a chain Id
*/
chainId: hexStripZeros(hexlify(chainId)),
chainName,
nativeCurrency: {
decimals: 18,
...nativeCurrency,
},
rpcUrls,
blockExplorerUrls,
},
],
});
};
14 changes: 14 additions & 0 deletions packages/@purser/metamask/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ interface EthereumRequestArguments {
params?: unknown[] | object;
}

export interface EthereumNativeToken {
name: string;
symbol: string; // 2-6 characters long
decimals?: number;
}

export interface EthereumChain {
chainId: number;
chainName: string;
nativeCurrency: EthereumNativeToken;
rpcUrls: string[];
blockExplorerUrls?: string[];
}

export interface MetamaskEthereumGlobal {
isConnected: () => boolean;
request<R>(args: EthereumRequestArguments): Promise<R>;
Expand Down

0 comments on commit fb562a1

Please sign in to comment.