Skip to content

Commit

Permalink
refactor: contracy deployment api change + scoped registry editor scr…
Browse files Browse the repository at this point in the history
…ipt for open upm support +
  • Loading branch information
talha-trili committed Oct 9, 2024
1 parent 6e25f9d commit 5af8184
Show file tree
Hide file tree
Showing 22 changed files with 157 additions and 57 deletions.
6 changes: 2 additions & 4 deletions Runtime/Scripts-v2/API/TezosAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,12 @@ await UnityMainThreadDispatcher.Instance().EnqueueAsync(

public static async UniTask<bool> Disconnect()
{

if (!IsConnected())
{
TezosLogger.LogWarning("No connection found to disconnect");
return false;
}



if (IsWalletConnected())
{
var result = await _walletProviderController.Disconnect();
Expand Down Expand Up @@ -159,7 +157,7 @@ await UnityMainThreadDispatcher.Instance().EnqueueAsync(
return result;
}

public static UniTask RequestContractOrigination(OriginateContractRequest originateContractRequest) => ProviderFactory.GetConnectedProviderController().RequestContractOrigination(originateContractRequest);
public static UniTask DeployContract(DeployContractRequest deployContractRequest) => ProviderFactory.GetConnectedProviderController().DeployContract(deployContractRequest);

/// <summary>
/// Fetches the XTZ balance of a given wallet address asynchronously.
Expand Down
106 changes: 106 additions & 0 deletions Runtime/Scripts-v2/Editor/ScopedRegistryEditor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;

namespace Tezos.Editor
{
public class ScopedRegistryEditor : AssetPostprocessor
{
private static bool _packageImported;

private const string _registryName = "package.openupm.com";
private const string _registryUrl = "https://package.openupm.com";
private const string _nethereumScope = "com.nethereum";
private const string _reownScope = "com.reown";

private static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths
)
{
if (_packageImported) return;

foreach (string asset in importedAssets)
{
if (asset.Contains("com.trilitech.tezos-unity-sdk"))
{
Debug.Log("Tezos Wallet Connect imported, adding or updating scoped registries.");
AddOrUpdateScopedRegistry(
new ScopedRegistry
{
name =
_registryName,
url = _registryUrl,
scopes = new[] { _nethereumScope, _reownScope }
}
);
_packageImported = true;
CompilationPipeline.RequestScriptCompilation();
break;
}
}
}

private static void AddOrUpdateScopedRegistry(ScopedRegistry newRegistry)
{
var manifestPath = Path.Combine(Application.dataPath, "..", "Packages/manifest.json");
var manifestJson = File.ReadAllText(manifestPath);

var manifest = JsonConvert.DeserializeObject<ManifestJson>(manifestJson);

var existingRegistry = manifest.scopedRegistries
.FirstOrDefault(
reg => reg.name == newRegistry.name &&
reg.url == newRegistry.url
);

if (existingRegistry != null)
{
var missingScopes = newRegistry.scopes.Except(existingRegistry.scopes).ToList();
if (missingScopes.Count > 0)
{
existingRegistry.scopes = existingRegistry.scopes.Concat(missingScopes).ToArray();
Debug.Log(
$"Updated scoped registry '{newRegistry.name}' with missing scopes: {string.Join(", ", missingScopes)}"
);
}
else
{
Debug.Log(
$"No updates needed for scoped registry '{newRegistry.name}' as all scopes are already present."
);
}
}
else
{
manifest.scopedRegistries.Add(newRegistry);
Debug.Log(
$"Added new scoped registry '{newRegistry.name}' with scopes: {string.Join(", ", newRegistry.scopes)}"
);
}

File.WriteAllText(manifestPath, JsonConvert.SerializeObject(manifest, Formatting.Indented));
}

public class ScopedRegistry
{
public string name;
public string url;
public string[] scopes;
}

public class ManifestJson
{
public Dictionary<string, string> dependencies = new();
public List<ScopedRegistry> scopedRegistries = new();
}
}
}
#endif
3 changes: 3 additions & 0 deletions Runtime/Scripts-v2/Editor/ScopedRegistryEditor.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 3 additions & 9 deletions Runtime/Scripts-v2/Editor/TezosEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public void SetupConfigs()
CopyAndMergeFolders(SourceWebGLTemplatesPath, Path.Combine(DestinationAssetsPath, "WebGLTemplates"));
SetWebGLTemplate(WebGLTemplateName);
CreateTezosConfigs();

AssetDatabase.SaveAssets();
AssetDatabase.Refresh();

Debug.Log("Tezos setup completed.");
}
Expand All @@ -53,9 +56,6 @@ private static void CreateLinkerFile()

File.WriteAllText(linkerFilePath, linkXmlContent);
Debug.Log($"link.xml created/updated at: {linkerFilePath}");

AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}

