Switch Network
Once you have your basic dev environment set up, you are ready to start interacting with some smart contracts. There are some basic things you'll need, regardless of what convenience library you're using, when communicating with a smart contract:
The Contract Network
If you aren't connected to the right network, you aren't going to have any luck sending transactions to your contract, so make sure you have this right! Many dapp developers choose to deploy their contract to a testnet
first, in order to avoid potentially disastrous fees if something goes wrong during development and testing
on mainnet
.
export default () => {
const [network, setNetwork] = useState("");
useEffect(() => {
const provider = window.ton ?? {};
if (!provider.isOpenMask) return;
// Initial chainId value
provider.send("wallet_getChain").then((chainId) => setNetwork(chainId));
// Subscribe to change network
provider.on("chainChanged", setNetwork);
return () => {
// Unsubscribe
provider.off("chainChanged", setNetwork);
};
}, []);
return (
<div>
<div>{network ?? "OpenMask not detected"}</div>
</div>
);
};
Please try to change netwrok in the header of your OpenMask extesion:
Request to change network from dApp
No matter which network you deploy your final dapp on, your user will need to be able to access it. OpenMask makes available wallet_switchChain
, which allows you to prompt the user to add a chain that you suggest, and switch to it using a confirmation dialogue.
export default () => {
const [network, setNetwork] = useState("");
const switchNetwork = async () => {
const provider = window.ton ?? {};
if (!provider?.isOpenMask) return;
const next = network === "mainnet" ? "testnet" : "mainnet";
try {
await provider.send("wallet_switchChain", next);
setNetwork(next);
} catch (e) {
console.error(e);
}
};
useEffect(() => {
const provider = window.ton ?? {};
if (!provider?.isOpenMask) return;
// Initial chainId value
provider.send("wallet_getChain").then((chainId) => setNetwork(chainId));
}, []);
return (
<div>
<button onClick={switchNetwork}>
Switch network
</button>
<div>{network ?? "OpenMask not detected"}</div>
</div>
);
};