How to Trigger a Network Change on OP_WALLET
OP_WALLET allows developers to programmatically request a network change through the switchNetwork
method. This is useful for ensuring that users are on the correct network for specific operations, such as interacting with smart contracts or sending transactions.
Method
switchNetwork(network: UnisatNetwork): Promise<void>;
-
Parameters:
network: UnisatNetwork
: The network to switch to (testnet
,mainnet
, orregtest
).
Example Code
import { UnisatNetwork } from "@btc-vision/transaction";
await opnet.switchNetwork(UnisatNetwork.regtest);
console.log("Network switched to regtest.");
tip
Use getNetwork()
to check the current network before requesting a change:
const currentNetwork = await opnet.getNetwork();
if (currentNetwork !== UnisatNetwork.regtest) {
await opnet.switchNetwork(UnisatNetwork.regtest);
}
Best Practices
- Notify users when a network switch is requested and completed.
- If the network switch fails (e.g., unsupported network), display an appropriate error message to the user.
What’s Next?
- Learn how to Listen for Network Changes
- Explore how to Request Accounts from OP_WALLET