private static void CopyAndMergeFolders(string sourcePath, string destinationPath)
Expand All @@ -73,7 +73,6 @@ private static void CopyAndMergeFolders(string sourcePath, string destinationPat
}

CopyDirectoryRecursively(sourcePath, destinationPath);
AssetDatabase.Refresh();
}

private static void CopyDirectoryRecursively(string sourceDir, string targetDir)
Expand All @@ -100,9 +99,6 @@ private static void SetWebGLTemplate(string templateName)
{
PlayerSettings.WebGL.template = templateName;
Debug.Log($"Set WebGL template to: {templateName}");

AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}

private static void CreateTezosConfigs()
Expand All @@ -114,8 +110,6 @@ private static void CreateTezosConfigs()
tezosConfig.DataProvider = dataProviderConfig;

EditorUtility.SetDirty(tezosConfig);
AssetDatabase.SaveAssetIfDirty(tezosConfig);
AssetDatabase.Refresh();
Debug.Log("Tezos configs created and updated.");

EditorGUIUtility.PingObject(tezosConfig);
Expand Down
3 changes: 2 additions & 1 deletion Runtime/Scripts-v2/Initializer/Tezos.Initializer.asmdef
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"GUID:a36d4ab4ac1445529d56bb1978202fe9",
"GUID:a86c196fe46d49568cc834ea82f009c3",
"GUID:67dfc283a3014520b1ae80c0cb8e8822",
"GUID:832ee16f9a74421fa64eac13167606ab"
"GUID:832ee16f9a74421fa64eac13167606ab",
"GUID:0c0f402fc1cb344ef87d37f5a81f2739"
],
"includePlatforms": [],
"excludePlatforms": [],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Tezos.Operation
{
public struct OriginateContractRequest
public struct DeployContractRequest
{
public string Script;
public string DelegateAddress;
Expand Down
1 change: 1 addition & 0 deletions Runtime/Scripts-v2/Operation/OperationRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace Tezos.Operation
public struct OperationRequest
{
public string Destination;
public string ContractABI;
public string EntryPoint;
public string Arg;
public string Amount;
Expand Down
6 changes: 3 additions & 3 deletions Runtime/Scripts-v2/Provider/IProviderController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ public interface IProviderController : IController
ProviderType ProviderType { get; }
bool IsConnected { get; }
UniTask<string> GetBalance();
UniTask<OperationResponse> RequestOperation(OperationRequest operationRequest);
UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signRequest);
UniTask RequestContractOrigination(OriginateContractRequest originationRequest);
UniTask<OperationResponse> RequestOperation(OperationRequest operationRequest);
UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signRequest);
UniTask DeployContract(DeployContractRequest originationRequest);
}
}
14 changes: 3 additions & 11 deletions Runtime/Scripts-v2/Request/HttpClients/TezosClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Text;
using Dynamic.Json;
using Newtonsoft.Json;
using Tezos.Cysharp.Threading.Tasks;
using Tezos.Logger;
Expand All @@ -14,15 +13,7 @@ public class TezosClient

private int RequestTimeout { get; }

private T DeserializeJson<T>(string json)
{
if (typeof(T) == typeof(string))
{
return (T)(object)DJson.Parse(json, JsonOptions.DefaultOptions);
}

return JsonConvert.DeserializeObject<T>(json);
}
private T DeserializeJson<T>(string json) => JsonConvert.DeserializeObject<T>(json);

