Skip to content

Commit b42ffaa

Browse files
add ability to switch networks
1 parent f6e2ef7 commit b42ffaa

File tree

7 files changed

+93
-14
lines changed

7 files changed

+93
-14
lines changed

Assets/Plugin/thirdweb.jslib

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ var plugin = {
5454
dynCall_viii(cb, idPtr, null, buffer);
5555
});
5656
},
57+
ThirdwebSwitchNetwork: async function (chainId) {
58+
await window.bridge.switchNetwork(chainId);
59+
},
5760
};
5861

5962
mergeInto(LibraryManager.library, plugin);

Assets/SDKTest.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ public async void OnLoginCLick()
2525
loginButton.text = "Connecting...";
2626
string address = await sdk.wallet.Connect();
2727
loginButton.text = "Connected as: " + address.Substring(0, 6) + "...";
28+
int chain = await sdk.wallet.GetChainId();
29+
Debug.Log("chain: " + chain);
30+
if (chain != 5) {
31+
sdk.wallet.SwitchNetwork(5);
32+
}
2833
}
2934

3035
public async void OnBalanceClick()

Assets/Scenes/SampleScene.unity

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1407,7 +1407,7 @@ MonoBehaviour:
14071407
m_PrefabInstance: {fileID: 0}
14081408
m_PrefabAsset: {fileID: 0}
14091409
m_GameObject: {fileID: 545609468}
1410-
m_Enabled: 1
1410+
m_Enabled: 0
14111411
m_EditorHideFlags: 0
14121412
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
14131413
m_Name:

Assets/TextMesh Pro/Resources/Fonts & Materials/LiberationSans SDF.asset

100755100644
Lines changed: 19 additions & 6 deletions
Large diffs are not rendered by default.

Assets/Thirdweb/Scripts/Bridge.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,16 +57,28 @@ public static async Task<string> Connect() {
5757
return result;
5858
}
5959

60+
public static void SwitchNetwork(int chainId) {
61+
ThirdwebSwitchNetwork(chainId);
62+
}
63+
6064
public static async Task<T> InvokeRoute<T>(string route, string[] body)
6165
{
6266
var msg = Utils.ToJson(new RequestMessageBody(body));
6367
string taskId = Guid.NewGuid().ToString();
6468
var task = new TaskCompletionSource<string>();
6569
taskMap[taskId] = task;
6670
ThirdwebInvoke(taskId, route, msg, jsCallback);
67-
string result = await task.Task;
68-
// Debug.LogFormat("Result from {0}: {1}", route, result);
69-
return JsonConvert.DeserializeObject<Result<T>>(result).result;
71+
try
72+
{
73+
string result = await task.Task;
74+
// Debug.LogFormat("Result from {0}: {1}", route, result);
75+
return JsonConvert.DeserializeObject<Result<T>>(result).result;
76+
}
77+
catch (Exception)
78+
{
79+
// Debug.LogFormat("Error from {0}: {1}", route, e);
80+
return default(T);
81+
}
7082
}
7183

7284
[DllImport("__Internal")]
@@ -75,5 +87,7 @@ public static async Task<T> InvokeRoute<T>(string route, string[] body)
7587
private static extern string ThirdwebInitialize(string chainOrRPC, string options);
7688
[DllImport("__Internal")]
7789
private static extern string ThirdwebConnect(string taskId, Action<string, string, string> cb);
90+
[DllImport("__Internal")]
91+
private static extern string ThirdwebSwitchNetwork(int chainId);
7892
}
7993
}

Assets/Thirdweb/Scripts/Wallet.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,26 @@ public async Task<string> GetAddress()
2727
return await Bridge.InvokeRoute<string>(getRoute("getAddress"), new string[] { });
2828
}
2929

30+
public async Task<bool> IsConnected()
31+
{
32+
return await Bridge.InvokeRoute<bool>(getRoute("isConnected"), new string[] { });
33+
}
34+
35+
public async Task<int> GetChainId()
36+
{
37+
return await Bridge.InvokeRoute<int>(getRoute("getChainId"), new string[] { });
38+
}
39+
40+
public async Task<bool> IsOnCorrectChain()
41+
{
42+
return await Bridge.InvokeRoute<bool>(getRoute("isOnCorrectChain"), new string[] { });
43+
}
44+
45+
public void SwitchNetwork(int chainId)
46+
{
47+
Bridge.SwitchNetwork(chainId);
48+
}
49+
3050
public async Task<TransactionResult> Transfer(string to, string amount, string currencyAddress = Utils.NativeTokenAddress)
3151
{
3252
return await Bridge.InvokeRoute<TransactionResult>(getRoute("transfer"), Utils.ToJsonStringArray(to, amount, currencyAddress));

Assets/WebGLTemplates/Better2020/index.html

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,17 +104,24 @@
104104
console.log("bridge.initialize", chain, options);
105105
const sdk = new ThirdwebSDK(chain, JSON.parse(options));
106106
w.thirdweb = sdk;
107-
}
107+
};
108108

109109
w.bridge.connect = async () => {
110110
if(w.ethereum) {
111111
await w.ethereum.enable
112112
const provider = new ethers.providers.Web3Provider(w.ethereum);
113113
await provider.send("eth_requestAccounts", []);
114-
const signer = provider.getSigner()
115114
if(w.thirdweb) {
116115
console.log("connecting SDK");
117-
w.thirdweb.updateSignerOrProvider(signer);
116+
w.thirdweb.updateSignerOrProvider(provider.getSigner());
117+
w.ethereum.on("accountsChanged", async (accounts) => {
118+
console.log("accountsChanged", accounts);
119+
w.thirdweb.updateSignerOrProvider(provider.getSigner());
120+
});
121+
w.ethereum.on("chainChanged", async (chain) => {
122+
console.log("chainChanged", chain);
123+
w.thirdweb.updateSignerOrProvider(provider.getSigner());
124+
});
118125
return await w.thirdweb.wallet.getAddress();
119126
} else {
120127
console.error("window.thirdweb is not defined");
@@ -124,7 +131,24 @@
124131
console.error("Please install a wallet browser extension");
125132
return null;
126133
}
127-
}
134+
};
135+
136+
w.bridge.switchNetwork = async (chainId) => {
137+
try {
138+
if (chainId) {
139+
await window.ethereum.request({
140+
method: 'wallet_switchEthereumChain',
141+
params: [{ chainId: "0x" + chainId.toString(16) }], // chainId must be in hexadecimal numbers
142+
});
143+
} else {
144+
console.error("Error switrching network");
145+
return null;
146+
}
147+
} catch (e) {
148+
console.error("Error switrching network", e);
149+
return null;
150+
}
151+
};
128152

129153
w.bridge.invoke = async (route, payload) => {
130154
const routeArgs = route.split(".")

0 commit comments

Comments
 (0)