diff --git a/CHANGELOG.md b/CHANGELOG.md index 6259bb88..8275b659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [Bug](https://github.com/trilitech/tezos-unity-sdk/issues/102) with standalone IL2CPP build fails - [Bug](https://github.com/trilitech/tezos-unity-sdk/issues/103) with closing Beacon database connections before app exit +### Added +- Missing namespaces + +### Changed +- Issue Report Form menu item path changed (new path: `Tools/Tezos SDK for Unity/Report an Issue`) + ## [1.5.1] - 2023-06-27 ### Fixed diff --git a/Editor/IssueReportFormWindow.cs b/Editor/IssueReportFormWindow.cs index 19ff0496..b166b330 100644 --- a/Editor/IssueReportFormWindow.cs +++ b/Editor/IssueReportFormWindow.cs @@ -4,7 +4,7 @@ using Newtonsoft.Json.Linq; using UnityEngine.Networking; -namespace Tezos.Editor.Windows +namespace TezosSDK.Editor.Windows { public class IssueReportFormWindow : EditorWindow { @@ -19,7 +19,7 @@ public class IssueReportFormWindow : EditorWindow private string errorMessage = ""; private string successMessage = ""; - [MenuItem("Tezos SDK/Issue Report Form")] + [MenuItem("Tools/Tezos SDK for Unity/Report an Issue")] public static void ShowWindow() { GetWindow("Issue Report Form"); diff --git a/Runtime/View/AuthenticationManager.cs b/Runtime/View/AuthenticationManager.cs index 6e30f2bb..791abff8 100644 --- a/Runtime/View/AuthenticationManager.cs +++ b/Runtime/View/AuthenticationManager.cs @@ -2,83 +2,86 @@ using TezosSDK.Tezos.Wallet; using UnityEngine; -public class AuthenticationManager : MonoBehaviour +namespace TezosSDK.View { - private ITezos _tezos; - [SerializeField] private QRCodeView qrCodeView; - [SerializeField] private GameObject contentPanel; - [SerializeField] private GameObject deepLinkButton; - [SerializeField] private GameObject logoutButton; - [SerializeField] private GameObject qrCodePanel; + public class AuthenticationManager : MonoBehaviour + { + private ITezos _tezos; + [SerializeField] private QRCodeView qrCodeView; + [SerializeField] private GameObject contentPanel; + [SerializeField] private GameObject deepLinkButton; + [SerializeField] private GameObject logoutButton; + [SerializeField] private GameObject qrCodePanel; - private bool _isMobile; + private bool _isMobile; - void Start() - { + void Start() + { #if (UNITY_IOS || UNITY_ANDROID) _isMobile = true; #else - _isMobile = false; + _isMobile = false; #endif - _tezos = TezosSingleton.Instance; - - _tezos.Wallet.MessageReceiver.HandshakeReceived += OnHandshakeReceived; - _tezos.Wallet.MessageReceiver.AccountConnected += OnAccountConnected; - _tezos.Wallet.MessageReceiver.AccountDisconnected += OnAccountDisconnected; - } + _tezos = TezosSingleton.Instance; - void OnHandshakeReceived(string handshake) - { - EnableUI(isAuthenticated: false); - qrCodeView.SetQrCode(handshake); - } + _tezos.Wallet.MessageReceiver.HandshakeReceived += OnHandshakeReceived; + _tezos.Wallet.MessageReceiver.AccountConnected += OnAccountConnected; + _tezos.Wallet.MessageReceiver.AccountDisconnected += OnAccountDisconnected; + } - void OnAccountConnected(string result) - { - EnableUI(isAuthenticated: true); - Debug.Log("OnAccountConnected"); - } + void OnHandshakeReceived(string handshake) + { + EnableUI(isAuthenticated: false); + qrCodeView.SetQrCode(handshake); + } - void OnAccountDisconnected(string result) - { - Debug.Log("OnAccountDisconnected"); - } + void OnAccountConnected(string result) + { + EnableUI(isAuthenticated: true); + Debug.Log("OnAccountConnected"); + } - public void DisconnectWallet() - { - EnableUI(isAuthenticated: false); - _tezos.Wallet.Disconnect(); - } + void OnAccountDisconnected(string result) + { + Debug.Log("OnAccountDisconnected"); + } - public void ConnectByDeeplink() - { - _tezos.Wallet.Connect(WalletProviderType.beacon); - } + public void DisconnectWallet() + { + EnableUI(isAuthenticated: false); + _tezos.Wallet.Disconnect(); + } - void EnableUI(bool isAuthenticated) - { - if (isAuthenticated) + public void ConnectByDeeplink() { - deepLinkButton.SetActive(false); - qrCodePanel.SetActive(false); + _tezos.Wallet.Connect(WalletProviderType.beacon); } - else + + void EnableUI(bool isAuthenticated) { - if (_isMobile) + if (isAuthenticated) { - deepLinkButton.SetActive(true); + deepLinkButton.SetActive(false); qrCodePanel.SetActive(false); } else { - qrCodePanel.SetActive(true); - deepLinkButton.SetActive(false); + if (_isMobile) + { + deepLinkButton.SetActive(true); + qrCodePanel.SetActive(false); + } + else + { + qrCodePanel.SetActive(true); + deepLinkButton.SetActive(false); + } } - } - logoutButton.SetActive(isAuthenticated); + logoutButton.SetActive(isAuthenticated); - if (contentPanel == null) return; - contentPanel.SetActive(isAuthenticated); + if (contentPanel == null) return; + contentPanel.SetActive(isAuthenticated); + } } } \ No newline at end of file diff --git a/Runtime/View/QRCodeView.cs b/Runtime/View/QRCodeView.cs index 253d410b..afd5744c 100644 --- a/Runtime/View/QRCodeView.cs +++ b/Runtime/View/QRCodeView.cs @@ -3,51 +3,53 @@ using ZXing; using ZXing.QrCode; - -public class QRCodeView : MonoBehaviour +namespace TezosSDK.View { - [SerializeField] private RawImage _rawImage; - private Texture2D _texture; - - void Start() - { - if (_texture != null) return; - - _rawImage.texture = _texture = new Texture2D(256, 256); - _texture.filterMode = FilterMode.Point; - } - - public void SetQrCode(string handshake) + public class QRCodeView : MonoBehaviour { - var uri = "tezos://?type=tzip10&data=" + handshake; - EncodeTextToQrCode(uri); - } + [SerializeField] private RawImage _rawImage; + private Texture2D _texture; - public void EncodeTextToQrCode(string text) - { - if (_texture == null) + void Start() { + if (_texture != null) return; + _rawImage.texture = _texture = new Texture2D(256, 256); _texture.filterMode = FilterMode.Point; } - var colors = Encode(text, _texture.width, _texture.height); - _texture.SetPixels32(colors); - _texture.Apply(); - } + public void SetQrCode(string handshake) + { + var uri = "tezos://?type=tzip10&data=" + handshake; + EncodeTextToQrCode(uri); + } - private Color32[] Encode(string text, int width, int height) - { - var writer = new BarcodeWriter + public void EncodeTextToQrCode(string text) { - Format = BarcodeFormat.QR_CODE, - Options = new QrCodeEncodingOptions() + if (_texture == null) { - Width = width, - Height = height, - PureBarcode = true + _rawImage.texture = _texture = new Texture2D(256, 256); + _texture.filterMode = FilterMode.Point; } - }; - return writer.Write(text); + + var colors = Encode(text, _texture.width, _texture.height); + _texture.SetPixels32(colors); + _texture.Apply(); + } + + private Color32[] Encode(string text, int width, int height) + { + var writer = new BarcodeWriter + { + Format = BarcodeFormat.QR_CODE, + Options = new QrCodeEncodingOptions() + { + Width = width, + Height = height, + PureBarcode = true + } + }; + return writer.Write(text); + } } } \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/CopyToClipboard.cs b/Samples~/Scripts/DemoExample/CopyToClipboard.cs index 02f7b5ba..b0068443 100644 --- a/Samples~/Scripts/DemoExample/CopyToClipboard.cs +++ b/Samples~/Scripts/DemoExample/CopyToClipboard.cs @@ -1,44 +1,46 @@ using System.Collections; -using Unity.VisualScripting; using UnityEngine; using UnityEngine.EventSystems; using CoroutineRunner = TezosSDK.Helpers.CoroutineRunner; -public class CopyToClipboard : MonoBehaviour, IPointerClickHandler +namespace TezosSDK.Samples.DemoExample { - [SerializeField] TMPro.TextMeshProUGUI text; - [SerializeField] TMPro.TMP_InputField inputField; + public class CopyToClipboard : MonoBehaviour, IPointerClickHandler + { + [SerializeField] TMPro.TextMeshProUGUI text; + [SerializeField] TMPro.TMP_InputField inputField; - bool _blockCopy = false; + bool _blockCopy = false; - private void Start() - { - inputField.gameObject.SetActive(false); - } + private void Start() + { + inputField.gameObject.SetActive(false); + } + + public void OnPointerClick(PointerEventData eventData) + { + if (_blockCopy) + return; - public void OnPointerClick(PointerEventData eventData) - { - if (_blockCopy) - return; - #if UNITY_WEBGL inputField.gameObject.SetActive(true); inputField.text = text.text; text.gameObject.SetActive(false); #endif - - // copy text to the clipboard - GUIUtility.systemCopyBuffer = text.text; - CoroutineRunner.Instance.StartWrappedCoroutine(OnTextCopied()); - } - IEnumerator OnTextCopied() - { - _blockCopy = true; - string origin = text.text; - text.text = "Copied to clipboard."; - yield return new WaitForSeconds(1.5f); - text.text = origin; - _blockCopy = false; + // copy text to the clipboard + GUIUtility.systemCopyBuffer = text.text; + CoroutineRunner.Instance.StartWrappedCoroutine(OnTextCopied()); + } + + IEnumerator OnTextCopied() + { + _blockCopy = true; + string origin = text.text; + text.text = "Copied to clipboard."; + yield return new WaitForSeconds(1.5f); + text.text = origin; + _blockCopy = false; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/ExampleManager.cs b/Samples~/Scripts/DemoExample/Core/ExampleManager.cs index 19a9e3c4..96887db0 100644 --- a/Samples~/Scripts/DemoExample/Core/ExampleManager.cs +++ b/Samples~/Scripts/DemoExample/Core/ExampleManager.cs @@ -10,410 +10,413 @@ using UnityEngine; using Logger = TezosSDK.Helpers.Logger; -public class ExampleManager : IExampleManager +namespace TezosSDK.Samples.DemoExample { - private string _networkRPC; + public class ExampleManager : IExampleManager + { + private string _networkRPC; - private const string - contractAddress = "KT1WguzxyLmuKbJhz3jNuoRzzaUCncfp6PFE"; //"KT1DMWAeaP6wxKWPFDLGDkB7xUg563852AjD"; + private const string + contractAddress = "KT1WguzxyLmuKbJhz3jNuoRzzaUCncfp6PFE"; //"KT1DMWAeaP6wxKWPFDLGDkB7xUg563852AjD"; - private const int softCurrencyID = 0; + private const int softCurrencyID = 0; - private ITezosAPI _tezos; + private ITezosAPI _tezos; - public User CurrentUser { get; private set; } + public User CurrentUser { get; private set; } - public ExampleManager() - { - CurrentUser = null; - } + public ExampleManager() + { + CurrentUser = null; + } - public void Init(Action callback = null) - { - _tezos = TezosSingleton.Instance; - _networkRPC = TezosConfig.Instance.RpcBaseUrl; - } + public void Init(Action callback = null) + { + _tezos = TezosSingleton.Instance; + _networkRPC = TezosConfig.Instance.RpcBaseUrl; + } - public void Unpair() - { - _tezos.DisconnectWallet(); - CurrentUser = null; - } + public void Unpair() + { + _tezos.DisconnectWallet(); + CurrentUser = null; + } - public void FetchInventoryItems(Action> callback) - { - var activeWalletAddress = _tezos.GetActiveWalletAddress(); // Address to the current active account - - const string entrypoint = "view_items_of"; - var input = new { @string = activeWalletAddress }; - - CoroutineRunner.Instance.StartWrappedCoroutine( - _tezos.ReadView( - contractAddress: contractAddress, - entrypoint: entrypoint, - input: JsonSerializer.Serialize(input, JsonOptions.DefaultOptions), - callback: result => - { - Logger.LogDebug("READING INVENTORY DATA"); - - // deserialize the json data to inventory items - CoroutineRunner.Instance.StartWrappedCoroutine( - NetezosExtensions.HumanizeValue( - val: result, - rpcUri: _networkRPC, - destination: contractAddress, - humanizeEntrypoint: "humanizeInventory", - onComplete: (ContractInventoryViewResult[] inventory) => - OnInventoryFetched(inventory, callback)) - ); - })); - } + public void FetchInventoryItems(Action> callback) + { + var activeWalletAddress = _tezos.GetActiveWalletAddress(); // Address to the current active account - private void OnInventoryFetched(ContractInventoryViewResult[] inventory, Action> callback) - { - var dummyItemList = new List(); - var owner = _tezos.GetActiveWalletAddress(); + const string entrypoint = "view_items_of"; + var input = new {@string = activeWalletAddress}; + + CoroutineRunner.Instance.StartWrappedCoroutine( + _tezos.ReadView( + contractAddress: contractAddress, + entrypoint: entrypoint, + input: JsonSerializer.Serialize(input, JsonOptions.DefaultOptions), + callback: result => + { + Logger.LogDebug("READING INVENTORY DATA"); + + // deserialize the json data to inventory items + CoroutineRunner.Instance.StartWrappedCoroutine( + NetezosExtensions.HumanizeValue( + val: result, + rpcUri: _networkRPC, + destination: contractAddress, + humanizeEntrypoint: "humanizeInventory", + onComplete: (ContractInventoryViewResult[] inventory) => + OnInventoryFetched(inventory, callback)) + ); + })); + } - if (inventory != null) + private void OnInventoryFetched(ContractInventoryViewResult[] inventory, Action> callback) { - foreach (var item in inventory) + var dummyItemList = new List(); + var owner = _tezos.GetActiveWalletAddress(); + + if (inventory != null) { - var id = Convert.ToInt32(item.id); - var itemType = id == 0 ? 0 : Convert.ToInt32(item.item.itemType) % 4 + 1; - var amount = id == 0 ? Convert.ToInt32(item.amount) : 1; - - var stats = new StatParams( - Convert.ToInt32(item.item.damage), - Convert.ToInt32(item.item.armor), - Convert.ToInt32(item.item.attackSpeed), - Convert.ToInt32(item.item.healthPoints), - Convert.ToInt32(item.item.manaPoints) - ); - - dummyItemList.Add(new Item( - (ItemType)itemType, - "Items/TestItem " + itemType, - "Item " + id, - stats, - amount, - id, - owner)); + foreach (var item in inventory) + { + var id = Convert.ToInt32(item.id); + var itemType = id == 0 ? 0 : Convert.ToInt32(item.item.itemType) % 4 + 1; + var amount = id == 0 ? Convert.ToInt32(item.amount) : 1; + + var stats = new StatParams( + Convert.ToInt32(item.item.damage), + Convert.ToInt32(item.item.armor), + Convert.ToInt32(item.item.attackSpeed), + Convert.ToInt32(item.item.healthPoints), + Convert.ToInt32(item.item.manaPoints) + ); + + dummyItemList.Add(new Item( + (ItemType) itemType, + "Items/TestItem " + itemType, + "Item " + id, + stats, + amount, + id, + owner)); + } } + + callback?.Invoke(dummyItemList); } - callback?.Invoke(dummyItemList); - } + public class ContractItem + { + public string damage { get; set; } + public string armor { get; set; } + public string attackSpeed { get; set; } + public string healthPoints { get; set; } + public string manaPoints { get; set; } + public string itemType { get; set; } + } - public class ContractItem - { - public string damage { get; set; } - public string armor { get; set; } - public string attackSpeed { get; set; } - public string healthPoints { get; set; } - public string manaPoints { get; set; } - public string itemType { get; set; } - } + public class ContractInventoryViewResult + { + public string id { get; set; } + public string amount { get; set; } + public ContractItem item { get; set; } + } - public class ContractInventoryViewResult - { - public string id { get; set; } - public string amount { get; set; } - public ContractItem item { get; set; } - } + public class ContractMarketplaceViewResult + { + public string id { get; set; } + public string owner { get; set; } + public string currency { get; set; } + public string price { get; set; } + public ContractItem item { get; set; } + } - public class ContractMarketplaceViewResult - { - public string id { get; set; } - public string owner { get; set; } - public string currency { get; set; } - public string price { get; set; } - public ContractItem item { get; set; } - } + public void FetchMarketItems(Action> callback) + { + const string entrypoint = "view_items_on_market"; - public void FetchMarketItems(Action> callback) - { - const string entrypoint = "view_items_on_market"; + // Prepping parameters for Netezos and for Native is different. + // Double serialization converts double quotes (") symbol into 'u0002' string + // var input = "{\"prim\": \"Unit\"}"; + var input = new MichelinePrim + { + Prim = PrimType.Unit + }.ToJson(); + + CoroutineRunner.Instance.StartWrappedCoroutine( + _tezos.ReadView( + contractAddress: contractAddress, + entrypoint: entrypoint, + input: input, + callback: result => + { + // deserialize the json data to market items + CoroutineRunner.Instance.StartWrappedCoroutine( + NetezosExtensions.HumanizeValue( + val: result, + rpcUri: _networkRPC, + destination: contractAddress, + humanizeEntrypoint: "humanizeMarketplace", + onComplete: (ContractMarketplaceViewResult[] market) => + OnMarketplaceFetched(market, callback)) + ); + })); + } - // Prepping parameters for Netezos and for Native is different. - // Double serialization converts double quotes (") symbol into 'u0002' string - // var input = "{\"prim\": \"Unit\"}"; - var input = new MichelinePrim + private void OnMarketplaceFetched(ContractMarketplaceViewResult[] market, Action> callback) { - Prim = PrimType.Unit - }.ToJson(); - - CoroutineRunner.Instance.StartWrappedCoroutine( - _tezos.ReadView( - contractAddress: contractAddress, - entrypoint: entrypoint, - input: input, - callback: result => + var dummyItemList = new List(); + + if (market != null) + { + foreach (var item in market) { - // deserialize the json data to market items - CoroutineRunner.Instance.StartWrappedCoroutine( - NetezosExtensions.HumanizeValue( - val: result, - rpcUri: _networkRPC, - destination: contractAddress, - humanizeEntrypoint: "humanizeMarketplace", - onComplete: (ContractMarketplaceViewResult[] market) => - OnMarketplaceFetched(market, callback)) + var id = Convert.ToInt32(item.id); + var itemType = id == 0 ? 0 : Convert.ToInt32(item.item.itemType) % 4 + 1; + var currency = Convert.ToInt32(item.currency); + var price = Convert.ToInt32(item.price); + var owner = item.owner; + + var stats = new StatParams( + Convert.ToInt32(item.item.damage), + Convert.ToInt32(item.item.armor), + Convert.ToInt32(item.item.attackSpeed), + Convert.ToInt32(item.item.healthPoints), + Convert.ToInt32(item.item.manaPoints) ); - })); - } - - private void OnMarketplaceFetched(ContractMarketplaceViewResult[] market, Action> callback) - { - var dummyItemList = new List(); - if (market != null) - { - foreach (var item in market) - { - var id = Convert.ToInt32(item.id); - var itemType = id == 0 ? 0 : Convert.ToInt32(item.item.itemType) % 4 + 1; - var currency = Convert.ToInt32(item.currency); - var price = Convert.ToInt32(item.price); - var owner = item.owner; - - var stats = new StatParams( - Convert.ToInt32(item.item.damage), - Convert.ToInt32(item.item.armor), - Convert.ToInt32(item.item.attackSpeed), - Convert.ToInt32(item.item.healthPoints), - Convert.ToInt32(item.item.manaPoints) - ); - - dummyItemList.Add(new Item( - (ItemType)itemType, - "Items/TestItem " + itemType, - "Item " + id, - stats, - price, - id, - owner)); + dummyItemList.Add(new Item( + (ItemType) itemType, + "Items/TestItem " + itemType, + "Item " + id, + stats, + price, + id, + owner)); + } } - } - - callback?.Invoke(dummyItemList); - } - public void BuyItem(string owner, int itemID) - { - const string entryPoint = "buy"; + callback?.Invoke(dummyItemList); + } - var parameter = new MichelinePrim + public void BuyItem(string owner, int itemID) { - Prim = PrimType.Pair, - Args = new List + const string entryPoint = "buy"; + + var parameter = new MichelinePrim { - new MichelineString(owner), - new MichelineInt(itemID) - } - }.ToJson(); + Prim = PrimType.Pair, + Args = new List + { + new MichelineString(owner), + new MichelineInt(itemID) + } + }.ToJson(); - Logger.LogDebug(contractAddress + " " + entryPoint + parameter); - _tezos.CallContract(contractAddress, entryPoint, parameter, 0); + Logger.LogDebug(contractAddress + " " + entryPoint + parameter); + _tezos.CallContract(contractAddress, entryPoint, parameter, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } + } - public void MintItem() - { - const string entrypoint = "mint"; - const string input = "{\"prim\": \"Unit\"}"; + public void MintItem() + { + const string entrypoint = "mint"; + const string input = "{\"prim\": \"Unit\"}"; - _tezos.CallContract(contractAddress, entrypoint, input, 0); + _tezos.CallContract(contractAddress, entrypoint, input, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } - - public User GetCurrentUser() - { - return CurrentUser; - } + } - public void GetBalance(Action callback) - { - var routine = _tezos.ReadBalance(callback); - CoroutineRunner.Instance.StartWrappedCoroutine(routine); - } + public User GetCurrentUser() + { + return CurrentUser; + } - public void GetSoftBalance(Action callback) - { - GetSoftBalanceRoutine(callback); - } + public void GetBalance(Action callback) + { + var routine = _tezos.ReadBalance(callback); + CoroutineRunner.Instance.StartWrappedCoroutine(routine); + } - private void GetSoftBalanceRoutine(Action callback) - { - var caller = _tezos.GetActiveWalletAddress(); + public void GetSoftBalance(Action callback) + { + GetSoftBalanceRoutine(callback); + } - var input = new MichelinePrim + private void GetSoftBalanceRoutine(Action callback) { - Prim = PrimType.Pair, - Args = new List + var caller = _tezos.GetActiveWalletAddress(); + + var input = new MichelinePrim { - new MichelineString(caller), - new MichelineInt(softCurrencyID) - } - }.ToJson(); - - CoroutineRunner.Instance.StartWrappedCoroutine( - _tezos.ReadView( - contractAddress: contractAddress, - entrypoint: "get_balance", - input: input, - callback: result => + Prim = PrimType.Pair, + Args = new List { - var intProp = result.GetProperty("int"); - var intValue = Convert.ToInt32(intProp.ToString()); - callback(intValue); - })); - } + new MichelineString(caller), + new MichelineInt(softCurrencyID) + } + }.ToJson(); + + CoroutineRunner.Instance.StartWrappedCoroutine( + _tezos.ReadView( + contractAddress: contractAddress, + entrypoint: "get_balance", + input: input, + callback: result => + { + var intProp = result.GetProperty("int"); + var intValue = Convert.ToInt32(intProp.ToString()); + callback(intValue); + })); + } - public void TransferItem(int itemID, int amount, string address) - { - Logger.LogDebug( - $"Transfering item {itemID} from {_tezos.GetActiveWalletAddress()} to Address: {address}"); + public void TransferItem(int itemID, int amount, string address) + { + Logger.LogDebug( + $"Transfering item {itemID} from {_tezos.GetActiveWalletAddress()} to Address: {address}"); - var sender = _tezos.GetActiveWalletAddress(); - const string entrypoint = "transfer"; - var input = "[ { \"prim\": \"Pair\", \"args\": [ { \"string\": \"" + sender + - "\" }, [ { \"prim\": \"Pair\", \"args\": [ { \"string\": \"" + address + - "\" }, { \"prim\": \"Pair\", \"args\": [ { \"int\": \"" + itemID + "\" }, { \"int\": \"" + amount + - "\" } ] } ] } ] ] } ]"; + var sender = _tezos.GetActiveWalletAddress(); + const string entrypoint = "transfer"; + var input = "[ { \"prim\": \"Pair\", \"args\": [ { \"string\": \"" + sender + + "\" }, [ { \"prim\": \"Pair\", \"args\": [ { \"string\": \"" + address + + "\" }, { \"prim\": \"Pair\", \"args\": [ { \"int\": \"" + itemID + "\" }, { \"int\": \"" + amount + + "\" } ] } ] } ] ] } ]"; - _tezos.CallContract(contractAddress, entrypoint, input, 0); + _tezos.CallContract(contractAddress, entrypoint, input, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } + } - public void AddItemToMarket(int itemID, int price) - { - Debug.Log("Adding Item " + itemID + " to Market with the price of " + price); + public void AddItemToMarket(int itemID, int price) + { + Debug.Log("Adding Item " + itemID + " to Market with the price of " + price); - const string entryPoint = "addToMarket"; + const string entryPoint = "addToMarket"; - var parameter = new MichelinePrim - { - Prim = PrimType.Pair, - Args = new List + var parameter = new MichelinePrim { - new MichelinePrim + Prim = PrimType.Pair, + Args = new List { - Prim = PrimType.Pair, - Args = new List + new MichelinePrim { - new MichelineInt(0), // (currency ID = 0) represents coins - new MichelineInt(price), - } - }, - new MichelineInt(itemID), - } - }.ToJson(); - - _tezos.CallContract(contractAddress, entryPoint, parameter, 0); + Prim = PrimType.Pair, + Args = new List + { + new MichelineInt(0), // (currency ID = 0) represents coins + new MichelineInt(price), + } + }, + new MichelineInt(itemID), + } + }.ToJson(); + + _tezos.CallContract(contractAddress, entryPoint, parameter, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } + } - public void RemoveItemFromMarket(int itemID) - { - Debug.Log("Removing Item " + itemID + " from market."); + public void RemoveItemFromMarket(int itemID) + { + Debug.Log("Removing Item " + itemID + " from market."); - const string entryPoint = "removeFromMarket"; + const string entryPoint = "removeFromMarket"; - var sender = _tezos.GetActiveWalletAddress(); - var parameter = new MichelinePrim - { - Prim = PrimType.Pair, - Args = new List + var sender = _tezos.GetActiveWalletAddress(); + var parameter = new MichelinePrim { - new MichelineString(sender), - new MichelineInt(itemID) - } - }.ToJson(); + Prim = PrimType.Pair, + Args = new List + { + new MichelineString(sender), + new MichelineInt(itemID) + } + }.ToJson(); - _tezos.CallContract(contractAddress, entryPoint, parameter, 0); + _tezos.CallContract(contractAddress, entryPoint, parameter, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } + } - public void GetCoins() - { - const string entryPoint = "login"; - const string parameter = "{\"prim\": \"Unit\"}"; + public void GetCoins() + { + const string entryPoint = "login"; + const string parameter = "{\"prim\": \"Unit\"}"; - _tezos.CallContract(contractAddress, entryPoint, parameter, 0); + _tezos.CallContract(contractAddress, entryPoint, parameter, 0); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } - - public void IsItemOnMarket(int itemID, string owner, Action callback) - { - const string entrypoint = "is_item_on_market"; + } - var input = new MichelinePrim + public void IsItemOnMarket(int itemID, string owner, Action callback) { - Prim = PrimType.Pair, - Args = new List + const string entrypoint = "is_item_on_market"; + + var input = new MichelinePrim { - new MichelineString(owner), - new MichelineInt(itemID) - } - }.ToJson(); - - CoroutineRunner.Instance.StartWrappedCoroutine( - _tezos.ReadView( - contractAddress: contractAddress, - entrypoint: entrypoint, - input: input, - callback: result => + Prim = PrimType.Pair, + Args = new List { - var boolString = result.GetProperty("prim"); - var boolVal = boolString.GetString() == "True"; - callback?.Invoke(boolVal); - })); - } + new MichelineString(owner), + new MichelineInt(itemID) + } + }.ToJson(); + + CoroutineRunner.Instance.StartWrappedCoroutine( + _tezos.ReadView( + contractAddress: contractAddress, + entrypoint: entrypoint, + input: input, + callback: result => + { + var boolString = result.GetProperty("prim"); + var boolVal = boolString.GetString() == "True"; + callback?.Invoke(boolVal); + })); + } - public void RequestSignPayload(SignPayloadType signingType, string payload) - { - _tezos.RequestSignPayload(signingType, payload); + public void RequestSignPayload(SignPayloadType signingType, string payload) + { + _tezos.RequestSignPayload(signingType, payload); #if UNITY_IOS || UNITY_ANDROID Application.OpenURL("tezos://"); #endif - } + } - public bool VerifyPayload(SignPayloadType signingType, string payload) - { - return _tezos.VerifySignedPayload(signingType, payload); - } + public bool VerifyPayload(SignPayloadType signingType, string payload) + { + return _tezos.VerifySignedPayload(signingType, payload); + } - public string GetActiveAccountAddress() - { - return _tezos.GetActiveWalletAddress(); - } + public string GetActiveAccountAddress() + { + return _tezos.GetActiveWalletAddress(); + } - public void Login(WalletProviderType walletProvider) - { - _tezos.ConnectWallet(walletProvider); - } + public void Login(WalletProviderType walletProvider) + { + _tezos.ConnectWallet(walletProvider); + } - public BeaconMessageReceiver GetMessageReceiver() - { - return _tezos.MessageReceiver; + public BeaconMessageReceiver GetMessageReceiver() + { + return _tezos.MessageReceiver; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/IExampleManager.cs b/Samples~/Scripts/DemoExample/Core/IExampleManager.cs index cb6e6bc2..9f9b2795 100644 --- a/Samples~/Scripts/DemoExample/Core/IExampleManager.cs +++ b/Samples~/Scripts/DemoExample/Core/IExampleManager.cs @@ -4,111 +4,114 @@ using TezosSDK.Beacon; using TezosSDK.Tezos.Wallet; -public interface IExampleManager +namespace TezosSDK.Samples.DemoExample { - public void Init(Action callback = null); - public void Unpair(); - - public void GetCoins(); - - /// - /// Returns the currently active user. - /// - /// The Currently active user - public User GetCurrentUser(); - - /// - /// Retrieves items that should be displayed in the inventory - /// - /// - /// callback function that takes a list of IItemModels that should be displayed in Inventory - /// - public void FetchInventoryItems(Action> callback); - - /// - /// Retrieves items that should be displayed in the market - /// - /// - /// callback function that takes a list of IItemModels that should be displayed in Market - /// - public void FetchMarketItems(Action> callback); - - /// - /// Buys an item - /// - /// Owner of the item being sold - /// ID of the item that will be bought - /// callback takes a bool (true if the transaction is completed successfully) - public void BuyItem(string owner, int itemID); - - /// - /// Mints an item - /// - public void MintItem(); - - /// - /// Get account balance - /// - /// callback that takes the retrieved balance (int) - public void GetBalance(Action callback); - - /// - /// Get soft currency balance - /// - /// callback that takes the retrieved balance (int) - public void GetSoftBalance(Action callback); - - /// - /// Returns the address of the current active wallet - /// - /// - public string GetActiveAccountAddress(); - - public void Login(WalletProviderType walletProvider); - - /// - /// Transfers an item to an account address - /// - /// ID of the item that will be transfered - /// amount of the item to be transfered - /// address of the user that will receive the item - /// callback takes a bool (true if the transfer is completed successfully) - public void TransferItem(int itemID, int amount, string address); - - /// - /// Transfers an item from the inventory to the market - /// - /// ID of the item that will be added to the market - /// price of the item on the market - /// callback takes a bool (true if the process is completed successfully) - public void AddItemToMarket(int itemID, int price); - - /// - /// Transfers an item from the market to the inventory - /// - /// ID of the item that will be transfered - /// callback takes a bool (true if the process is completed successfully) - public void RemoveItemFromMarket(int itemID); - - /// - /// Return the Tezos wallet MessageReceiver for using callbacks - /// - public BeaconMessageReceiver GetMessageReceiver(); - - /// - /// Checks if item is on the marketplace in the blockchain - /// - /// - /// - /// - public void IsItemOnMarket(int itemID, string owner, Action callback); - - /// - /// Sends a request to sign a payload - /// - /// - /// - void RequestSignPayload(SignPayloadType signingType, string payload); - - bool VerifyPayload(SignPayloadType signingType, string payload); + public interface IExampleManager + { + public void Init(Action callback = null); + public void Unpair(); + + public void GetCoins(); + + /// + /// Returns the currently active user. + /// + /// The Currently active user + public User GetCurrentUser(); + + /// + /// Retrieves items that should be displayed in the inventory + /// + /// + /// callback function that takes a list of IItemModels that should be displayed in Inventory + /// + public void FetchInventoryItems(Action> callback); + + /// + /// Retrieves items that should be displayed in the market + /// + /// + /// callback function that takes a list of IItemModels that should be displayed in Market + /// + public void FetchMarketItems(Action> callback); + + /// + /// Buys an item + /// + /// Owner of the item being sold + /// ID of the item that will be bought + /// callback takes a bool (true if the transaction is completed successfully) + public void BuyItem(string owner, int itemID); + + /// + /// Mints an item + /// + public void MintItem(); + + /// + /// Get account balance + /// + /// callback that takes the retrieved balance (int) + public void GetBalance(Action callback); + + /// + /// Get soft currency balance + /// + /// callback that takes the retrieved balance (int) + public void GetSoftBalance(Action callback); + + /// + /// Returns the address of the current active wallet + /// + /// + public string GetActiveAccountAddress(); + + public void Login(WalletProviderType walletProvider); + + /// + /// Transfers an item to an account address + /// + /// ID of the item that will be transfered + /// amount of the item to be transfered + /// address of the user that will receive the item + /// callback takes a bool (true if the transfer is completed successfully) + public void TransferItem(int itemID, int amount, string address); + + /// + /// Transfers an item from the inventory to the market + /// + /// ID of the item that will be added to the market + /// price of the item on the market + /// callback takes a bool (true if the process is completed successfully) + public void AddItemToMarket(int itemID, int price); + + /// + /// Transfers an item from the market to the inventory + /// + /// ID of the item that will be transfered + /// callback takes a bool (true if the process is completed successfully) + public void RemoveItemFromMarket(int itemID); + + /// + /// Return the Tezos wallet MessageReceiver for using callbacks + /// + public BeaconMessageReceiver GetMessageReceiver(); + + /// + /// Checks if item is on the marketplace in the blockchain + /// + /// + /// + /// + public void IsItemOnMarket(int itemID, string owner, Action callback); + + /// + /// Sends a request to sign a payload + /// + /// + /// + void RequestSignPayload(SignPayloadType signingType, string payload); + + bool VerifyPayload(SignPayloadType signingType, string payload); + } } \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/IItemModel.cs b/Samples~/Scripts/DemoExample/Core/IItemModel.cs index 934a46ca..33e2c7ee 100644 --- a/Samples~/Scripts/DemoExample/Core/IItemModel.cs +++ b/Samples~/Scripts/DemoExample/Core/IItemModel.cs @@ -1,42 +1,46 @@ - -public interface IItemModel -{ - public ItemType Type { get; } - public string ResourcePath { get; } - public string Name { get; } - public StatParams Stats { get; } - public int ID { get; } - public float Price { get; } - public string Owner { get; } -} - -public enum ItemType +namespace TezosSDK.Samples.DemoExample { - Head, - Torso, - Legs, - Feet, - Hand, - Accessory, - Consumable -} + public interface IItemModel + { + public ItemType Type { get; } + public string ResourcePath { get; } + public string Name { get; } + public StatParams Stats { get; } + public int ID { get; } + public float Price { get; } + public string Owner { get; } + } -public class StatParams -{ - public StatParams() { } - - public StatParams(float damage, float armor, float attackSpeed, float healthPoints, float manaPoints) + public enum ItemType { - Damage = damage; - Armor = armor; - AttackSpeed = attackSpeed; - HealthPoints = healthPoints; - ManaPoints = manaPoints; + Head, + Torso, + Legs, + Feet, + Hand, + Accessory, + Consumable } - public float Damage { get; set; } = 0; - public float Armor { get; set; } = 0; - public float AttackSpeed { get; set; } = 0; - public float HealthPoints { get; set; } = 0; - public float ManaPoints { get; set; } = 0; + public class StatParams + { + public StatParams() + { + } + + public StatParams(float damage, float armor, float attackSpeed, float healthPoints, float manaPoints) + { + Damage = damage; + Armor = armor; + AttackSpeed = attackSpeed; + HealthPoints = healthPoints; + ManaPoints = manaPoints; + } + + public float Damage { get; set; } = 0; + public float Armor { get; set; } = 0; + public float AttackSpeed { get; set; } = 0; + public float HealthPoints { get; set; } = 0; + public float ManaPoints { get; set; } = 0; + } } \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/IUserModel.cs b/Samples~/Scripts/DemoExample/Core/IUserModel.cs index e2458f9f..dd85a20f 100644 --- a/Samples~/Scripts/DemoExample/Core/IUserModel.cs +++ b/Samples~/Scripts/DemoExample/Core/IUserModel.cs @@ -1,6 +1,8 @@ - -public interface IUserModel +namespace TezosSDK.Samples.DemoExample { - public string Name { get; } - public string Identifier { get; } -} + public interface IUserModel + { + public string Name { get; } + public string Identifier { get; } + } +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/Item.cs b/Samples~/Scripts/DemoExample/Core/Item.cs index fa5680ae..7cc7820a 100644 --- a/Samples~/Scripts/DemoExample/Core/Item.cs +++ b/Samples~/Scripts/DemoExample/Core/Item.cs @@ -1,23 +1,25 @@ - -public class Item : IItemModel +namespace TezosSDK.Samples.DemoExample { - public Item(ItemType type, string resourcePath, string name, StatParams parameters, float price, int id, string owner) + public class Item : IItemModel { - Type = type; - ResourcePath = resourcePath; - Name = name; - Stats = parameters; - Price = price; - ID = id; - Owner = owner; - } + public Item(ItemType type, string resourcePath, string name, StatParams parameters, float price, int id, string owner) + { + Type = type; + ResourcePath = resourcePath; + Name = name; + Stats = parameters; + Price = price; + ID = id; + Owner = owner; + } - public ItemType Type { get; } - public string ResourcePath { get; } - public string Name { get; } - public StatParams Stats { get; } - - public float Price { get; } - public int ID { get; } - public string Owner { get; } -} + public ItemType Type { get; } + public string ResourcePath { get; } + public string Name { get; } + public StatParams Stats { get; } + + public float Price { get; } + public int ID { get; } + public string Owner { get; } + } +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/Core/User.cs b/Samples~/Scripts/DemoExample/Core/User.cs index 916706a3..72d678d1 100644 --- a/Samples~/Scripts/DemoExample/Core/User.cs +++ b/Samples~/Scripts/DemoExample/Core/User.cs @@ -1,18 +1,21 @@ -public class User : IUserModel +namespace TezosSDK.Samples.DemoExample { - public User(string name, string id, string address) + public class User : IUserModel { - Name = name; - Identifier = id; - Address = address; - } - - public string Name { get; } - public string Identifier { get; } - public string Address { get; private set; } + public User(string name, string id, string address) + { + Name = name; + Identifier = id; + Address = address; + } - public void UpdateAddress(string address) - { - Address = address; + public string Name { get; } + public string Identifier { get; } + public string Address { get; private set; } + + public void UpdateAddress(string address) + { + Address = address; + } } } diff --git a/Samples~/Scripts/DemoExample/ExampleFactory.cs b/Samples~/Scripts/DemoExample/ExampleFactory.cs index a9e1760a..95d84d51 100644 --- a/Samples~/Scripts/DemoExample/ExampleFactory.cs +++ b/Samples~/Scripts/DemoExample/ExampleFactory.cs @@ -1,23 +1,26 @@ using UnityEngine; -public class ExampleFactory : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - public static ExampleFactory Instance; - private IExampleManager _exampleManager = null; - - private void Awake() + public class ExampleFactory : MonoBehaviour { - if (Instance == null) - Instance = this; - else if(Instance != this) - Destroy(this); - - _exampleManager = new ExampleManager(); - _exampleManager.Init(); - } + public static ExampleFactory Instance; + private IExampleManager _exampleManager = null; - public IExampleManager GetExampleManager() - { - return _exampleManager; + private void Awake() + { + if (Instance == null) + Instance = this; + else if (Instance != this) + Destroy(this); + + _exampleManager = new ExampleManager(); + _exampleManager.Init(); + } + + public IExampleManager GetExampleManager() + { + return _exampleManager; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/InventoryManager.cs b/Samples~/Scripts/DemoExample/InventoryManager.cs index b47d44f8..805ff7c1 100644 --- a/Samples~/Scripts/DemoExample/InventoryManager.cs +++ b/Samples~/Scripts/DemoExample/InventoryManager.cs @@ -3,214 +3,221 @@ using UnityEngine.Events; using Logger = TezosSDK.Helpers.Logger; - -[RequireComponent(typeof(SnapController))] -public class InventoryManager : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - public UnityEvent onItemMint; - public UnityEvent onInventoryRefresh; - - [SerializeField] private Draggable itemPrefab; - [SerializeField] private List inventorySlots; - [SerializeField] private List equippedSlots; - [SerializeField] private List draggables = new List(); - [SerializeField] private StatsView statsView; - [SerializeField] private ItemView itemView; - - private Dictionary _itemIDtoDraggable = new Dictionary(); - private SnapController _snapController; - private List _lastHeldItems = new List(); - - private const string PlayerPrefsInvKey = "_inv_"; - private const string PlayerPrefsEquipKey = "_eq_"; - - private void Start() + [RequireComponent(typeof(SnapController))] + public class InventoryManager : MonoBehaviour { - _snapController = GetComponent(); - } + public UnityEvent onItemMint; + public UnityEvent onInventoryRefresh; - private void OnApplicationQuit() - { - // no need for local storage, since data need to be coming from the blockchain - //SaveInventoryLocally(); - } + [SerializeField] private Draggable itemPrefab; + [SerializeField] private List inventorySlots; + [SerializeField] private List equippedSlots; + [SerializeField] private List draggables = new List(); + [SerializeField] private StatsView statsView; + [SerializeField] private ItemView itemView; - public void Init(List items) - { - //ClearInventory(); - UpdateItems(items); - UpdateSnapController(); - - // no need for local storage, since data need to be coming from the blockchain - //LoadLocalInventory(); - } + private Dictionary _itemIDtoDraggable = new Dictionary(); + private SnapController _snapController; + private List _lastHeldItems = new List(); - private void AddItem(IItemModel itemModel) - { - Draggable newItem = Instantiate(itemPrefab, this.transform); - ItemReseource itemRes = Resources.Load(itemModel.ResourcePath); - if (itemRes != null) - newItem.Sprite = itemRes.ItemSprite; - else - Logger.LogError("Could find resource file for " + itemModel.ResourcePath); - newItem.Item = itemModel; - newItem.OnClick = OnItemClicked; - draggables.Add(newItem); - ItemSnapPoint emptySlot = GetFirstEmptySlot(); - if (emptySlot != null) + private const string PlayerPrefsInvKey = "_inv_"; + private const string PlayerPrefsEquipKey = "_eq_"; + + private void Start() { - newItem.SetCurrentSlot(emptySlot); - _itemIDtoDraggable[itemModel.ID] = newItem; + _snapController = GetComponent(); } - else + + private void OnApplicationQuit() { - Logger.LogError("Trying to add an item but Inventory is full!"); - return; + // no need for local storage, since data need to be coming from the blockchain + //SaveInventoryLocally(); } - } - /// - /// Adds any missing items and removes any items that should be gone. - /// - public void UpdateItems(List items) - { - ClearInventory(); - UpdateStatsView(); - _lastHeldItems.Clear(); - foreach (IItemModel item in items) + public void Init(List items) { - _lastHeldItems.Add(item.ID); - if (!_itemIDtoDraggable.ContainsKey(item.ID)) - { - AddItem(item); - } + //ClearInventory(); + UpdateItems(items); + UpdateSnapController(); + + // no need for local storage, since data need to be coming from the blockchain + //LoadLocalInventory(); } - foreach (var itemToRemove in _itemIDtoDraggable) + private void AddItem(IItemModel itemModel) { - if (!_lastHeldItems.Contains(itemToRemove.Value.Item.ID)) + Draggable newItem = Instantiate(itemPrefab, this.transform); + ItemReseource itemRes = Resources.Load(itemModel.ResourcePath); + if (itemRes != null) + newItem.Sprite = itemRes.ItemSprite; + else + Logger.LogError("Could find resource file for " + itemModel.ResourcePath); + newItem.Item = itemModel; + newItem.OnClick = OnItemClicked; + draggables.Add(newItem); + ItemSnapPoint emptySlot = GetFirstEmptySlot(); + if (emptySlot != null) { - itemToRemove.Value.CurrentSlot.RemoveItemInSlot(); - //Uncertain if RemoveItemInSlot's event also removes the item from the dictionary or not. - //_itemIDtoDraggable.Remove(itemToRemove.Key); + newItem.SetCurrentSlot(emptySlot); + _itemIDtoDraggable[itemModel.ID] = newItem; + } + else + { + Logger.LogError("Trying to add an item but Inventory is full!"); + return; } } - } - private void ClearInventory() - { - foreach (var snapSlot in inventorySlots) + /// + /// Adds any missing items and removes any items that should be gone. + /// + public void UpdateItems(List items) { - snapSlot.RemoveItemInSlot(); - } - - foreach (var snapSlot in equippedSlots) - { - snapSlot.RemoveItemInSlot(); + ClearInventory(); + UpdateStatsView(); + _lastHeldItems.Clear(); + foreach (IItemModel item in items) + { + _lastHeldItems.Add(item.ID); + if (!_itemIDtoDraggable.ContainsKey(item.ID)) + { + AddItem(item); + } + } + + foreach (var itemToRemove in _itemIDtoDraggable) + { + if (!_lastHeldItems.Contains(itemToRemove.Value.Item.ID)) + { + itemToRemove.Value.CurrentSlot.RemoveItemInSlot(); + //Uncertain if RemoveItemInSlot's event also removes the item from the dictionary or not. + //_itemIDtoDraggable.Remove(itemToRemove.Key); + } + } } - - foreach (var draggable in draggables) + + private void ClearInventory() { - Destroy(draggable.gameObject); - } - - draggables.Clear(); - _itemIDtoDraggable.Clear(); - } + foreach (var snapSlot in inventorySlots) + { + snapSlot.RemoveItemInSlot(); + } - private void UpdateSnapController() - { - _snapController.Draggables = draggables; - _snapController.SnapPoints = inventorySlots; - foreach(var slot in equippedSlots) - _snapController.SnapPoints.Add(slot); - } + foreach (var snapSlot in equippedSlots) + { + snapSlot.RemoveItemInSlot(); + } - private ItemSnapPoint GetFirstEmptySlot() - { - foreach (var snapPoint in inventorySlots) - if (!snapPoint.HasItem) - return snapPoint; - return null; - } - - private void SaveInventoryLocally() - { - PlayerPrefs.DeleteAll(); - string playerID = ((ExampleManager)ExampleFactory.Instance.GetExampleManager()).CurrentUser.Identifier; - string invSaveLoc = playerID + PlayerPrefsInvKey; - string eqSaveLoc = playerID + PlayerPrefsEquipKey; - for (int i = 0; i < inventorySlots.Count; i++) + foreach (var draggable in draggables) + { + Destroy(draggable.gameObject); + } + + draggables.Clear(); + _itemIDtoDraggable.Clear(); + } + + private void UpdateSnapController() { - if (inventorySlots[i].HasItem) - PlayerPrefs.SetInt(invSaveLoc + i, inventorySlots[i].CurrentItemInSlot.Item.ID); + _snapController.Draggables = draggables; + _snapController.SnapPoints = inventorySlots; + foreach (var slot in equippedSlots) + _snapController.SnapPoints.Add(slot); } - for (int i = 0; i < equippedSlots.Count; i++) + + private ItemSnapPoint GetFirstEmptySlot() { - if (equippedSlots[i].HasItem) - PlayerPrefs.SetInt(eqSaveLoc + i, equippedSlots[i].CurrentItemInSlot.Item.ID); + foreach (var snapPoint in inventorySlots) + if (!snapPoint.HasItem) + return snapPoint; + return null; } - Logger.LogDebug("Inventory saved locally."); - } - private void LoadLocalInventory() - { - ExampleManager db = (ExampleManager)ExampleFactory.Instance.GetExampleManager(); - string playerID = db.CurrentUser.Identifier; - string invSaveLoc = playerID + PlayerPrefsInvKey; - string eqSaveLoc = playerID + PlayerPrefsEquipKey; - for (int i = 0; i < inventorySlots.Count; i++) + private void SaveInventoryLocally() { - if (PlayerPrefs.HasKey(invSaveLoc + i)) + PlayerPrefs.DeleteAll(); + string playerID = ((ExampleManager) ExampleFactory.Instance.GetExampleManager()).CurrentUser.Identifier; + string invSaveLoc = playerID + PlayerPrefsInvKey; + string eqSaveLoc = playerID + PlayerPrefsEquipKey; + for (int i = 0; i < inventorySlots.Count; i++) { - int itemID = PlayerPrefs.GetInt(invSaveLoc + i); - _itemIDtoDraggable[itemID].SetCurrentSlot(inventorySlots[i]); + if (inventorySlots[i].HasItem) + PlayerPrefs.SetInt(invSaveLoc + i, inventorySlots[i].CurrentItemInSlot.Item.ID); } + + for (int i = 0; i < equippedSlots.Count; i++) + { + if (equippedSlots[i].HasItem) + PlayerPrefs.SetInt(eqSaveLoc + i, equippedSlots[i].CurrentItemInSlot.Item.ID); + } + + Logger.LogDebug("Inventory saved locally."); } - for (int i = 0; i < equippedSlots.Count; i++) + + private void LoadLocalInventory() { - if (PlayerPrefs.HasKey(eqSaveLoc + i)) + ExampleManager db = (ExampleManager) ExampleFactory.Instance.GetExampleManager(); + string playerID = db.CurrentUser.Identifier; + string invSaveLoc = playerID + PlayerPrefsInvKey; + string eqSaveLoc = playerID + PlayerPrefsEquipKey; + for (int i = 0; i < inventorySlots.Count; i++) + { + if (PlayerPrefs.HasKey(invSaveLoc + i)) + { + int itemID = PlayerPrefs.GetInt(invSaveLoc + i); + _itemIDtoDraggable[itemID].SetCurrentSlot(inventorySlots[i]); + } + } + + for (int i = 0; i < equippedSlots.Count; i++) { - int itemID = PlayerPrefs.GetInt(eqSaveLoc + i); - _itemIDtoDraggable[itemID].SetCurrentSlot(equippedSlots[i]); + if (PlayerPrefs.HasKey(eqSaveLoc + i)) + { + int itemID = PlayerPrefs.GetInt(eqSaveLoc + i); + _itemIDtoDraggable[itemID].SetCurrentSlot(equippedSlots[i]); + } } + + Logger.LogDebug("Inventory loaded."); } - Logger.LogDebug("Inventory loaded."); - } - public void UpdateStatsView() - { - StatParams heroStats = new StatParams(); - - foreach (var slot in equippedSlots) + public void UpdateStatsView() { - if (!slot.HasItem) - continue; - StatParams sp = slot.CurrentItemInSlot.Item.Stats; - foreach (var prop in sp.GetType().GetProperties()) + StatParams heroStats = new StatParams(); + + foreach (var slot in equippedSlots) { - float value = (float)prop.GetValue(sp) + (float)prop.GetValue(heroStats); - prop.SetValue(heroStats, value); + if (!slot.HasItem) + continue; + StatParams sp = slot.CurrentItemInSlot.Item.Stats; + foreach (var prop in sp.GetType().GetProperties()) + { + float value = (float) prop.GetValue(sp) + (float) prop.GetValue(heroStats); + prop.SetValue(heroStats, value); + } } + + statsView.DisplayStats(heroStats); } - statsView.DisplayStats(heroStats); - } - public void OnMintButtonClicked() - { - onItemMint.Invoke(); - } + public void OnMintButtonClicked() + { + onItemMint.Invoke(); + } - public void OnRefreshButtonClicked() - { - onInventoryRefresh.Invoke(); - } + public void OnRefreshButtonClicked() + { + onInventoryRefresh.Invoke(); + } - public void OnItemClicked(Draggable item) - { - itemView.transform.parent.gameObject.SetActive(true); - itemView.gameObject.SetActive(true); - itemView.DisplayItem(item.Item, item.Sprite); - itemView.GetComponent().SetItem(item.Item); + public void OnItemClicked(Draggable item) + { + itemView.transform.parent.gameObject.SetActive(true); + itemView.gameObject.SetActive(true); + itemView.DisplayItem(item.Item, item.Sprite); + itemView.GetComponent().SetItem(item.Item); + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/MarketManager.cs b/Samples~/Scripts/DemoExample/MarketManager.cs index 75a40b69..3cf56519 100644 --- a/Samples~/Scripts/DemoExample/MarketManager.cs +++ b/Samples~/Scripts/DemoExample/MarketManager.cs @@ -2,66 +2,70 @@ using System.Security.Cryptography; using UnityEngine; -public class MarketManager : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private ItemView itemViewPrefab; - [SerializeField] private ItemView itemFullDisplay; - [SerializeField] private Transform contentParent; - - private List _marketItems = new List(); - private ItemView _currentSelectedItem; - - public void Init(List items) + public class MarketManager : MonoBehaviour { - ClearMarket(); - - foreach (var item in items) - AddItem(item); - } + [SerializeField] private ItemView itemViewPrefab; + [SerializeField] private ItemView itemFullDisplay; + [SerializeField] private Transform contentParent; - public void CheckSelection() - { - if (_currentSelectedItem == null) return; + private List _marketItems = new List(); + private ItemView _currentSelectedItem; - itemFullDisplay.DisplayItem(null, null); - } - - private void AddItem(IItemModel itemModel) - { - ItemView newItem = Instantiate(itemViewPrefab, contentParent); - newItem.DisplayItem(itemModel); - newItem.OnItemSelected = OnItemSelected; - _marketItems.Add(newItem); - } + public void Init(List items) + { + ClearMarket(); - private void ClearMarket() - { - _marketItems = new List(); - foreach (Transform child in contentParent) + foreach (var item in items) + AddItem(item); + } + + public void CheckSelection() + { + if (_currentSelectedItem == null) return; + + itemFullDisplay.DisplayItem(null, null); + } + + private void AddItem(IItemModel itemModel) { - Destroy(child.gameObject); + ItemView newItem = Instantiate(itemViewPrefab, contentParent); + newItem.DisplayItem(itemModel); + newItem.OnItemSelected = OnItemSelected; + _marketItems.Add(newItem); } - CheckSelection(); - } - private void OnItemSelected(ItemView selectedItem) - { - if (_currentSelectedItem != null) - _currentSelectedItem.Unselect(); + private void ClearMarket() + { + _marketItems = new List(); + foreach (Transform child in contentParent) + { + Destroy(child.gameObject); + } - if (_currentSelectedItem == selectedItem) + CheckSelection(); + } + + private void OnItemSelected(ItemView selectedItem) { - selectedItem.Unselect(); + if (_currentSelectedItem != null) + _currentSelectedItem.Unselect(); + + if (_currentSelectedItem == selectedItem) + { + selectedItem.Unselect(); + if (itemFullDisplay != null) + itemFullDisplay.ClearItem(); + _currentSelectedItem = null; + return; + } + + selectedItem.Select(); + _currentSelectedItem = selectedItem; if (itemFullDisplay != null) - itemFullDisplay.ClearItem(); - _currentSelectedItem = null; - return; + itemFullDisplay.DisplayItem(selectedItem.Item, selectedItem.CachedSprite); + itemFullDisplay.GetComponent().SetItem(selectedItem.Item); } - - selectedItem.Select(); - _currentSelectedItem = selectedItem; - if (itemFullDisplay != null) - itemFullDisplay.DisplayItem(selectedItem.Item, selectedItem.CachedSprite); - itemFullDisplay.GetComponent().SetItem(selectedItem.Item); } } diff --git a/Samples~/Scripts/DemoExample/UI/Draggable.cs b/Samples~/Scripts/DemoExample/UI/Draggable.cs index 79d1112e..4d81d026 100644 --- a/Samples~/Scripts/DemoExample/UI/Draggable.cs +++ b/Samples~/Scripts/DemoExample/UI/Draggable.cs @@ -3,68 +3,71 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public class Draggable : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IEndDragHandler, IDragHandler +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private ItemSnapPoint _currentSlot; - [SerializeField] private Image image; - - public IItemModel Item { get; set; } - public Action OnBeginDragging; - public Action OnEndDragging; - public Action OnClick; - public ItemSnapPoint CurrentSlot => _currentSlot; - - public Sprite Sprite + public class Draggable : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IEndDragHandler, IDragHandler { - get { return image.sprite; } - set { image.sprite = value; } - } + [SerializeField] private ItemSnapPoint _currentSlot; + [SerializeField] private Image image; - private bool _isDragging = false; + public IItemModel Item { get; set; } + public Action OnBeginDragging; + public Action OnEndDragging; + public Action OnClick; + public ItemSnapPoint CurrentSlot => _currentSlot; - private void Start() - { - if (_currentSlot != null) - ResetPosition(); - } + public Sprite Sprite + { + get { return image.sprite; } + set { image.sprite = value; } + } - public void OnPointerClick(PointerEventData eventData) - { - if(!_isDragging) - OnClick?.Invoke(this); - } + private bool _isDragging = false; - public void OnBeginDrag(PointerEventData eventData) - { - _isDragging = true; - OnBeginDragging?.Invoke(this); - } + private void Start() + { + if (_currentSlot != null) + ResetPosition(); + } - public void OnEndDrag(PointerEventData eventData) - { - _isDragging = false; - OnEndDragging?.Invoke(this); - } + public void OnPointerClick(PointerEventData eventData) + { + if (!_isDragging) + OnClick?.Invoke(this); + } - public void OnDrag(PointerEventData eventData) - { - transform.position = Input.mousePosition; - } + public void OnBeginDrag(PointerEventData eventData) + { + _isDragging = true; + OnBeginDragging?.Invoke(this); + } - public void SetCurrentSlot(ItemSnapPoint slot) - { - ItemSnapPoint prevSlot = _currentSlot; - _currentSlot = slot; - _currentSlot.SetItemInSlot(this); - transform.position = _currentSlot.transform.position; - if (prevSlot != null) - prevSlot.RemoveItemInSlot(); - } + public void OnEndDrag(PointerEventData eventData) + { + _isDragging = false; + OnEndDragging?.Invoke(this); + } - public void ResetPosition() - { - _currentSlot.SetItemInSlot(this); - if (_currentSlot != null) + public void OnDrag(PointerEventData eventData) + { + transform.position = Input.mousePosition; + } + + public void SetCurrentSlot(ItemSnapPoint slot) + { + ItemSnapPoint prevSlot = _currentSlot; + _currentSlot = slot; + _currentSlot.SetItemInSlot(this); transform.position = _currentSlot.transform.position; + if (prevSlot != null) + prevSlot.RemoveItemInSlot(); + } + + public void ResetPosition() + { + _currentSlot.SetItemInSlot(this); + if (_currentSlot != null) + transform.position = _currentSlot.transform.position; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/DraggableItemVisual.cs b/Samples~/Scripts/DemoExample/UI/DraggableItemVisual.cs index 996fdb8e..35fc7f0b 100644 --- a/Samples~/Scripts/DemoExample/UI/DraggableItemVisual.cs +++ b/Samples~/Scripts/DemoExample/UI/DraggableItemVisual.cs @@ -3,73 +3,76 @@ using UnityEngine; using UnityEngine.EventSystems; -[System.Obsolete] -public class DraggableItemVisual : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IEndDragHandler, IDragHandler +namespace TezosSDK.Samples.DemoExample { - private ItemSlot _curSlot; - - /// - /// Set the current slot - /// - /// The slot to be set to - public void SetSlot(ItemSlot slot) + [System.Obsolete] + public class DraggableItemVisual : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IEndDragHandler, IDragHandler { - _curSlot = slot; - } + private ItemSlot _curSlot; - //Sets the Item placement and size to be that of the slot - public void SetItemPlacement(ItemSlot slot) - { - transform.SetParent(slot.ItemSpace); - RectTransform rect = GetComponent(); - rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 0); - rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, 0); - rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0); - rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0); - } + /// + /// Set the current slot + /// + /// The slot to be set to + public void SetSlot(ItemSlot slot) + { + _curSlot = slot; + } - public void OnPointerClick(PointerEventData eventData) - { - - } + //Sets the Item placement and size to be that of the slot + public void SetItemPlacement(ItemSlot slot) + { + transform.SetParent(slot.ItemSpace); + RectTransform rect = GetComponent(); + rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 0); + rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, 0); + rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0); + rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0); + } - public void OnBeginDrag(PointerEventData eventData) - { - - } + public void OnPointerClick(PointerEventData eventData) + { - public void OnEndDrag(PointerEventData eventData) - { - //look through all things under draggable - RaycastHit[] hits; - RaycastHit hit; - ItemSlot slot = null; - var rayPosition = Input.mousePosition; - rayPosition.z -= 10; - hits = Physics.RaycastAll(rayPosition, transform.forward, 100.0f); - for (int i = 0; i < hits.Length; i++) + } + + public void OnBeginDrag(PointerEventData eventData) { - slot = null; - hit = hits[i]; - slot = hit.transform.GetComponent(); - if (slot == null) - { - continue; - } - //If the draggable is over a slot, check to see if it's open and if so, assign it to it - if (slot.ItemInSlot != null) + } + + public void OnEndDrag(PointerEventData eventData) + { + //look through all things under draggable + RaycastHit[] hits; + RaycastHit hit; + ItemSlot slot = null; + var rayPosition = Input.mousePosition; + rayPosition.z -= 10; + hits = Physics.RaycastAll(rayPosition, transform.forward, 100.0f); + for (int i = 0; i < hits.Length; i++) { - _curSlot.SetToSlot(this); - return; - } + slot = null; + hit = hits[i]; + slot = hit.transform.GetComponent(); + if (slot == null) + { + continue; + } + + //If the draggable is over a slot, check to see if it's open and if so, assign it to it + if (slot.ItemInSlot != null) + { + _curSlot.SetToSlot(this); + return; + } - slot.SetToSlot(this); + slot.SetToSlot(this); + } } - } - public void OnDrag(PointerEventData eventData) - { - transform.position = Input.mousePosition; + public void OnDrag(PointerEventData eventData) + { + transform.position = Input.mousePosition; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/FlexibleGridLayout.cs b/Samples~/Scripts/DemoExample/UI/FlexibleGridLayout.cs index d5d04ec2..51aa9e0b 100644 --- a/Samples~/Scripts/DemoExample/UI/FlexibleGridLayout.cs +++ b/Samples~/Scripts/DemoExample/UI/FlexibleGridLayout.cs @@ -1,88 +1,92 @@ using UnityEngine; using UnityEngine.UI; -public class FlexibleGridLayout : LayoutGroup +namespace TezosSDK.Samples.DemoExample { - public enum FitType - { - Uniform, - Width, - Height, - FixedRows, - FixedColumns - } - - [SerializeField] FitType _fitType = FitType.Uniform; - [SerializeField, Min(1)] private int _rows; - [SerializeField, Min(1)] private int _columns; - [SerializeField] private Vector2 _cellSize; - [SerializeField] private Vector2 _spacing; - - [SerializeField] private bool _fitX; - [SerializeField] private bool _fitY; - - /// - /// Calculates and updates the placement of grid elements based on parameters - /// - public override void CalculateLayoutInputHorizontal() + public class FlexibleGridLayout : LayoutGroup { - base.CalculateLayoutInputHorizontal(); - - if (_fitType == FitType.Uniform || _fitType == FitType.Width || _fitType == FitType.Height) + public enum FitType { - float sqrt = Mathf.Sqrt(transform.childCount); - _rows = Mathf.CeilToInt(sqrt); - _columns = Mathf.CeilToInt(sqrt); + Uniform, + Width, + Height, + FixedRows, + FixedColumns } - if (_fitType == FitType.Width || _fitType == FitType.FixedColumns) - { - _rows = Mathf.CeilToInt(transform.childCount / (float)_columns); - } - if (_fitType == FitType.Height || _fitType == FitType.FixedRows) + [SerializeField] FitType _fitType = FitType.Uniform; + [SerializeField, Min(1)] private int _rows; + [SerializeField, Min(1)] private int _columns; + [SerializeField] private Vector2 _cellSize; + [SerializeField] private Vector2 _spacing; + + [SerializeField] private bool _fitX; + [SerializeField] private bool _fitY; + + /// + /// Calculates and updates the placement of grid elements based on parameters + /// + public override void CalculateLayoutInputHorizontal() { - _columns = Mathf.CeilToInt(transform.childCount / (float)_rows); - } + base.CalculateLayoutInputHorizontal(); - float parentWidth = rectTransform.rect.width; - float parentHeight = rectTransform.rect.height; + if (_fitType == FitType.Uniform || _fitType == FitType.Width || _fitType == FitType.Height) + { + float sqrt = Mathf.Sqrt(transform.childCount); + _rows = Mathf.CeilToInt(sqrt); + _columns = Mathf.CeilToInt(sqrt); + } - float cellWidth = (parentWidth / (float)_columns) - ((_spacing.x/(float)_columns) * (_columns - 1)) - (padding.left / (float) _columns) - (padding.right / (float) _columns); - float cellHeight = (parentHeight / (float)_rows) - ((_spacing.y / (float)_rows) * (_rows - 1)) - (padding.top / (float)_rows) - (padding.bottom / (float)_rows); + if (_fitType == FitType.Width || _fitType == FitType.FixedColumns) + { + _rows = Mathf.CeilToInt(transform.childCount / (float) _columns); + } - _cellSize.x = _fitX ? cellWidth : _cellSize.x; - _cellSize.y = _fitY ? cellHeight : _cellSize.y; + if (_fitType == FitType.Height || _fitType == FitType.FixedRows) + { + _columns = Mathf.CeilToInt(transform.childCount / (float) _rows); + } - int columnCount = 0; - int rowCount = 0; + float parentWidth = rectTransform.rect.width; + float parentHeight = rectTransform.rect.height; - for (int i = 0; i < rectChildren.Count; i++) - { - rowCount = i / _columns; - columnCount = i % _columns; + float cellWidth = (parentWidth / (float) _columns) - ((_spacing.x / (float) _columns) * (_columns - 1)) - (padding.left / (float) _columns) - (padding.right / (float) _columns); + float cellHeight = (parentHeight / (float) _rows) - ((_spacing.y / (float) _rows) * (_rows - 1)) - (padding.top / (float) _rows) - (padding.bottom / (float) _rows); + + _cellSize.x = _fitX ? cellWidth : _cellSize.x; + _cellSize.y = _fitY ? cellHeight : _cellSize.y; + + int columnCount = 0; + int rowCount = 0; - var item = rectChildren[i]; + for (int i = 0; i < rectChildren.Count; i++) + { + rowCount = i / _columns; + columnCount = i % _columns; - var xPos = (_cellSize.x * columnCount) + (_spacing.x * columnCount) + padding.left; - var yPos = (_cellSize.y * rowCount) + (_spacing.y * rowCount) + padding.top; + var item = rectChildren[i]; - SetChildAlongAxis(item, 0, xPos, _cellSize.x); - SetChildAlongAxis(item, 1, yPos, _cellSize.y); + var xPos = (_cellSize.x * columnCount) + (_spacing.x * columnCount) + padding.left; + var yPos = (_cellSize.y * rowCount) + (_spacing.y * rowCount) + padding.top; + + SetChildAlongAxis(item, 0, xPos, _cellSize.x); + SetChildAlongAxis(item, 1, yPos, _cellSize.y); + } } - } - public override void CalculateLayoutInputVertical() - { - //Unused for now - } + public override void CalculateLayoutInputVertical() + { + //Unused for now + } - public override void SetLayoutHorizontal() - { - //Unused for now - } + public override void SetLayoutHorizontal() + { + //Unused for now + } - public override void SetLayoutVertical() - { - //Unused for now + public override void SetLayoutVertical() + { + //Unused for now + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/ItemController.cs b/Samples~/Scripts/DemoExample/UI/ItemController.cs index 6f8069a9..c77519b1 100644 --- a/Samples~/Scripts/DemoExample/UI/ItemController.cs +++ b/Samples~/Scripts/DemoExample/UI/ItemController.cs @@ -1,65 +1,66 @@ using System; -using System.Collections; -using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; -public class ItemController : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - private IItemModel item; + public class ItemController : MonoBehaviour + { + private IItemModel item; - [SerializeField] private TMPro.TMP_InputField transferAddressInput; - [SerializeField] private TMPro.TMP_InputField amountInput; - [SerializeField] private TMPro.TMP_InputField priceInput; - [SerializeField] private Button transferButton; - [SerializeField] private Button addToMarketButton; - [SerializeField] private Button removeFromMarketButton; + [SerializeField] private TMPro.TMP_InputField transferAddressInput; + [SerializeField] private TMPro.TMP_InputField amountInput; + [SerializeField] private TMPro.TMP_InputField priceInput; + [SerializeField] private Button transferButton; + [SerializeField] private Button addToMarketButton; + [SerializeField] private Button removeFromMarketButton; - private bool _hasMoreThanOneItem = false; - - public void SetItem(IItemModel newItem) - { - item = newItem; - - // is the item already on the market or not - ExampleFactory.Instance.GetExampleManager().IsItemOnMarket(item.ID, item.Owner, OnIsItemOnMarket); - - // check the amount of the item (using the price) - _hasMoreThanOneItem = item.Price > 1; - amountInput.gameObject.SetActive(_hasMoreThanOneItem); - - // reset input fields - transferAddressInput.text = ""; - amountInput.text = ""; - priceInput.text = ""; - } + private bool _hasMoreThanOneItem = false; - public void TransferItem() - { - string destAddress = transferAddressInput.text; - string amountString = amountInput.text; - int amount = 1; - if (_hasMoreThanOneItem) - amount = (amountString == String.Empty)? 1 : int.Parse(amountString); - ExampleFactory.Instance.GetExampleManager().TransferItem(item.ID, amount, destAddress); - } + public void SetItem(IItemModel newItem) + { + item = newItem; - public void AddItemToMarket() - { - int price = int.Parse(priceInput.text); - ExampleFactory.Instance.GetExampleManager().AddItemToMarket(item.ID, price); - } + // is the item already on the market or not + ExampleFactory.Instance.GetExampleManager().IsItemOnMarket(item.ID, item.Owner, OnIsItemOnMarket); - public void RemoveItemFromMarket() - { - ExampleFactory.Instance.GetExampleManager().RemoveItemFromMarket(item.ID); - } - - public void OnIsItemOnMarket(bool success) - { - addToMarketButton.gameObject.SetActive(!success); - removeFromMarketButton.gameObject.SetActive(success); - transferButton.gameObject.SetActive(!success); - priceInput.interactable = !success; + // check the amount of the item (using the price) + _hasMoreThanOneItem = item.Price > 1; + amountInput.gameObject.SetActive(_hasMoreThanOneItem); + + // reset input fields + transferAddressInput.text = ""; + amountInput.text = ""; + priceInput.text = ""; + } + + public void TransferItem() + { + string destAddress = transferAddressInput.text; + string amountString = amountInput.text; + int amount = 1; + if (_hasMoreThanOneItem) + amount = (amountString == String.Empty) ? 1 : int.Parse(amountString); + ExampleFactory.Instance.GetExampleManager().TransferItem(item.ID, amount, destAddress); + } + + public void AddItemToMarket() + { + int price = int.Parse(priceInput.text); + ExampleFactory.Instance.GetExampleManager().AddItemToMarket(item.ID, price); + } + + public void RemoveItemFromMarket() + { + ExampleFactory.Instance.GetExampleManager().RemoveItemFromMarket(item.ID); + } + + public void OnIsItemOnMarket(bool success) + { + addToMarketButton.gameObject.SetActive(!success); + removeFromMarketButton.gameObject.SetActive(success); + transferButton.gameObject.SetActive(!success); + priceInput.interactable = !success; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/ItemSlot.cs b/Samples~/Scripts/DemoExample/UI/ItemSlot.cs index 965c8ba0..a7100f99 100644 --- a/Samples~/Scripts/DemoExample/UI/ItemSlot.cs +++ b/Samples~/Scripts/DemoExample/UI/ItemSlot.cs @@ -1,31 +1,34 @@ using UnityEngine; using UnityEngine.UI; -[System.Obsolete] -[RequireComponent(typeof(Image))] -public class ItemSlot : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private Transform _itemSpace; + [System.Obsolete] + [RequireComponent(typeof(Image))] + public class ItemSlot : MonoBehaviour + { + [SerializeField] private Transform _itemSpace; - public Transform ItemSpace => _itemSpace; + public Transform ItemSpace => _itemSpace; - public DraggableItemVisual ItemInSlot => _itemInSlot; + public DraggableItemVisual ItemInSlot => _itemInSlot; - private DraggableItemVisual _itemInSlot; + private DraggableItemVisual _itemInSlot; - /// - /// assigns an item to slot and lets the item know what slot it's set to - /// - /// The item to be asigned to this slot - public void SetToSlot(DraggableItemVisual item) - { - if (_itemInSlot != item) + /// + /// assigns an item to slot and lets the item know what slot it's set to + /// + /// The item to be asigned to this slot + public void SetToSlot(DraggableItemVisual item) { - _itemInSlot = item; - _itemInSlot.SetSlot(this); - } + if (_itemInSlot != item) + { + _itemInSlot = item; + _itemInSlot.SetSlot(this); + } - item.SetItemPlacement(this); + item.SetItemPlacement(this); + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/ItemSnapPoint.cs b/Samples~/Scripts/DemoExample/UI/ItemSnapPoint.cs index b92d090a..60126ada 100644 --- a/Samples~/Scripts/DemoExample/UI/ItemSnapPoint.cs +++ b/Samples~/Scripts/DemoExample/UI/ItemSnapPoint.cs @@ -1,65 +1,65 @@ using UnityEngine; -using System; using System.Linq; using UnityEngine.Events; -using UnityEngine.EventSystems; using UnityEngine.UI; -[RequireComponent(typeof(Image))] -public class ItemSnapPoint : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private bool snappable = true; - [SerializeField] private bool allowAllItemTypes = true; - [SerializeField] private ItemType[] allowedTypes; + [RequireComponent(typeof(Image))] + public class ItemSnapPoint : MonoBehaviour + { + [SerializeField] private bool snappable = true; + [SerializeField] private bool allowAllItemTypes = true; + [SerializeField] private ItemType[] allowedTypes; - private Draggable _currentItemInSlot; - private Image _image; - private bool _highledEnabled = true; - private Color _originalColor; - private Color _highlightColor; + private Draggable _currentItemInSlot; + private Image _image; + private bool _highledEnabled = true; + private Color _originalColor; + private Color _highlightColor; - public bool AllowsAllItemTypes => allowAllItemTypes; - public bool HasItem => _currentItemInSlot != null; - public bool IsSnappable => snappable; - public Draggable CurrentItemInSlot => _currentItemInSlot; - - [Header("Events:")] - [SerializeField] public UnityEvent OnItemSet; - [SerializeField] public UnityEvent OnItemRemoved; + public bool AllowsAllItemTypes => allowAllItemTypes; + public bool HasItem => _currentItemInSlot != null; + public bool IsSnappable => snappable; + public Draggable CurrentItemInSlot => _currentItemInSlot; - private void Start() - { - _image = GetComponent(); - _originalColor = _image.color; - _highlightColor = Color.white; - } + [Header("Events:")] [SerializeField] public UnityEvent OnItemSet; + [SerializeField] public UnityEvent OnItemRemoved; - public void SetItemInSlot(Draggable item) - { - _currentItemInSlot = item; - OnItemSet?.Invoke(); - } + private void Start() + { + _image = GetComponent(); + _originalColor = _image.color; + _highlightColor = Color.white; + } - public void RemoveItemInSlot() - { - _currentItemInSlot = null; - OnItemRemoved?.Invoke(); - } + public void SetItemInSlot(Draggable item) + { + _currentItemInSlot = item; + OnItemSet?.Invoke(); + } - public void Highlight(bool highlight) - { - _image.color = (highlight) ? _highlightColor : _originalColor; - } + public void RemoveItemInSlot() + { + _currentItemInSlot = null; + OnItemRemoved?.Invoke(); + } - public void EnableHighlighting(bool enable) - { - _highledEnabled = enable; - if (!_highledEnabled) - _image.color = _originalColor; - } + public void Highlight(bool highlight) + { + _image.color = (highlight) ? _highlightColor : _originalColor; + } - public bool AcceptsItem(IItemModel item) - { - return allowedTypes.Contains(item.Type); + public void EnableHighlighting(bool enable) + { + _highledEnabled = enable; + if (!_highledEnabled) + _image.color = _originalColor; + } + + public bool AcceptsItem(IItemModel item) + { + return allowedTypes.Contains(item.Type); + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/ItemView.cs b/Samples~/Scripts/DemoExample/UI/ItemView.cs index 09809d03..af84b35f 100644 --- a/Samples~/Scripts/DemoExample/UI/ItemView.cs +++ b/Samples~/Scripts/DemoExample/UI/ItemView.cs @@ -4,99 +4,103 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public class ItemView : MonoBehaviour, IPointerClickHandler +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private Image backgroundImage; - [SerializeField] private Image itemImage; - [SerializeField] private TMPro.TextMeshProUGUI priceText; - [SerializeField] private TMPro.TextMeshProUGUI nameText; - [SerializeField] private TMPro.TextMeshProUGUI typeText; - [SerializeField] private StatsView statsView; - [SerializeField] private Color selectColor = Color.white; - [SerializeField] private Sprite defaultImage; + public class ItemView : MonoBehaviour, IPointerClickHandler + { + [SerializeField] private Image backgroundImage; + [SerializeField] private Image itemImage; + [SerializeField] private TMPro.TextMeshProUGUI priceText; + [SerializeField] private TMPro.TextMeshProUGUI nameText; + [SerializeField] private TMPro.TextMeshProUGUI typeText; + [SerializeField] private StatsView statsView; + [SerializeField] private Color selectColor = Color.white; + [SerializeField] private Sprite defaultImage; - private IItemModel _item; - private Color _originalBackgroundColor; - private Sprite _cachedSprite; - private Sprite _initSprite; + private IItemModel _item; + private Color _originalBackgroundColor; + private Sprite _cachedSprite; + private Sprite _initSprite; - public IItemModel Item => _item; - public Action OnItemSelected; - public Sprite CachedSprite => _cachedSprite; + public IItemModel Item => _item; + public Action OnItemSelected; + public Sprite CachedSprite => _cachedSprite; - private void Start() - { - _originalBackgroundColor = backgroundImage.color; - _initSprite = itemImage.sprite; - } - - public void DisplayItem(IItemModel item, Sprite cahcedSprite = null) - { - if (item == null) + private void Start() { - Debug.LogWarning("item in market currently null -test message-"); - - priceText.text = "Price"; - nameText.text = "Name"; - typeText.text = "[Type]"; - StatParams statParams = new StatParams(0, 0, 0, 0, 0); - statsView.DisplayStats(statParams); - itemImage.sprite = _initSprite; - return; + _originalBackgroundColor = backgroundImage.color; + _initSprite = itemImage.sprite; } - else - { - if (priceText != null) - priceText.text = item.Price.ToString(CultureInfo.InvariantCulture); - if (nameText != null) - nameText.text = item.Name; - if (typeText != null) - typeText.text = item.Type.ToString(); - if (statsView != null) - statsView.DisplayStats(item.Stats); - if (cahcedSprite != null) + public void DisplayItem(IItemModel item, Sprite cahcedSprite = null) + { + if (item == null) { - itemImage.sprite = cahcedSprite; - _cachedSprite = itemImage.sprite; + Debug.LogWarning("item in market currently null -test message-"); + + priceText.text = "Price"; + nameText.text = "Name"; + typeText.text = "[Type]"; + StatParams statParams = new StatParams(0, 0, 0, 0, 0); + statsView.DisplayStats(statParams); + itemImage.sprite = _initSprite; + return; } - else if (itemImage != null) + else { - ItemReseource itemRes = Resources.Load(item.ResourcePath); - itemImage.sprite = itemRes.ItemSprite; - _cachedSprite = itemImage.sprite; + + if (priceText != null) + priceText.text = item.Price.ToString(CultureInfo.InvariantCulture); + if (nameText != null) + nameText.text = item.Name; + if (typeText != null) + typeText.text = item.Type.ToString(); + if (statsView != null) + statsView.DisplayStats(item.Stats); + if (cahcedSprite != null) + { + itemImage.sprite = cahcedSprite; + _cachedSprite = itemImage.sprite; + } + else if (itemImage != null) + { + ItemReseource itemRes = Resources.Load(item.ResourcePath); + itemImage.sprite = itemRes.ItemSprite; + _cachedSprite = itemImage.sprite; + } } + + _item = item; } - _item = item; - } - public void OnPointerClick(PointerEventData eventData) - { - OnItemSelected?.Invoke(this); - } + public void OnPointerClick(PointerEventData eventData) + { + OnItemSelected?.Invoke(this); + } - public void Select() - { - backgroundImage.color = selectColor; - } + public void Select() + { + backgroundImage.color = selectColor; + } - public void Unselect() - { - backgroundImage.color = _originalBackgroundColor; - } + public void Unselect() + { + backgroundImage.color = _originalBackgroundColor; + } - public void ClearItem() - { - if (priceText != null) - priceText.text = string.Empty; - if (nameText != null) - nameText.text = string.Empty; - if (typeText != null) - typeText.text = string.Empty; - if (itemImage != null) - itemImage.sprite = defaultImage; - if (statsView != null) - statsView.Clear(); - _item = null; + public void ClearItem() + { + if (priceText != null) + priceText.text = string.Empty; + if (nameText != null) + nameText.text = string.Empty; + if (typeText != null) + typeText.text = string.Empty; + if (itemImage != null) + itemImage.sprite = defaultImage; + if (statsView != null) + statsView.Clear(); + _item = null; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/MarketItemController.cs b/Samples~/Scripts/DemoExample/UI/MarketItemController.cs index ee1ed8b4..34dd1918 100644 --- a/Samples~/Scripts/DemoExample/UI/MarketItemController.cs +++ b/Samples~/Scripts/DemoExample/UI/MarketItemController.cs @@ -3,32 +3,35 @@ using UnityEngine; using UnityEngine.UI; -public class MarketItemController : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - private IItemModel item; - - public void SetItem(IItemModel newItem) + public class MarketItemController : MonoBehaviour { - item = newItem; - } + private IItemModel item; - public void BuyItemFromMarket() - { - if(item != null) - ExampleFactory.Instance.GetExampleManager().BuyItem(item.Owner, item.ID); - else - Debug.LogError("No item selected!"); - } - - public void OnItemBoughtFromMarket(bool success) - { - if (success) + public void SetItem(IItemModel newItem) { - Debug.Log("Item removed from market!"); + item = newItem; } - else + + public void BuyItemFromMarket() + { + if (item != null) + ExampleFactory.Instance.GetExampleManager().BuyItem(item.Owner, item.ID); + else + Debug.LogError("No item selected!"); + } + + public void OnItemBoughtFromMarket(bool success) { - Debug.Log("Failed to remove item from market."); + if (success) + { + Debug.Log("Item removed from market!"); + } + else + { + Debug.Log("Failed to remove item from market."); + } } } } diff --git a/Samples~/Scripts/DemoExample/UI/PanelController.cs b/Samples~/Scripts/DemoExample/UI/PanelController.cs index 741b7350..4fe57dab 100644 --- a/Samples~/Scripts/DemoExample/UI/PanelController.cs +++ b/Samples~/Scripts/DemoExample/UI/PanelController.cs @@ -1,5 +1,8 @@ using UnityEngine; -public class PanelController : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { -} + public class PanelController : MonoBehaviour + { + } +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/RegisterPanel.cs b/Samples~/Scripts/DemoExample/UI/RegisterPanel.cs index db636c67..021bc514 100644 --- a/Samples~/Scripts/DemoExample/UI/RegisterPanel.cs +++ b/Samples~/Scripts/DemoExample/UI/RegisterPanel.cs @@ -1,87 +1,91 @@ using System.Collections; using Beacon.Sdk.Beacon.Sign; using TezosSDK.Tezos.Wallet; +using TezosSDK.View; using UnityEngine; using UnityEngine.UI; -public class RegisterPanel : PanelController +namespace TezosSDK.Samples.DemoExample { - [SerializeField, Header("Components")] private Button _deepLinkPair; - [SerializeField, Header("Components")] private Button _socialLoginButton; - [SerializeField] private RawImage _qrImage; - [SerializeField] private QRCodeView _qrCodeView; - [SerializeField, Header("Manager")] private UIManager _uiManager; + public class RegisterPanel : PanelController + { + [SerializeField, Header("Components")] private Button _deepLinkPair; + [SerializeField, Header("Components")] private Button _socialLoginButton; + [SerializeField] private RawImage _qrImage; + [SerializeField] private QRCodeView _qrCodeView; + [SerializeField, Header("Manager")] private UIManager _uiManager; - private IExampleManager _exampleManager; - private const string PayloadToSign = "Tezos Signed Message: mydap.com 2021-01-14T15:16:04Z Hello world!"; + private IExampleManager _exampleManager; + private const string PayloadToSign = "Tezos Signed Message: mydap.com 2021-01-14T15:16:04Z Hello world!"; - private IEnumerator Start() - { - // skip a frame before start accessing Database - yield return null; + private IEnumerator Start() + { + // skip a frame before start accessing Database + yield return null; - _exampleManager = ExampleFactory.Instance.GetExampleManager(); - _exampleManager.GetMessageReceiver().HandshakeReceived += (handshake) => _qrCodeView.SetQrCode(handshake); + _exampleManager = ExampleFactory.Instance.GetExampleManager(); + _exampleManager.GetMessageReceiver().HandshakeReceived += (handshake) => _qrCodeView.SetQrCode(handshake); - SetButtonState(_deepLinkPair, false, false); - SetButtonState(_socialLoginButton, false, false); - _qrImage.gameObject.SetActive(false); + SetButtonState(_deepLinkPair, false, false); + SetButtonState(_socialLoginButton, false, false); + _qrImage.gameObject.SetActive(false); #if UNITY_STANDALONE || UNITY_EDITOR - // make QR code available for Standalone - _qrImage.gameObject.SetActive(true); + // make QR code available for Standalone + _qrImage.gameObject.SetActive(true); #elif (UNITY_IOS || UNITY_ANDROID) SetButtonState(_deepLinkPair, true, true); #elif UNITY_WEBGL SetButtonState(_deepLinkPair, true, true); SetButtonState(_socialLoginButton, true, true); #endif - } + } - /// - /// For use on Deep Link connection button to pair to an on device wallet. - /// - public void DeepLinkPair() - { - _exampleManager.Login(WalletProviderType.beacon); - } + /// + /// For use on Deep Link connection button to pair to an on device wallet. + /// + public void DeepLinkPair() + { + _exampleManager.Login(WalletProviderType.beacon); + } - /// - /// Login with social networks. - /// - public void SocialLoginHandler() - { - _exampleManager.Login(WalletProviderType.kukai); - } + /// + /// Login with social networks. + /// + public void SocialLoginHandler() + { + _exampleManager.Login(WalletProviderType.kukai); + } - /// - /// To unpair from wallets. - /// - public void UnPair() - { - _exampleManager.Unpair(); - } + /// + /// To unpair from wallets. + /// + public void UnPair() + { + _exampleManager.Unpair(); + } - /// - /// Allows to set the button's state in a single line. - /// - /// The button in question. - /// The state of activity of it's GameObject. - /// If the button can be interactable or not. - private void SetButtonState(Button button, bool active, bool interactable) - { - button.gameObject.SetActive(active); - button.interactable = interactable; - } + /// + /// Allows to set the button's state in a single line. + /// + /// The button in question. + /// The state of activity of it's GameObject. + /// If the button can be interactable or not. + private void SetButtonState(Button button, bool active, bool interactable) + { + button.gameObject.SetActive(active); + button.interactable = interactable; + } - public void SignPayloadTest() - { - ExampleFactory.Instance.GetExampleManager().RequestSignPayload(SignPayloadType.micheline, PayloadToSign); - } + public void SignPayloadTest() + { + ExampleFactory.Instance.GetExampleManager().RequestSignPayload(SignPayloadType.micheline, PayloadToSign); + } - public void VerifySignatureTest() - { - var verified = ExampleFactory.Instance.GetExampleManager() - .VerifyPayload(SignPayloadType.micheline, PayloadToSign); - Debug.Log("Verification success: " + verified); + public void VerifySignatureTest() + { + var verified = ExampleFactory.Instance.GetExampleManager() + .VerifyPayload(SignPayloadType.micheline, PayloadToSign); + Debug.Log("Verification success: " + verified); + } } } \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/SnapController.cs b/Samples~/Scripts/DemoExample/UI/SnapController.cs index 711043df..6863e10e 100644 --- a/Samples~/Scripts/DemoExample/UI/SnapController.cs +++ b/Samples~/Scripts/DemoExample/UI/SnapController.cs @@ -1,98 +1,101 @@ using System.Collections.Generic; using UnityEngine; -public class SnapController : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private List snapPoints; - [SerializeField] private List draggables; - [SerializeField] private float snapRange = 100f; + public class SnapController : MonoBehaviour + { + [SerializeField] private List snapPoints; + [SerializeField] private List draggables; + [SerializeField] private float snapRange = 100f; - private ItemSnapPoint _currentHighlighedSlot = null; - private Draggable _currentDraggable = null; - private bool _isDragging = false; + private ItemSnapPoint _currentHighlighedSlot = null; + private Draggable _currentDraggable = null; + private bool _isDragging = false; - private void Update() - { - if (_currentHighlighedSlot != null) - _currentHighlighedSlot.Highlight(false); - - if (_isDragging) + private void Update() { - _currentHighlighedSlot = GetNearestSlotFromMouse(); if (_currentHighlighedSlot != null) - _currentHighlighedSlot.Highlight(true); + _currentHighlighedSlot.Highlight(false); + + if (_isDragging) + { + _currentHighlighedSlot = GetNearestSlotFromMouse(); + if (_currentHighlighedSlot != null) + _currentHighlighedSlot.Highlight(true); + } } - } - public List SnapPoints - { - get => snapPoints; - set => snapPoints = value; - } - - public List Draggables - { - get => draggables; - set + public List SnapPoints + { + get => snapPoints; + set => snapPoints = value; + } + + public List Draggables { - draggables = value; - foreach (var draggable in draggables) + get => draggables; + set { - draggable.OnBeginDragging = OnItemDragBegin; - draggable.OnEndDragging = OnItemDragEnd; + draggables = value; + foreach (var draggable in draggables) + { + draggable.OnBeginDragging = OnItemDragBegin; + draggable.OnEndDragging = OnItemDragEnd; + } } } - } - - public void OnItemDragBegin(Draggable draggable) - { - _isDragging = true; - _currentDraggable = draggable; - } - public void OnItemDragEnd(Draggable draggable) - { - _isDragging = false; - _currentDraggable = null; - if (_currentHighlighedSlot != null) - draggable.SetCurrentSlot(_currentHighlighedSlot); - else - draggable.ResetPosition(); - } + public void OnItemDragBegin(Draggable draggable) + { + _isDragging = true; + _currentDraggable = draggable; + } - private void EnableSlotHighlighting(bool enable) - { - foreach (var snapPoint in snapPoints) + public void OnItemDragEnd(Draggable draggable) { - snapPoint.EnableHighlighting(enable); + _isDragging = false; + _currentDraggable = null; + if (_currentHighlighedSlot != null) + draggable.SetCurrentSlot(_currentHighlighedSlot); + else + draggable.ResetPosition(); } - } - private ItemSnapPoint GetNearestSlotFromMouse() - { - float closestDistance = -1; - ItemSnapPoint closestSnapPoint = null; - foreach (var snapPoint in snapPoints) + private void EnableSlotHighlighting(bool enable) { - // check if slot is snappable and empty - if ((!snapPoint.IsSnappable)||(snapPoint.HasItem)) - continue; - // check if slot accepts item type - if (!snapPoint.AllowsAllItemTypes) - if (!snapPoint.AcceptsItem(_currentDraggable.Item)) - continue; - // calculate distance from mouse to slot - float distance = Vector2.Distance(Input.mousePosition, snapPoint.transform.position); - if (closestSnapPoint == null || distance < closestDistance) + foreach (var snapPoint in snapPoints) { - closestDistance = distance; - closestSnapPoint = snapPoint; + snapPoint.EnableHighlighting(enable); } } - if (closestDistance <= snapRange) - return closestSnapPoint; - else - return null; + private ItemSnapPoint GetNearestSlotFromMouse() + { + float closestDistance = -1; + ItemSnapPoint closestSnapPoint = null; + foreach (var snapPoint in snapPoints) + { + // check if slot is snappable and empty + if ((!snapPoint.IsSnappable) || (snapPoint.HasItem)) + continue; + // check if slot accepts item type + if (!snapPoint.AllowsAllItemTypes) + if (!snapPoint.AcceptsItem(_currentDraggable.Item)) + continue; + // calculate distance from mouse to slot + float distance = Vector2.Distance(Input.mousePosition, snapPoint.transform.position); + if (closestSnapPoint == null || distance < closestDistance) + { + closestDistance = distance; + closestSnapPoint = snapPoint; + } + } + + if (closestDistance <= snapRange) + return closestSnapPoint; + else + return null; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/StatTextView.cs b/Samples~/Scripts/DemoExample/UI/StatTextView.cs index f833cbe3..3137d5f8 100644 --- a/Samples~/Scripts/DemoExample/UI/StatTextView.cs +++ b/Samples~/Scripts/DemoExample/UI/StatTextView.cs @@ -2,18 +2,21 @@ using System.Collections.Generic; using UnityEngine; -public class StatTextView : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private TMPro.TextMeshProUGUI statNameText; - [SerializeField] private TMPro.TextMeshProUGUI statValueText; - - public void SetStatName(string name) + public class StatTextView : MonoBehaviour { - statNameText.text = name; - } + [SerializeField] private TMPro.TextMeshProUGUI statNameText; + [SerializeField] private TMPro.TextMeshProUGUI statValueText; - public void SetStatValue(string value) - { - statValueText.text = value; + public void SetStatName(string name) + { + statNameText.text = name; + } + + public void SetStatValue(string value) + { + statValueText.text = value; + } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/StatsView.cs b/Samples~/Scripts/DemoExample/UI/StatsView.cs index f266cc1d..bf0d2095 100644 --- a/Samples~/Scripts/DemoExample/UI/StatsView.cs +++ b/Samples~/Scripts/DemoExample/UI/StatsView.cs @@ -2,30 +2,33 @@ using System.Text.RegularExpressions; using UnityEngine; -public class StatsView : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private StatTextView statTextPrefab; - - public void DisplayStats(StatParams stats) + public class StatsView : MonoBehaviour { - Clear(); - - PropertyInfo[] pis = stats.GetType().GetProperties(); - foreach (PropertyInfo pi in pis) + [SerializeField] private StatTextView statTextPrefab; + + public void DisplayStats(StatParams stats) { - StatTextView newStat = Instantiate(statTextPrefab, transform); - // convert name from camel case to sentence case - string sentName = Regex.Replace(pi.Name, @"\p{Lu}", m => " " + m.Value); - newStat.SetStatName(sentName); - newStat.SetStatValue(pi.GetValue(stats).ToString()); + Clear(); + + PropertyInfo[] pis = stats.GetType().GetProperties(); + foreach (PropertyInfo pi in pis) + { + StatTextView newStat = Instantiate(statTextPrefab, transform); + // convert name from camel case to sentence case + string sentName = Regex.Replace(pi.Name, @"\p{Lu}", m => " " + m.Value); + newStat.SetStatName(sentName); + newStat.SetStatValue(pi.GetValue(stats).ToString()); + } } - } - public void Clear() - { - foreach (Transform child in transform) + public void Clear() { - Destroy(child.gameObject); + foreach (Transform child in transform) + { + Destroy(child.gameObject); + } } } } diff --git a/Samples~/Scripts/DemoExample/UI/TabButton.cs b/Samples~/Scripts/DemoExample/UI/TabButton.cs index b7cf1811..bfe61336 100644 --- a/Samples~/Scripts/DemoExample/UI/TabButton.cs +++ b/Samples~/Scripts/DemoExample/UI/TabButton.cs @@ -3,62 +3,65 @@ using UnityEngine.EventSystems; using UnityEngine.Events; -[RequireComponent(typeof(Image))] -public class TabButton : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler, IPointerExitHandler +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private TabGroup _tabGroup; - [SerializeField] private Image _background; - - public TabGroup TabGroup => _tabGroup; - public Image Background => _background; + [RequireComponent(typeof(Image))] + public class TabButton : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler, IPointerExitHandler + { + [SerializeField] private TabGroup _tabGroup; + [SerializeField] private Image _background; - public UnityEvent OnTabSelected; - public UnityEvent OnTabDeselected; + public TabGroup TabGroup => _tabGroup; + public Image Background => _background; - public void OnPointerClick(PointerEventData eventData) - { - TabGroup.OnTabSelected(this); - } + public UnityEvent OnTabSelected; + public UnityEvent OnTabDeselected; - public void OnPointerEnter(PointerEventData eventData) - { - TabGroup.OnTabEnter(this); - } + public void OnPointerClick(PointerEventData eventData) + { + TabGroup.OnTabSelected(this); + } - public void OnPointerExit(PointerEventData eventData) - { - TabGroup.OnTabExit(this); - } + public void OnPointerEnter(PointerEventData eventData) + { + TabGroup.OnTabEnter(this); + } - void Awake() - { - if (_background == null) + public void OnPointerExit(PointerEventData eventData) { - _background = GetComponent(); + TabGroup.OnTabExit(this); } - _tabGroup.Subscribe(this); - } + void Awake() + { + if (_background == null) + { + _background = GetComponent(); + } - /// - /// To be called when the button is selected so that event callbacks can be used. - /// - public void Select() - { - if (OnTabSelected != null) + _tabGroup.Subscribe(this); + } + + /// + /// To be called when the button is selected so that event callbacks can be used. + /// + public void Select() { - OnTabSelected.Invoke(); + if (OnTabSelected != null) + { + OnTabSelected.Invoke(); + } } - } - /// - /// To be called when the button is deselected so that event callbacks can be used. - /// - public void Deselect() - { - if (OnTabDeselected != null) + /// + /// To be called when the button is deselected so that event callbacks can be used. + /// + public void Deselect() { - OnTabDeselected.Invoke(); + if (OnTabDeselected != null) + { + OnTabDeselected.Invoke(); + } } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UI/TabGroup.cs b/Samples~/Scripts/DemoExample/UI/TabGroup.cs index c0c556b1..1a866345 100644 --- a/Samples~/Scripts/DemoExample/UI/TabGroup.cs +++ b/Samples~/Scripts/DemoExample/UI/TabGroup.cs @@ -1,102 +1,106 @@ using System.Collections.Generic; using UnityEngine; -public class TabGroup : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [SerializeField] private List _tabButtons; - [SerializeField] private Sprite _tabIdle; - [SerializeField] private Sprite _tabHover; - [SerializeField] private Sprite _tabActive; - [SerializeField] private List _pannelsToSwap; + public class TabGroup : MonoBehaviour + { + [SerializeField] private List _tabButtons; + [SerializeField] private Sprite _tabIdle; + [SerializeField] private Sprite _tabHover; + [SerializeField] private Sprite _tabActive; + [SerializeField] private List _pannelsToSwap; - public List TabButtons => _tabButtons; - public Sprite TabIdle => _tabIdle; - public Sprite TabHover => _tabHover; - public Sprite TabActive => _tabActive; + public List TabButtons => _tabButtons; + public Sprite TabIdle => _tabIdle; + public Sprite TabHover => _tabHover; + public Sprite TabActive => _tabActive; - private TabButton _selectedTab; + private TabButton _selectedTab; - private void Start() - { - if (_tabButtons.Count == 0) - { - return; - } + private void Start() + { + if (_tabButtons.Count == 0) + { + return; + } - OnTabSelected(_tabButtons[0]); + OnTabSelected(_tabButtons[0]); - } + } - /// - /// Subscribe a tab button to this group. - /// - /// The tab button that is subscribing to this group. - public void Subscribe(TabButton button) - { - if (TabButtons == null) + /// + /// Subscribe a tab button to this group. + /// + /// The tab button that is subscribing to this group. + public void Subscribe(TabButton button) { - _tabButtons.Add(button); + if (TabButtons == null) + { + _tabButtons.Add(button); + } } - } - /// - /// To be called when a tab button is hovered over. - /// - /// The tab button that has been used. - public void OnTabEnter(TabButton button) - { - ResetTabs(); - if (_selectedTab == null || button != _selectedTab) + /// + /// To be called when a tab button is hovered over. + /// + /// The tab button that has been used. + public void OnTabEnter(TabButton button) { - button.Background.sprite = TabHover; + ResetTabs(); + if (_selectedTab == null || button != _selectedTab) + { + button.Background.sprite = TabHover; + } } - } - /// - /// To be called when a tab button is no longer being hovered over. - /// - /// The tab button that has been exited from. - public void OnTabExit(TabButton button) - { - ResetTabs(); - } - - /// - /// To be called when a new tab is selected. - /// - /// The tab button that has been used. - public void OnTabSelected(TabButton button) - { - if (_selectedTab != null) + /// + /// To be called when a tab button is no longer being hovered over. + /// + /// The tab button that has been exited from. + public void OnTabExit(TabButton button) { - _selectedTab.Deselect(); + ResetTabs(); } - _selectedTab = button; - _selectedTab.Select(); + /// + /// To be called when a new tab is selected. + /// + /// The tab button that has been used. + public void OnTabSelected(TabButton button) + { + if (_selectedTab != null) + { + _selectedTab.Deselect(); + } + + _selectedTab = button; + _selectedTab.Select(); - ResetTabs(); - button.Background.sprite = TabActive; + ResetTabs(); + button.Background.sprite = TabActive; - int index = button.transform.GetSiblingIndex(); - for (int i = 0; i < _pannelsToSwap.Count; i++) - { - _pannelsToSwap[i].SetActive(i == index ? true : false); + int index = button.transform.GetSiblingIndex(); + for (int i = 0; i < _pannelsToSwap.Count; i++) + { + _pannelsToSwap[i].SetActive(i == index ? true : false); + } } - } - /// - /// Sets all tabs back to their initial state - /// - public void ResetTabs() - { - foreach (TabButton button in _tabButtons) + /// + /// Sets all tabs back to their initial state + /// + public void ResetTabs() { - if (_selectedTab != null && button == _selectedTab) + foreach (TabButton button in _tabButtons) { - continue; + if (_selectedTab != null && button == _selectedTab) + { + continue; + } + + button.Background.sprite = TabIdle; } - button.Background.sprite = TabIdle; } } -} +} \ No newline at end of file diff --git a/Samples~/Scripts/DemoExample/UIManager.cs b/Samples~/Scripts/DemoExample/UIManager.cs index dba93bae..e597ea25 100644 --- a/Samples~/Scripts/DemoExample/UIManager.cs +++ b/Samples~/Scripts/DemoExample/UIManager.cs @@ -6,232 +6,235 @@ using UnityEngine; using UnityEngine.UI; -public class UIManager : MonoBehaviour +namespace TezosSDK.Samples.DemoExample { - [Header("References:")] [SerializeField] - private GameObject loginPanel; - - [SerializeField] private GameObject welcomePanel; - [SerializeField] private TMPro.TextMeshProUGUI welcomeText; - [SerializeField] private TabButton inventoryButton; - [SerializeField] private TabButton marketButton; - [SerializeField] private InventoryManager inventory; - [SerializeField] private MarketManager market; - [SerializeField] private GameObject loadingPanel; - [SerializeField] private TMPro.TextMeshProUGUI accountText; - [SerializeField] private TMPro.TextMeshProUGUI balanceText; - [SerializeField] private TMPro.TextMeshProUGUI softBalanceText; - [SerializeField] private GameObject popupPanel; - - private IExampleManager _manager; - - private void Start() - { - _manager = ExampleFactory.Instance.GetExampleManager(); - InitializeCallbacks(); + public class UIManager : MonoBehaviour + { + [Header("References:")] [SerializeField] + private GameObject loginPanel; + + [SerializeField] private GameObject welcomePanel; + [SerializeField] private TMPro.TextMeshProUGUI welcomeText; + [SerializeField] private TabButton inventoryButton; + [SerializeField] private TabButton marketButton; + [SerializeField] private InventoryManager inventory; + [SerializeField] private MarketManager market; + [SerializeField] private GameObject loadingPanel; + [SerializeField] private TMPro.TextMeshProUGUI accountText; + [SerializeField] private TMPro.TextMeshProUGUI balanceText; + [SerializeField] private TMPro.TextMeshProUGUI softBalanceText; + [SerializeField] private GameObject popupPanel; + + private IExampleManager _manager; + + private void Start() + { + _manager = ExampleFactory.Instance.GetExampleManager(); + InitializeCallbacks(); - AllowUIAccess(false); - inventoryButton.OnTabSelected.AddListener(AccessInventory); - marketButton.OnTabSelected.AddListener(AccessMarket); + AllowUIAccess(false); + inventoryButton.OnTabSelected.AddListener(AccessInventory); + marketButton.OnTabSelected.AddListener(AccessMarket); - inventory.onInventoryRefresh.AddListener(AccessInventory); - inventory.onItemMint.AddListener(MintItem); - } + inventory.onInventoryRefresh.AddListener(AccessInventory); + inventory.onItemMint.AddListener(MintItem); + } - private void InitializeCallbacks() - { - _manager.GetMessageReceiver().AccountConnected += OnAccountConnected; - _manager.GetMessageReceiver().AccountConnectionFailed += OnAccountConnectionFailed; - _manager.GetMessageReceiver().AccountDisconnected += OnAccountDisconnected; - _manager.GetMessageReceiver().ContractCallCompleted += OnContractCallCompleted; - _manager.GetMessageReceiver().ContractCallFailed += OnContractCallFailed; - _manager.GetMessageReceiver().ContractCallInjected += OnContractCallInjected; - _manager.GetMessageReceiver().PayloadSigned += OnPayloadSigned; - } + private void InitializeCallbacks() + { + _manager.GetMessageReceiver().AccountConnected += OnAccountConnected; + _manager.GetMessageReceiver().AccountConnectionFailed += OnAccountConnectionFailed; + _manager.GetMessageReceiver().AccountDisconnected += OnAccountDisconnected; + _manager.GetMessageReceiver().ContractCallCompleted += OnContractCallCompleted; + _manager.GetMessageReceiver().ContractCallFailed += OnContractCallFailed; + _manager.GetMessageReceiver().ContractCallInjected += OnContractCallInjected; + _manager.GetMessageReceiver().PayloadSigned += OnPayloadSigned; + } - private void AccessInventory() - { - loadingPanel.SetActive(true); + private void AccessInventory() + { + loadingPanel.SetActive(true); - _manager.FetchInventoryItems(PopulateInventory); + _manager.FetchInventoryItems(PopulateInventory); - DisplayWalletData(); - } + DisplayWalletData(); + } - private void AccessMarket() - { - loadingPanel.SetActive(true); + private void AccessMarket() + { + loadingPanel.SetActive(true); - _manager.FetchMarketItems(PopulateMarket); + _manager.FetchMarketItems(PopulateMarket); - DisplayWalletData(); - } + DisplayWalletData(); + } - private void MintItem() - { - _manager.MintItem(); - } + private void MintItem() + { + _manager.MintItem(); + } - public void GetCoins() - { - _manager.GetCoins(); - } + public void GetCoins() + { + _manager.GetCoins(); + } - public void OnSignIn(bool success) - { - AllowUIAccess(success); - //TODO: GetActiveAccount() in the BeaconConnector SHOULD be returning stuff from the paired account. - //Something in there might be usable to populate the User info I removed if we still want this. - welcomeText.text = success ? "Welcome!" : "Pairing failed or timed out"; - DisplayWalletData(); - } + public void OnSignIn(bool success) + { + AllowUIAccess(success); + //TODO: GetActiveAccount() in the BeaconConnector SHOULD be returning stuff from the paired account. + //Something in there might be usable to populate the User info I removed if we still want this. + welcomeText.text = success ? "Welcome!" : "Pairing failed or timed out"; + DisplayWalletData(); + } - public void AllowUIAccess(bool allow) - { - loginPanel.SetActive(!allow); - welcomePanel.SetActive(allow); - inventoryButton.gameObject.SetActive(allow); - marketButton.gameObject.SetActive(allow); - } + public void AllowUIAccess(bool allow) + { + loginPanel.SetActive(!allow); + welcomePanel.SetActive(allow); + inventoryButton.gameObject.SetActive(allow); + marketButton.gameObject.SetActive(allow); + } - private void PopulateInventory(List items) - { - Action action = () => + private void PopulateInventory(List items) { - inventory.Init(items); - loadingPanel.SetActive(false); - }; - CoroutineRunner.Instance.StartWrappedCoroutine(DoActionNextFrame(action)); - } + Action action = () => + { + inventory.Init(items); + loadingPanel.SetActive(false); + }; + CoroutineRunner.Instance.StartWrappedCoroutine(DoActionNextFrame(action)); + } - private void PopulateMarket(List items) - { - Action action = () => + private void PopulateMarket(List items) { - market.Init(items); - loadingPanel.SetActive(false); - }; - CoroutineRunner.Instance.StartWrappedCoroutine(DoActionNextFrame(action)); - } + Action action = () => + { + market.Init(items); + loadingPanel.SetActive(false); + }; + CoroutineRunner.Instance.StartWrappedCoroutine(DoActionNextFrame(action)); + } - private IEnumerator DoActionNextFrame(Action action) - { - yield return new WaitForEndOfFrame(); - action?.Invoke(); - } + private IEnumerator DoActionNextFrame(Action action) + { + yield return new WaitForEndOfFrame(); + action?.Invoke(); + } - public void ResetWalletData() - { - SetAccountText("0"); - SetBalanceText(0); - SetSoftBalanceText(0); - } + public void ResetWalletData() + { + SetAccountText("0"); + SetBalanceText(0); + SetSoftBalanceText(0); + } - private void DisplayWalletData() - { - string address = _manager.GetActiveAccountAddress(); - SetAccountText(address); - _manager.GetBalance(SetBalanceText); - _manager.GetSoftBalance(SetSoftBalanceText); - } + private void DisplayWalletData() + { + string address = _manager.GetActiveAccountAddress(); + SetAccountText(address); + _manager.GetBalance(SetBalanceText); + _manager.GetSoftBalance(SetSoftBalanceText); + } - private void SetBalanceText(ulong balance) - { - // balance is in mutez (one millionth of tezos) - var floatBalance = balance * 0.000001; - balanceText.text = (floatBalance).ToString(); - } + private void SetBalanceText(ulong balance) + { + // balance is in mutez (one millionth of tezos) + var floatBalance = balance * 0.000001; + balanceText.text = (floatBalance).ToString(); + } - private void SetSoftBalanceText(int balance) - { - // balance is in mutez (one millionth of tezos) - softBalanceText.text = balance.ToString(); - } + private void SetSoftBalanceText(int balance) + { + // balance is in mutez (one millionth of tezos) + softBalanceText.text = balance.ToString(); + } - private void SetAccountText(string account) - { - accountText.text = account; - } + private void SetAccountText(string account) + { + accountText.text = account; + } - private void DisplayPopup(string message) - { - UnityMainThreadDispatcher.Enqueue((msg) => + private void DisplayPopup(string message) { - popupPanel.SetActive(true); - popupPanel.GetComponentInChildren().text = msg; - }, message); - } + UnityMainThreadDispatcher.Enqueue((msg) => + { + popupPanel.SetActive(true); + popupPanel.GetComponentInChildren().text = msg; + }, message); + } - #region Tezos Callbacks + #region Tezos Callbacks - private void OnAccountConnected(string account) - { - if (!string.IsNullOrEmpty(account)) - OnSignIn(true); - } + private void OnAccountConnected(string account) + { + if (!string.IsNullOrEmpty(account)) + OnSignIn(true); + } - private void OnAccountConnectionFailed(string response) - { - DisplayPopup("Wallet connection failed!\n \n" + - "Response: \n" + response); - } + private void OnAccountConnectionFailed(string response) + { + DisplayPopup("Wallet connection failed!\n \n" + + "Response: \n" + response); + } - private void OnAccountDisconnected(string account) - { - AllowUIAccess(false); - ResetWalletData(); - } + private void OnAccountDisconnected(string account) + { + AllowUIAccess(false); + ResetWalletData(); + } - [Serializable] - private struct Transaction - { - public string transactionHash; - } + [Serializable] + private struct Transaction + { + public string transactionHash; + } - private void OnContractCallCompleted(string response) - { - string transactionHash = - JsonSerializer.Deserialize(response).GetProperty("transactionHash").ToString(); - DisplayPopup("Transaction completed!\n \n" + - "Transaction hash:\n" + transactionHash + - "\n \nResponse:\n" + response); - } + private void OnContractCallCompleted(string response) + { + string transactionHash = + JsonSerializer.Deserialize(response).GetProperty("transactionHash").ToString(); + DisplayPopup("Transaction completed!\n \n" + + "Transaction hash:\n" + transactionHash + + "\n \nResponse:\n" + response); + } - private void OnContractCallFailed(string response) - { - DisplayPopup("Transaction failed!\n \n" + - "Response:\n" + response); - } + private void OnContractCallFailed(string response) + { + DisplayPopup("Transaction failed!\n \n" + + "Response:\n" + response); + } - private void OnContractCallInjected(string result) - { - string successString = JsonSerializer.Deserialize(result).GetProperty("success").ToString(); - string transactionHash = - JsonSerializer.Deserialize(result).GetProperty("transactionHash").ToString(); - bool success = successString != null && bool.Parse(successString); - if (success) + private void OnContractCallInjected(string result) { - _manager.FetchMarketItems(PopulateMarket); - _manager.FetchInventoryItems(PopulateInventory); - market.CheckSelection(); - DisplayWalletData(); + string successString = JsonSerializer.Deserialize(result).GetProperty("success").ToString(); + string transactionHash = + JsonSerializer.Deserialize(result).GetProperty("transactionHash").ToString(); + bool success = successString != null && bool.Parse(successString); + if (success) + { + _manager.FetchMarketItems(PopulateMarket); + _manager.FetchInventoryItems(PopulateInventory); + market.CheckSelection(); + DisplayWalletData(); + } + + DisplayPopup("Call injected!\n \n" + + "Response:\n" + success + + "\n \nTransaction Hash:\n" + transactionHash); } - DisplayPopup("Call injected!\n \n" + - "Response:\n" + success + - "\n \nTransaction Hash:\n" + transactionHash); - } + private void OnPayloadSigned(string result) + { + var signature = JsonSerializer + .Deserialize(result) + .GetProperty("signature") + .ToString(); - private void OnPayloadSigned(string result) - { - var signature = JsonSerializer - .Deserialize(result) - .GetProperty("signature") - .ToString(); + DisplayPopup($"Signed!\n \n" + + $"Signature: {signature}"); + } - DisplayPopup($"Signed!\n \n" + - $"Signature: {signature}"); + #endregion } - - #endregion } \ No newline at end of file diff --git a/Samples~/Scripts/NftApiSample/DataManager.cs b/Samples~/Scripts/NftApiSample/DataManager.cs index 71aed83b..8dd6425b 100644 --- a/Samples~/Scripts/NftApiSample/DataManager.cs +++ b/Samples~/Scripts/NftApiSample/DataManager.cs @@ -7,144 +7,147 @@ using TezosSDK.Tezos.API.Models.Tokens; using UnityEngine; -public class DataManager : MonoBehaviour +namespace TezosSDK.Samples.NFTApiSample { - private ITezosAPI _tezos; - - private string _connectedAddress; - private string _checkContract; - private string _checkAddress; - private string _checkTokenId; + public class DataManager : MonoBehaviour + { + private ITezosAPI _tezos; - public Action DataReceived; + private string _connectedAddress; + private string _checkContract; + private string _checkAddress; + private string _checkTokenId; - private const int MaxTokens = 20; + public Action DataReceived; - void Start() - { - _tezos = TezosSingleton.Instance; - _tezos.MessageReceiver.AccountConnected += OnAccountConnected; - } + private const int MaxTokens = 20; - void OnAccountConnected(string result) - { - var json = JsonSerializer.Deserialize(result); - var account = json.GetProperty("account"); - _connectedAddress = account.GetProperty("address").GetString(); - } + void Start() + { + _tezos = TezosSingleton.Instance; + _tezos.MessageReceiver.AccountConnected += OnAccountConnected; + } - public void GetTokensForOwners() - { - var walletAddress = string.IsNullOrEmpty(_checkAddress) - ? _connectedAddress - : _checkAddress; + void OnAccountConnected(string result) + { + var json = JsonSerializer.Deserialize(result); + var account = json.GetProperty("account"); + _connectedAddress = account.GetProperty("address").GetString(); + } - CoroutineRunner.Instance.StartCoroutine( - _tezos.GetTokensForOwner((tbs) => - { - if (tbs == null) - { - DataReceived.Invoke($"Incorrect address - {walletAddress}"); - Debug.Log($"Incorrect address - {walletAddress}"); - return; - } + public void GetTokensForOwners() + { + var walletAddress = string.IsNullOrEmpty(_checkAddress) + ? _connectedAddress + : _checkAddress; - List tokens = new List(tbs); - if (tokens.Count > 0) + CoroutineRunner.Instance.StartCoroutine( + _tezos.GetTokensForOwner((tbs) => { - var result = ""; - foreach (var tb in tokens) + if (tbs == null) { - result += - $"{walletAddress} has {tb.Balance} tokens on contract {tb.TokenContract.Address}" + - "\r\n" + "\r\n"; - Debug.Log( - $"{walletAddress} has {tb.Balance} tokens on contract {tb.TokenContract.Address}"); + DataReceived.Invoke($"Incorrect address - {walletAddress}"); + Debug.Log($"Incorrect address - {walletAddress}"); + return; } - DataReceived.Invoke(result); - } - else - { - DataReceived.Invoke($"{walletAddress} has no tokens"); - Debug.Log($"{walletAddress} has no tokens"); - } - }, - owner: walletAddress, - withMetadata: false, - maxItems: MaxTokens, - orderBy: new TokensForOwnerOrder.Default(0))); - } - - public void IsHolderOfContract() - { - var walletAddress = string.IsNullOrEmpty(_checkAddress) - ? _connectedAddress - : _checkAddress; + List tokens = new List(tbs); + if (tokens.Count > 0) + { + var result = ""; + foreach (var tb in tokens) + { + result += + $"{walletAddress} has {tb.Balance} tokens on contract {tb.TokenContract.Address}" + + "\r\n" + "\r\n"; + Debug.Log( + $"{walletAddress} has {tb.Balance} tokens on contract {tb.TokenContract.Address}"); + } + + DataReceived.Invoke(result); + } + else + { + DataReceived.Invoke($"{walletAddress} has no tokens"); + Debug.Log($"{walletAddress} has no tokens"); + } + }, + owner: walletAddress, + withMetadata: false, + maxItems: MaxTokens, + orderBy: new TokensForOwnerOrder.Default(0))); + } - if (string.IsNullOrEmpty(_checkContract)) + public void IsHolderOfContract() { - DataReceived.Invoke("Enter contract address"); - Debug.Log("Enter contract address"); - return; - } + var walletAddress = string.IsNullOrEmpty(_checkAddress) + ? _connectedAddress + : _checkAddress; - CoroutineRunner.Instance.StartCoroutine(_tezos.IsHolderOfContract((flag) => + if (string.IsNullOrEmpty(_checkContract)) { - var message = flag - ? $"{walletAddress} is HOLDER of contract {_checkContract}" - : $"{walletAddress} is NOT HOLDER of contract {_checkContract}"; - - DataReceived.Invoke(message); - Debug.Log(message); - }, - wallet: walletAddress, - contractAddress: _checkContract)); - } + DataReceived.Invoke("Enter contract address"); + Debug.Log("Enter contract address"); + return; + } - public void IsHolderOfToken() - { - var walletAddress = string.IsNullOrEmpty(_checkAddress) - ? _connectedAddress - : _checkAddress; + CoroutineRunner.Instance.StartCoroutine(_tezos.IsHolderOfContract((flag) => + { + var message = flag + ? $"{walletAddress} is HOLDER of contract {_checkContract}" + : $"{walletAddress} is NOT HOLDER of contract {_checkContract}"; - var tokenId = string.IsNullOrEmpty(_checkTokenId) - ? 0 - : Convert.ToUInt32(_checkTokenId); + DataReceived.Invoke(message); + Debug.Log(message); + }, + wallet: walletAddress, + contractAddress: _checkContract)); + } - if (string.IsNullOrEmpty(_checkContract)) + public void IsHolderOfToken() { - DataReceived.Invoke("Enter contract address"); - Debug.Log("Enter contract address"); - return; - } + var walletAddress = string.IsNullOrEmpty(_checkAddress) + ? _connectedAddress + : _checkAddress; - CoroutineRunner.Instance.StartCoroutine(_tezos.IsHolderOfToken((flag) => + var tokenId = string.IsNullOrEmpty(_checkTokenId) + ? 0 + : Convert.ToUInt32(_checkTokenId); + + if (string.IsNullOrEmpty(_checkContract)) { - var message = flag - ? $"{walletAddress} is HOLDER of token" - : $"{walletAddress} is NOT HOLDER of token"; - - DataReceived.Invoke(message); - Debug.Log(message); - }, - wallet: walletAddress, - contractAddress: _checkContract, - tokenId: tokenId)); - } + DataReceived.Invoke("Enter contract address"); + Debug.Log("Enter contract address"); + return; + } - public void SetCheckAddress(string address) - { - _checkAddress = address; - } + CoroutineRunner.Instance.StartCoroutine(_tezos.IsHolderOfToken((flag) => + { + var message = flag + ? $"{walletAddress} is HOLDER of token" + : $"{walletAddress} is NOT HOLDER of token"; - public void SetCheckTokenId(string tokenId) - { - _checkTokenId = tokenId; - } + DataReceived.Invoke(message); + Debug.Log(message); + }, + wallet: walletAddress, + contractAddress: _checkContract, + tokenId: tokenId)); + } - public void SetCheckContract(string contract) - { - _checkContract = contract; + public void SetCheckAddress(string address) + { + _checkAddress = address; + } + + public void SetCheckTokenId(string tokenId) + { + _checkTokenId = tokenId; + } + + public void SetCheckContract(string contract) + { + _checkContract = contract; + } } } \ No newline at end of file diff --git a/Samples~/Scripts/NftApiSample/UiManager.cs b/Samples~/Scripts/NftApiSample/UiManager.cs index baf3c9e4..b14f808f 100644 --- a/Samples~/Scripts/NftApiSample/UiManager.cs +++ b/Samples~/Scripts/NftApiSample/UiManager.cs @@ -1,41 +1,44 @@ using UnityEngine; using UnityEngine.UI; -public class UiManager : MonoBehaviour +namespace TezosSDK.Samples.NFTApiSample { - [SerializeField] private DataManager dataManager; - [SerializeField] private InputField addressInputField; - [SerializeField] private InputField contractInputField; - [SerializeField] private InputField tokenIdInputField; - [SerializeField] private Text resultText; - - void Start() + public class UiManager : MonoBehaviour { - dataManager.DataReceived += OnDataReceived; + [SerializeField] private DataManager dataManager; + [SerializeField] private InputField addressInputField; + [SerializeField] private InputField contractInputField; + [SerializeField] private InputField tokenIdInputField; + [SerializeField] private Text resultText; - addressInputField.onEndEdit.AddListener(delegate { OnEndEditAddress(addressInputField); }); - contractInputField.onEndEdit.AddListener(delegate { OnEndEditContract(contractInputField); }); - tokenIdInputField.onEndEdit.AddListener(delegate { OnEndEditTokenId(tokenIdInputField); }); - } + void Start() + { + dataManager.DataReceived += OnDataReceived; - void OnDataReceived(string data) - { - resultText.text = string.Empty; - resultText.text = data; - } + addressInputField.onEndEdit.AddListener(delegate { OnEndEditAddress(addressInputField); }); + contractInputField.onEndEdit.AddListener(delegate { OnEndEditContract(contractInputField); }); + tokenIdInputField.onEndEdit.AddListener(delegate { OnEndEditTokenId(tokenIdInputField); }); + } - void OnEndEditAddress(InputField input) - { - dataManager.SetCheckAddress(input.text); - } + void OnDataReceived(string data) + { + resultText.text = string.Empty; + resultText.text = data; + } - void OnEndEditContract(InputField input) - { - dataManager.SetCheckContract(input.text); - } + void OnEndEditAddress(InputField input) + { + dataManager.SetCheckAddress(input.text); + } - void OnEndEditTokenId(InputField input) - { - dataManager.SetCheckTokenId(input.text); + void OnEndEditContract(InputField input) + { + dataManager.SetCheckContract(input.text); + } + + void OnEndEditTokenId(InputField input) + { + dataManager.SetCheckTokenId(input.text); + } } } \ No newline at end of file diff --git a/Samples~/Scripts/ScriptableObjects/ItemReseource.cs b/Samples~/Scripts/ScriptableObjects/ItemReseource.cs index b52d5de3..a72d0327 100644 --- a/Samples~/Scripts/ScriptableObjects/ItemReseource.cs +++ b/Samples~/Scripts/ScriptableObjects/ItemReseource.cs @@ -2,9 +2,12 @@ using System.Collections.Generic; using UnityEngine; -[CreateAssetMenu(fileName = "ItemResources", menuName = "ScriptableObjects/ItemResources", order = 1)] -public class ItemReseource : ScriptableObject +namespace TezosSDK.Samples { - public string Name; - public Sprite ItemSprite; -} + [CreateAssetMenu(fileName = "ItemResources", menuName = "ScriptableObjects/ItemResources", order = 1)] + public class ItemReseource : ScriptableObject + { + public string Name; + public Sprite ItemSprite; + } +} \ No newline at end of file diff --git a/Tests/Editor/EditmodeTests.cs b/Tests/Editor/EditmodeTests.cs index 53ab65c1..d926b89a 100644 --- a/Tests/Editor/EditmodeTests.cs +++ b/Tests/Editor/EditmodeTests.cs @@ -1,11 +1,13 @@ using NUnit.Framework; - -public class EditmodeTests +namespace Tests.Editor { - // A Test behaves as an ordinary method - [Test] - public void EditmodeTestsSimplePasses() + public class EditmodeTests { + // A Test behaves as an ordinary method + [Test] + public void EditmodeTestsSimplePasses() + { + } } } \ No newline at end of file