public async UniTask<T> GetRequest<T>(string endpoint)
{
Expand Down Expand Up @@ -59,7 +50,8 @@ public async UniTask<T> PostRequest<T>(string endpoint, object data)
request.timeout = RequestTimeout;
request.SetRequestHeader(HttpHeaders.Accept.Key, HttpHeaders.Accept.Value);
request.SetRequestHeader(HttpHeaders.UserAgent.Key, HttpHeaders.UserAgent.Value);
request.SetRequestHeader(HttpHeaders.ContentType.Key, "application/json");
request.SetRequestHeader(HttpHeaders.ContentType.Key, HttpHeaders.ContentType.Value);

var operation = request.SendWebRequest();
while (!operation.isDone)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ public interface ISocialLoginProvider
bool IsLoggedIn();
UniTask<OperationResponse> RequestOperation(OperationRequest operationRequest);
UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signPayloadRequest);
UniTask RequestContractOrigination(OriginateContractRequest originateContractRequest);
UniTask RequestContractOrigination(DeployContractRequest deployContractRequest);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,6 @@ public async UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest
return await _signPayloadTcs.WithTimeout(10 * 1000);
}

public UniTask RequestContractOrigination(OriginateContractRequest originateContractRequest) => throw new NotSupportedException("Contract origination is not supported by Kukai wallet.");
public UniTask RequestContractOrigination(DeployContractRequest deployContractRequest) => throw new NotSupportedException("Contract origination is not supported by Kukai wallet.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ public UniTask<SocialProviderData> LogIn(SocialProviderData data)

_logInTcs = new();
TezosLogger.LogDebug($"Connect method entered");
var tezosConfig = ConfigGetter.GetOrCreateConfig<TezosConfig>();
var appConfig = ConfigGetter.GetOrCreateConfig<AppConfig>();
var dataProviderConfig = ConfigGetter.GetOrCreateConfig<DataProviderConfig>();
var appConfig = ConfigGetter.GetOrCreateConfig<AppConfig>();
JsInitWallet(
tezosConfig.Network.ToString(), tezosConfig.Rpc, SocialLoginType.ToString().ToLower(), appConfig.AppName,
appConfig.AppUrl, appConfig.AppIcon
dataProviderConfig.Network.ToString(), dataProviderConfig.BaseUrl, SocialLoginType.ToString().ToLower(), appConfig.AppName,
appConfig.AppUrl, appConfig.AppIcon
);

JsConnectAccount();
Expand All @@ -146,7 +146,7 @@ public async UniTask<OperationResponse> RequestOperation(OperationRequest operat
if (_operationTcs != null && _operationTcs.Task.Status == UniTaskStatus.Pending) return await _operationTcs.Task;

_operationTcs = new();
JsSendContractCall(operationRequest.Destination, operationRequest.Amount.ToString(), operationRequest.EntryPoint, operationRequest.Arg);
JsSendContractCall(operationRequest.Destination, operationRequest.Amount, operationRequest.EntryPoint, operationRequest.Arg);
return await _operationTcs.WithTimeout(10 * 1000, "Request operation task timeout.");
}

Expand All @@ -159,7 +159,7 @@ public async UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest
return await _signPayloadTcs.WithTimeout(10 * 1000, "Sign payload task timeout.");
}

public UniTask RequestContractOrigination(OriginateContractRequest originationRequest)
public UniTask RequestContractOrigination(DeployContractRequest originationRequest)
{
TezosLogger.LogDebug("RequestContractOrigination - BeaconWebGL");
JsRequestContractOrigination(originationRequest.Script, originationRequest.DelegateAddress);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,6 @@ public async UniTask<bool> LogOut()
public UniTask<string> GetBalance() => _socialLoginProviders.Find(sp => sp.SocialLoginType == _socialProviderData?.SocialLoginType).GetBalance(_socialProviderData.WalletAddress);
public UniTask<OperationResponse> RequestOperation(OperationRequest walletOperationRequest) => _socialLoginProviders.Find(sp => sp.SocialLoginType == _socialProviderData?.SocialLoginType).RequestOperation(walletOperationRequest);
public UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signPayloadRequest) => _socialLoginProviders.Find(sp => sp.SocialLoginType == _socialProviderData?.SocialLoginType).RequestSignPayload(signPayloadRequest);
public UniTask RequestContractOrigination(OriginateContractRequest originateContractRequest) => _socialLoginProviders.Find(sp => sp.SocialLoginType == _socialProviderData?.SocialLoginType).RequestContractOrigination(originateContractRequest);
public UniTask DeployContract(DeployContractRequest deployContractRequest) => _socialLoginProviders.Find(sp => sp.SocialLoginType == _socialProviderData?.SocialLoginType).RequestContractOrigination(deployContractRequest);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public async UniTask<bool> Disconnect()
return await _signPayloadTcs.WithTimeout(10 * 1000, "Sign payload task timeout.");
}

