Skip to content

Commit 9939c02

Browse files
authored
Now the default behaviour for switching the chain is actually to try to add it, if it already exists, we're getting a prompt to switch to it. (#1250)
* Now the default behaviour for switching the chain is actually to try to add it, if it already exists, we're getting a prompt to switch to it. * Removed unnecessary chain declaration * Naming conventions and default values. * Addressed Oleks comments * Creating the directory if it doesn't exist * Removed return * Updated dependencies
1 parent 588f439 commit 9939c02

File tree

42 files changed

+246
-83
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+246
-83
lines changed
Binary file not shown.

Packages/io.chainsafe.web3-unity.web3auth/Runtime/WalletGUI/Scripts/Web3AuthWalletGUITokenManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ private async void SetTokens()
8383
customTokenDisplay.SetActive(false);
8484
}
8585
// Set native token
86-
nativeTokenSymbolText.text = Web3Unity.Web3.ChainConfig.Symbol.ToUpper();
86+
nativeTokenSymbolText.text = Web3Unity.Web3.ChainConfig.NativeCurrency.Symbol.ToUpper();
8787
var hexBalance = await Web3Unity.Web3.RpcProvider.GetBalance(Web3Unity.Web3.Signer.PublicAddress);
8888
var weiBalance = BigInteger.Parse(hexBalance.ToString());
8989
decimal ethBalance = (decimal)weiBalance / (decimal)Math.Pow(10, 18);

Packages/io.chainsafe.web3-unity.web3auth/Runtime/Web3AuthConnectionProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public override async Task Initialize(bool rememberSession)
9292

9393
//1155 is a decimal number, we need to convert it to an integer
9494
InitWeb3Auth(clientId, new HexBigInteger(BigInteger.Parse(chainConfig.ChainId)).HexValue,
95-
chainConfig.Rpc, chainConfig.Network, "", chainConfig.Symbol, "", network.ToString().ToLower(), Initialized, InitializeError);
95+
chainConfig.Rpc, chainConfig.Network, "", chainConfig.NativeCurrency.Symbol, "", network.ToString().ToLower(), Initialized, InitializeError);
9696

9797
await _initializeTcs.Task;
9898
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using UnityEditor;
2+
using UnityEngine;
3+
using System.IO;
4+
5+
public class OpenPersistentDataPath
6+
{
7+
[MenuItem("Edit/Open Persistent Data Path")]
8+
private static void OpenPersistentDataPathFolder()
9+
{
10+
string path = Application.persistentDataPath;
11+
12+
// Check if the directory exists
13+
if (!Directory.Exists(path))
14+
{
15+
Directory.CreateDirectory(path);
16+
}
17+
18+
// Open the folder in the file explorer
19+
EditorUtility.RevealInFinder(path);
20+
}
21+
}

Packages/io.chainsafe.web3-unity/Editor/OpenPersistenDataPath.cs.meta

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.ChainSettings.cs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
using System;
22
using System.Linq;
33
using ChainSafe.Gaming;
4+
using ChainSafe.Gaming.Web3;
45
using UnityEditor;
56
using UnityEditor.Experimental.GraphView;
67
using UnityEngine;
8+
using NativeCurrency = ChainSafe.Gaming.Web3.NativeCurrency;
79

