Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom chains in changeNetwork function #425

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
35 changes: 33 additions & 2 deletions apps/nextjs-example/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from "@aptos-labs/wallet-adapter-react";
import { AlertCircle } from "lucide-react";
import Image from "next/image";
import { useState } from "react";

// Imports for registering a browser extension wallet plugin on page load
import { MyWallet } from "@/utils/standardWallet";
Expand Down Expand Up @@ -144,7 +145,7 @@ interface WalletConnectionProps {
account: AccountInfo | null;
network: NetworkInfo | null;
wallet: WalletInfo | null;
changeNetwork: (network: Network) => Promise<AptosChangeNetworkOutput>;
changeNetwork: (network: Network, chainId?: number) => Promise<AptosChangeNetworkOutput>;
}

function WalletConnection({
Expand All @@ -162,6 +163,8 @@ function WalletConnection({
return true;
};

const [customChainId, setCustomChainId] = useState<number | "">("");

// TODO: Do a proper check for network change support
const isNetworkChangeSupported = wallet?.name === "Nightly";

Expand Down Expand Up @@ -292,7 +295,17 @@ function WalletConnection({
value={network?.name}
orientation="horizontal"
className="flex gap-6"
onValueChange={(value: Network) => changeNetwork(value)}
onValueChange={(value: Network) => {
if (value === Network.CUSTOM && customChainId && Number(customChainId) > 0) {
changeNetwork(value, Number(customChainId));
} else if (value !== Network.CUSTOM) {
changeNetwork(value);
} else {
console.warn("Invalid chainId");
}
}}


disabled={!isNetworkChangeSupported}
>
<div className="flex items-center space-x-2">
Expand All @@ -307,6 +320,24 @@ function WalletConnection({
<RadioGroupItem value={Network.MAINNET} id="mainnet-radio" />
<Label htmlFor="mainnet-radio">Mainnet</Label>
</div>

<div className="flex items-center space-x-2">
<RadioGroupItem
value={Network.CUSTOM}
id="custom-radio"
disabled={!customChainId || Number(customChainId) <= 0}
/>

<Label htmlFor="custom-radio">Custom</Label>

<input
type="number"
className="ml-2 border rounded px-2 py-1"
value={customChainId}
onChange={(e) => setCustomChainId(e.target.value ? Number(e.target.value) : "")}
placeholder="Enter chainId"
/>
</div>
</RadioGroup>
{!isNetworkChangeSupported && (
<div className="text-sm text-red-600 dark:text-red-400">
Expand Down
8 changes: 6 additions & 2 deletions packages/wallet-adapter-core/src/WalletCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1161,17 +1161,21 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
* @param network
* @returns AptosChangeNetworkOutput
*/
async changeNetwork(network: Network): Promise<AptosChangeNetworkOutput> {
async changeNetwork(
network: Network,
customChainId?: number
): Promise<AptosChangeNetworkOutput> {
try {
this.ensureWalletExists(this._wallet);
this.recordEvent("change_network_request", {
from: this._network?.name,
to: network,
});

const chainId =
network === Network.DEVNET
? await fetchDevnetChainId()
: NetworkToChainId[network];
: (network === Network.CUSTOM && customChainId) ? customChainId : NetworkToChainId[network];
if (this._wallet.changeNetwork) {
const networkInfo: StandardNetworkInfo = {
name: network,
Expand Down
9 changes: 6 additions & 3 deletions packages/wallet-adapter-react/src/WalletProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,21 @@ export const AptosWalletAdapterProvider: FC<AptosWalletProviderProps> = ({
}
};

const changeNetwork = async (network: Network) => {
const changeNetwork = async (network: Network, chainId?: number) => {
if (!walletCore) {
throw new Error("WalletCore is not initialized");
}

try {
return await walletCore?.changeNetwork(network);
return chainId !== undefined
arjanjohan marked this conversation as resolved.
Show resolved Hide resolved
? await walletCore.changeNetwork(network, chainId)
: await walletCore.changeNetwork(network);
} catch (error: any) {
if (onError) onError(error);
return Promise.reject(error);
}
};

useEffect(() => {
if (autoConnect) {
if (localStorage.getItem("AptosWalletName") && !connected) {
Expand Down
2 changes: 1 addition & 1 deletion packages/wallet-adapter-react/src/useWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export interface WalletContextState {
): Promise<PendingTransactionResponse>;
signMessage(message: SignMessagePayload): Promise<SignMessageResponse>;
signMessageAndVerify(message: SignMessagePayload): Promise<boolean>;
changeNetwork(network: Network): Promise<AptosChangeNetworkOutput>;
changeNetwork(network: Network, chainId?: number): Promise<AptosChangeNetworkOutput>;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets let the user pass in the chainId as a string, and have the adapter do the parsing before sending it to the wallet

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know in the example used in this repo, the chainId is provided in an input field and using string would make sense. However, I believe this to be an exceptional case. I imagina all dApps that will utilize this feature will handle the logic in the backend, and the chainId is not provided by the user but rather from some backend storage where it's stored as number.

Let me know what you think.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I'd argue that they will be retrieving it from an API query, where it will mostly be in a string format. Instead of requiring the dapp to convert it to a number, the adapter can handle that conversion for them.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense, thanks for clarifying. I will modify it and push the changes.

}

const DEFAULT_CONTEXT = {
Expand Down
9 changes: 6 additions & 3 deletions packages/wallet-adapter-vue/src/composables/useWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export interface WalletContextState {
): Promise<PendingTransactionResponse>;
signMessage(message: SignMessagePayload): Promise<SignMessageResponse>;
signMessageAndVerify(message: SignMessagePayload): Promise<boolean>;
changeNetwork(network: Network): Promise<AptosChangeNetworkOutput>;
changeNetwork(network: Network, chainId?: number): Promise<AptosChangeNetworkOutput>;
}

export interface AptosWalletProviderProps {
Expand Down Expand Up @@ -197,9 +197,12 @@ export function useWallet(
}
};

const changeNetwork = async (network: Network) => {
const changeNetwork = async (network: Network, chainId?: number) => {
try {
return await walletCoreInstance.changeNetwork(network);
// Call changeNetwork with chainId if provided, otherwise call without it
return chainId !== undefined
? await walletCoreInstance.changeNetwork(network, chainId)
: await walletCoreInstance.changeNetwork(network);
arjanjohan marked this conversation as resolved.
Show resolved Hide resolved
} catch (error: any) {
if (onError) onError(error);
return Promise.reject(error);
Expand Down