public async UniTask RequestContractOrigination(OriginateContractRequest originationRequest)
public async UniTask DeployContract(DeployContractRequest originationRequest)
{
TezosLogger.LogDebug("RequestContractOrigination - BeaconDotNet");
await _operationRequestHandler.RequestContractOrigination(originationRequest.Script, originationRequest.DelegateAddress, BeaconDappClient);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,11 @@ public UniTask<WalletProviderData> Connect(WalletProviderData data)

_walletConnectionTcs = new();
TezosLogger.LogDebug($"Connect method entered");
var tezosConfig = ConfigGetter.GetOrCreateConfig<TezosConfig>();
var appConfig = ConfigGetter.GetOrCreateConfig<AppConfig>();
var dataProviderConfig = ConfigGetter.GetOrCreateConfig<DataProviderConfig>();
var appConfig = ConfigGetter.GetOrCreateConfig<AppConfig>();
JsInitWallet(
tezosConfig.Network.ToString(), tezosConfig.Rpc, WalletType.ToString().ToLower(), appConfig.AppName,
appConfig.AppUrl, appConfig.AppIcon
dataProviderConfig.Network.ToString(), dataProviderConfig.BaseUrl, WalletType.ToString().ToLower(), appConfig.AppName,
appConfig.AppUrl, appConfig.AppIcon
);

JsConnectAccount();
Expand Down Expand Up @@ -164,7 +164,7 @@ public async UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest
return await _signPayloadTcs.WithTimeout(10 * 1000, "Sign payload task timeout.");
}

public UniTask RequestContractOrigination(OriginateContractRequest originationRequest)
public UniTask DeployContract(DeployContractRequest originationRequest)
{
TezosLogger.LogDebug("RequestContractOrigination - BeaconWebGL");
JsRequestContractOrigination(originationRequest.Script, originationRequest.DelegateAddress);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public interface IWalletProvider
public event Action<string> PairingRequested;
public WalletType WalletType { get; }
UniTask Init();
UniTask<string> GetBalance(string walletAddress);
UniTask<string> GetBalance(string walletAddress);
UniTask<WalletProviderData> Connect(WalletProviderData data);
UniTask<bool> Disconnect();
UniTask<OperationResponse> RequestOperation(OperationRequest operationRequest);
UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signRequest);
UniTask RequestContractOrigination(OriginateContractRequest originationRequest);
UniTask<OperationResponse> RequestOperation(OperationRequest operationRequest);
UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest signRequest);
UniTask DeployContract(DeployContractRequest originationRequest);
bool IsAlreadyConnected();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ public async UniTask<bool> Disconnect()
public UniTask<string> GetBalance() => _walletProviders.Find(wp => wp.WalletType == _connectedWalletData?.WalletType).GetBalance(_connectedWalletData.WalletAddress);
public UniTask<OperationResponse> RequestOperation(OperationRequest walletOperationRequest) => _walletProviders.Find(wp => wp.WalletType == _connectedWalletData?.WalletType).RequestOperation(walletOperationRequest);
public UniTask<SignPayloadResponse> RequestSignPayload(SignPayloadRequest walletSignPayloadRequest) => _walletProviders.Find(wp => wp.WalletType == _connectedWalletData?.WalletType).RequestSignPayload(walletSignPayloadRequest);
public UniTask RequestContractOrigination(OriginateContractRequest walletOriginateContractRequest) => _walletProviders.Find(wp => wp.WalletType == _connectedWalletData?.WalletType).RequestContractOrigination(walletOriginateContractRequest);
public UniTask DeployContract(DeployContractRequest walletDeployContractRequest) => _walletProviders.Find(wp => wp.WalletType == _connectedWalletData?.WalletType).DeployContract(walletDeployContractRequest);
}
}
Loading

0 comments on commit 5af8184

Please sign in to comment.