810
namespace ChainSafe.GamingSdk.Editor
911
{
@@ -85,7 +87,13 @@ public void OnGUI()
8587

8688
chainConfig.Network = EditorGUILayout.TextField("Network", chainConfig.Network);
8789
chainConfig.ChainId = EditorGUILayout.TextField("Chain ID", chainConfig.ChainId);
88-
chainConfig.Symbol = EditorGUILayout.TextField("Symbol", chainConfig.Symbol);
90+
EditorGUILayout.LabelField("Native Currency", EditorStyles.boldLabel);
91+
EditorGUI.indentLevel++;
92+
// Draw fields for NativeCurrency
93+
chainConfig.NativeCurrency.Name = EditorGUILayout.TextField("Name", chainConfig.NativeCurrency.Name);
94+
chainConfig.NativeCurrency.Symbol = EditorGUILayout.TextField("Symbol", chainConfig.NativeCurrency.Symbol);
95+
chainConfig.NativeCurrency.Decimals = EditorGUILayout.IntField("Decimals", chainConfig.NativeCurrency.Decimals);
96+
EditorGUI.indentLevel--;
8997
chainConfig.BlockExplorerUrl = EditorGUILayout.TextField("Block Explorer", chainConfig.BlockExplorerUrl);
9098

9199
GUI.enabled = true;
@@ -195,7 +203,12 @@ private void UpdateServerMenuInfo(bool chainSwitched = false)
195203
{
196204
chainConfig.Network = chainPrototype.chain;
197205
chainConfig.ChainId = chainPrototype.chainId.ToString();
198-
chainConfig.Symbol = chainPrototype.nativeCurrency.symbol;
206+
chainConfig.NativeCurrency = new NativeCurrency()
207+
{
208+
Name = chainPrototype.nativeCurrency.Name,
209+
Symbol = chainPrototype.nativeCurrency.Symbol,
210+
Decimals = chainPrototype.nativeCurrency.Decimals
211+
};
199212
if (chainPrototype.explorers != null)
200213
{
201214
chainConfig.BlockExplorerUrl = chainPrototype.explorers[0].url;
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Packages/io.chainsafe.web3-unity/Runtime/Scripts/ChainConfigEntry.cs

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using ChainSafe.Gaming.Web3;
3+
using ChainSafe.Gaming.Web3.Core.Chains;
34
using UnityEngine;
45

56
namespace ChainSafe.Gaming
@@ -10,13 +11,32 @@ public class ChainConfigEntry : IChainConfig
1011
private const string ChainIdDefault = "11155111";
1112
private const string ChainDefault = "Sepolia";
1213
private const string NetworkDefault = "Sepolia";
13-
private const string SymbolDefault = "Seth";
14+
15+
private static readonly NativeCurrencyUnityWrapper DefaultNativeCurrency = new()
16+
{
17+
Name = "Sepolia Ether",
18+
Symbol = "ETH",
19+
Decimals = 18
20+
};
21+
1422
private const string RpcDefault = "https://rpc.sepolia.org";
1523
private const string BlockExplorerUrlDefault = "https://sepolia.etherscan.io";
1624
private const string WsDefault = "";
1725

1826
[field: SerializeField] public string ChainId { get; set; }
19-
[field: SerializeField] public string Symbol { get; set; }
27+
28+
public INativeCurrency NativeCurrency
29+
{
30+
get => nativeCurrency;
31+
set => nativeCurrency = new NativeCurrencyUnityWrapper()
32+
{
33+
Name = value.Name,
34+
Symbol = value.Symbol,
35+
Decimals = value.Decimals
36+
};
37+
}
38+
39+
[SerializeField] private NativeCurrencyUnityWrapper nativeCurrency ;
2040
[field: SerializeField] public string Chain { get; set; }
2141
[field: SerializeField] public string Network { get; set; }
2242
[field: SerializeField] public string Rpc { get; set; }
@@ -26,7 +46,7 @@ public class ChainConfigEntry : IChainConfig
2646
public static ChainConfigEntry Default => new()
2747
{
2848
ChainId = ChainIdDefault,
29-
Symbol = SymbolDefault,
49+
NativeCurrency = DefaultNativeCurrency,
3050
Chain = ChainDefault,
3151
Network = NetworkDefault,
3252
Rpc = RpcDefault,
@@ -37,12 +57,23 @@ public class ChainConfigEntry : IChainConfig
3757
public static ChainConfigEntry Empty => new()
3858
{
3959
ChainId = string.Empty,
40-
Symbol = string.Empty,
60+
NativeCurrency = new NativeCurrencyUnityWrapper(),
4161
Chain = "Custom",
4262
Network = string.Empty,
4363
Rpc = string.Empty,
4464
BlockExplorerUrl = string.Empty,
4565
Ws = string.Empty
4666
};
4767
}
68+
69+
/// <summary>
70+
/// This is basically a wrapper for the INativeCurrency interface to allow for Unity serialization.
71+
/// </summary>
72+
[Serializable]
73+
public class NativeCurrencyUnityWrapper : INativeCurrency
74+
{
75+
[field: SerializeField] public string Name { get; set; } = "Ether";
76+
[field: SerializeField] public string Symbol { get; set; } = "ETH";
77+
[field: SerializeField] public int Decimals { get; set; } = 18;
78+
}
4879
}

Packages/io.chainsafe.web3-unity/Runtime/Scripts/Model/ChainInfoModel.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
using System.Collections.Generic;
2+
using Newtonsoft.Json;
23

34
namespace ChainSafe.Gaming.UnityPackage.Model
45
{
56
public struct NativeCurrency
67
{
7-
public string symbol { get; set; }
8+
[JsonProperty(PropertyName = "symbol")]
9+
public string Symbol { get; set; }
10+
11+
[JsonProperty(PropertyName = "decimals")]
12+
public int Decimals { get; set; }
13+
[JsonProperty(PropertyName = "name")]
14+
public string Name { get; set; }
815
}
916

1017
public struct Explorer

Packages/io.chainsafe.web3-unity/Runtime/Scripts/ProjectConfigUtilities.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Collections.Generic;
22
using System.IO;
33
using ChainSafe.Gaming.Web3;
4+
using ChainSafe.Gaming.Web3.Core.Chains;
45
using UnityEngine;
56

67
namespace ChainSafe.Gaming.UnityPackage
@@ -39,7 +40,12 @@ public static Web3ConfigAsset Create(string projectId, string chainId, string ch
3940
ChainId = chainId,
4041
Chain = chain,
4142
Network = network,
42-
Symbol = symbol,
43+
NativeCurrency = new NativeCurrencyUnityWrapper()
44+
{
45+
Name = symbol,
46+
Symbol = symbol,
47+
Decimals = 18
48+
},
4349
Rpc = rpc,
4450
Ws = ws,
4551
BlockExplorerUrl = blockExplorerUrl,
@@ -91,7 +97,7 @@ public LocalhostChainConfig(string chainId, string symbol, string chain, string
9197
var localhostEndPoint = $"127.0.0.1:{port}";
9298

9399
ChainId = chainId;
94-
Symbol = symbol;
100+
NativeCurrency = new NativeCurrencyUnityWrapper(){ Symbol = symbol, Name = symbol, Decimals = 18 };
95101
Chain = chain;
96102
Network = network;
97103
Rpc = $"http://{localhostEndPoint}";
@@ -100,7 +106,7 @@ public LocalhostChainConfig(string chainId, string symbol, string chain, string
100106
}
101107

102108
public string ChainId { get; }
103-
public string Symbol { get; }
109+
public INativeCurrency NativeCurrency { get; }
104110
public string Chain { get; }
105111
public string Network { get; }
106112
public string Rpc { get; }

scripts/lint.bat

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,5 @@ cd ..
88
:: Run format command in project root
99
dotnet format --verbosity=d --severity=warn ChainSafe.Gaming.sln --exclude /submodules
1010

11-
:: Navigate to the UnitySampleProject within src and run the format command
12-
pushd .\src\UnitySampleProject
13-
dotnet format --verbosity=d --severity=warn .\UnitySampleProject.sln
14-
popd
15-
1611
:: Restore the original directory
1712
popd
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using System.Collections.Generic;
2+
using ChainSafe.Gaming.Evm.Network;
3+
using Reown.Core.Common.Utils;
4+
using Reown.Core.Network.Models;
5+
6+
namespace ChainSafe.Gaming.Reown.Methods
7+
{
8+
[RpcMethod("wallet_addEthereumChain")]
9+
[RpcRequestOptions(Clock.ONE_MINUTE, 99993)]
10+
public class WalletAddEthereumChain : List<object>
11+
{
12+
public WalletAddEthereumChain(object[] chains)
13+
: base(chains)
14+
{
15+
}
16+
17+
public WalletAddEthereumChain()
18+
{
19+
}
20+
}
21+
}

src/ChainSafe.Gaming.Reown/ReownProvider.cs

Lines changed: 11 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Globalization;
34
using System.Linq;
5+
using System.Numerics;
46
using System.Threading;
57
using System.Threading.Tasks;
8+
using ChainSafe.Gaming.Evm.Network;
9+
using ChainSafe.Gaming.Evm.Providers;
610
using ChainSafe.Gaming.Reown.Connection;
711
using ChainSafe.Gaming.Reown.Methods;
812
using ChainSafe.Gaming.Reown.Models;
@@ -16,6 +20,7 @@
1620
using ChainSafe.Gaming.Web3.Core.Operations;
1721
using ChainSafe.Gaming.Web3.Environment;
1822
using ChainSafe.Gaming.Web3.Evm.Wallet;
23+
using Nethereum.Hex.HexTypes;
1924
using Nethereum.JsonRpc.Client.RpcMessages;
2025
using Newtonsoft.Json;
2126
using Reown.Core.Common.Logging;
@@ -48,7 +53,7 @@ public class ReownProvider : WalletProvider, ILifecycleParticipant, IConnectionH
4853
private readonly Web3Environment environment;
4954
private readonly IChainConfigSet chainConfigSet;
5055
private readonly IOperationTracker operationTracker;
51-
private readonly IMainThreadRunner mainThreadRunner;
56+
private readonly IRpcProvider rpcProvider;
5257

5358
private SessionStruct session;
5459
private bool connected;
@@ -66,11 +71,11 @@ public ReownProvider(
6671
Web3Environment environment,
6772
ReownHttpClient reownHttpClient,
6873
IOperationTracker operationTracker,
69-
IMainThreadRunner mainThreadRunner)
74+
IRpcProvider rpcProvider)
7075
: base(environment, chainConfig, operationTracker)
7176
{
7277
this.operationTracker = operationTracker;
73-
this.mainThreadRunner = mainThreadRunner;
78+
this.rpcProvider = rpcProvider;
7479
this.chainConfigSet = chainConfigSet;
7580
this.environment = environment;
7681
analyticsClient = environment.AnalyticsClient;
@@ -172,6 +177,7 @@ private async Task Initialize()
172177
"eth_sendTransaction",
173178
"eth_getTransactionByHash",
174179
"wallet_switchEthereumChain",
180+
"wallet_addEthereumChain",
175181
"eth_blockNumber",
176182
},
177183
Events = new[]
@@ -234,8 +240,6 @@ public override async Task<string> Connect()
234240

235241
connected = true;
236242

237-
await CheckAndSwitchNetwork();
238-
239243
return address;
240244
}
241245
catch (Exception e)
@@ -247,43 +251,6 @@ public override async Task<string> Connect()
247251
}
248252
}
249253

250-
private async Task CheckAndSwitchNetwork()
251-
{
252-
var chainId = ExtractChainIdFromAddress();
253-
if (chainId == $"{EvmNamespace}:{chainConfig.ChainId}")
254-
{
255-
return;
256-
}
257-
258-
const int maxSwitchAttempts = 3;
259-
260-
for (var i = 0; ;)
261-
{
262-
var messageToUser = i == 0
263-
? "Switching wallet network..."
264-
: $"Switching wallet network (attempt {i + 1})...";
265-
266-
using (operationTracker.TrackOperation(messageToUser))
267-
{
268-
try
269-
{
270-
await SwitchChain(chainConfig.ChainId);
271-
UpdateSessionChainId();
272-
return; // success, exit loop
273-
}
274-
catch (ReownNetworkException)
275-
{
276-
if (++i >= maxSwitchAttempts)
277-
{
278-
throw;
279-
}
280-
281-
logWriter.Log("Attempted to switch the network, but was rejected. Trying again...");
282-
}
283-
}
284-
}
285-
}
286-
287254
private void UpdateSessionChainId()
288255
{
289256
var defaultChain = session.Namespaces.Keys.FirstOrDefault();
@@ -589,6 +556,8 @@ async Task<T> MakeRequest<TRequest>(bool sendChainId = true)
589556
return await MakeRequest<EthSendTransaction>();
590557
case "wallet_switchEthereumChain":
591558
return await MakeRequest<WalletSwitchEthereumChain>(false);
559+
case "wallet_addEthereumChain":
560+
return await MakeRequest<WalletAddEthereumChain>(false);
592561
default:
593562
try
594563
{

src/ChainSafe.Gaming.Unity.EthereumWindow/Dto/NativeCurrency.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ namespace ChainSafe.Gaming.Unity.EthereumWindow.Dto
77
/// </summary>
88
public struct NativeCurrency
99
{
10-
public NativeCurrency(string symbol)
10+
public NativeCurrency(string name, string symbol, int decimals)
1111
{
12-
Name = symbol;
12+
Name = name;
1313
Symbol = symbol;
14-
Decimals = 18;
14+
Decimals = decimals;
1515
}
1616

1717
[JsonProperty("name")]

0 commit comments

Comments
 (0)