Пример #1
0
        public async Task <ActionResult <CryptoItem> > PostCryptoItem(CryptoItem item)
        {
            _context.CryptoItems.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetCryptoItem), new { id = item.Id }, item));
        }
Пример #2
0
    // This method tests Enjin's non-runtime API methods mostly used in the editor window.
    private void TestStaticEndpoints()
    {
        // Helper methods.
        TestMethod(() => { Enjin.StoreUserData(new User(), "test"); }, "user data storage");
        TestMethod <Boolean>(() => { return(Enjin.ValidateAddress("0xf629cbd94d3791c9250152bd8dfbdf380e2a3b9c")); }, true, "address validation");
        TestMethod(() => { Enjin.URLGetData("https://enjincoin.io/", new System.Collections.Generic.Dictionary <string, string>()); }, "fetching URL data");
        TestMethod <String>(() => { return(Enjin.URLGetData("bad URL", new System.Collections.Generic.Dictionary <string, string>())); }, string.Empty, "expected result from bad URL data");
        TestMethod(() => { Enjin.ResetErrorReport(); }, "error report reset");


        // CryptoItems methods.
        TestMethod(() => { Enjin.GetCryptoItemBalance(testingIdentityID, TESTING_ITEM_ID); }, "balance by identity");
        TestMethod(() => { Enjin.GetMintableItems(TESTING_ITEM_ID); }, "mintable item retrieval");
        TestMethod(() => {
            CryptoItem item = Enjin.GetCryptoItem(TESTING_ITEM_ID);
            Enjin.GetCryptoItemIDByName(item.name);
        }, "item identity by name");
        TestMethod(() => { Enjin.GetCryptoItemBalances(testingIdentityID); }, "all balances by identity");
        TestMethod(() => { Enjin.UpdateCryptoItem(new CryptoItem()); }, "item updating");
        TestMethod(() => { Enjin.GetAllCryptoItems(); }, "searching all items");
        TestMethod(() => {
            CryptoItem item = Enjin.GetCryptoItem(TESTING_ITEM_ID);
            Enjin.GetCryptoItemIDByName(item.name);
        }, "searching for item name");
        TestMethod(() => { Enjin.GetAllItems(0, 0, DEVELOPER_IDENTITY_ID); }, "getting all items by page");
        TestMethod(() => { Enjin.GetAllItems(DEVELOPER_IDENTITY_ID); }, "getting all items");

        // Enjin Platform API methods.
        TestMethod(() => { Enjin.GetTotalActiveTokens(DEVELOPER_IDENTITY_ID); }, "getting all active tokens");
        TestMethod(() => { Enjin.GetAppsByUserID(loginUser.id); }, "getting apps for user");
        TestMethod(() => { Enjin.GetAppByID(APP_ID); }, "getting app by id");

        // Identity methods.
        TestMethod(() => { Enjin.UpdateBalances(new Identity()); }, "identity balance updates");
        TestMethod(() => { Enjin.GetIdentity(testingIdentityID); }, "identity retrieval");
        TestMethod(() => { Enjin.GetAllIdentities(); }, "bulk identity retrieval");
        TestMethod(() => { Enjin.SearchIdentities("enjin"); }, "identity search");
        Identity sampleIdentity = new Identity
        {
            user = new Identity.User
            {
                name = loginUser.name,
                id   = loginUser.id
            },
            id     = testingIdentityID,
            fields = new Fields[] { new Fields("test", "enjin", 0, 0, 0) }
        };

        TestMethod(() => { Enjin.UpdateIdentity(sampleIdentity); }, "identity update");
        Enjin.AccessToken = TESTER_TOKEN;
        TestMethod(() => { Enjin.UpdateIdentityFields(testingIdentityID, new Fields[] { new Fields("test", "enjin!", 0, 0, 0) }); }, "identity field update");
        TestMethod(() => { Enjin.LinkIdentity(sampleIdentity); }, "identity link");
        TestMethod(() => { Enjin.UnLinkIdentity(testingIdentityID); }, "identity unlinking");
        TestMethod(() => { Enjin.DeleteIdentity(testingIdentityID + ""); }, "identity deletion");
        TestMethod(() => { Enjin.CreateIdentity(sampleIdentity); }, "identity creation");
        TestMethod(() => { Enjin.GetRoles(); }, "fetching identity roles");
        TestMethod(() => { Enjin.GetIdentities(0, 0); }, "fetching identity pages");
    }
Пример #3
0
        public IActionResult Encrypt(string data)
        {
            string secretKey = "dR7s?ufreWa=r*G_ZEphA*Ra";

            var        symmetricEncryptDecrypt = new SymmetricTripleDesCipher();
            CryptoItem response = symmetricEncryptDecrypt.Encrypt(data, secretKey);

            return(Ok(new { Value = response.EncryptedData, IV = response.IV }));
        }
Пример #4
0
        public async Task <IActionResult> PutCryptoItem(long id, CryptoItem item)
        {
            if (id != item.Id)
            {
                return(BadRequest());
            }

            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
Пример #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cryptoItem"></param>
        /// <param name="meltValue"></param>
        /// <returns></returns>
        private CryptoItem SetMeltValue(CryptoItem cryptoItem, float meltValue)
        {
            string  minValue = GraphQLClient.GraphQuery.GetEndPointData(Enjin.MeltValueURL + cryptoItem.reserve);
            decimal actual   = (decimal)(meltValue * Mathf.Pow(10, 18));

            if (actual < System.Convert.ToInt64(minValue))
            {
                cryptoItem.meltValue = minValue;
            }
            else
            {
                cryptoItem.meltValue = actual.ToString("0");
            }

            return(cryptoItem);
        }
Пример #6
0
 /// <summary>
 /// Local UI reset function for working CI object
 /// </summary>
 public void Reset()
 {
     //CurrentCryptoItem = new CryptoItem();
     NewCryptoItem = new CryptoItem();
     MetaDataURI   = "";
     Whitelist.Clear();
     MeltValue          = 0;
     MeltFee            = 0;
     NumToMint          = 1;
     NumToMelt          = 0;
     TotalItems         = 0;
     InitialItems       = 1;
     EnjValue           = 0;
     State              = CryptoItemState.MAIN;
     IsEditingWhitelist = false;
     ScrollIndex        = Vector2.zero;
     Address            = "";
     UpdateEnjPerItem();
 }
Пример #7
0
        public CryptoItemsController()
        {
            _resultQueue = new Dictionary <string, Result>();

            ModelType          = SupplyModel2.FIXED;
            ItemType           = CryptoItemType.FUNGIBLE;
            CurrentPage        = 1;
            FirstPage          = 1;
            PageNumber         = "01";
            Pagination         = Enjin.GetAllItems(CurrentPage, EnjinEditor.ItemsPerPage, EnjinEditor.CurrentUserIdentity.id);
            SelectedIndex      = 0;
            SearchOptionIndex  = 0;
            InitialItems       = 1;
            FilterSelection    = 1;
            LastFilterSelected = 1;
            ListItems          = new string[9];
            SelectedIndex      = 0;
            EnjValue           = 0;
            ScrollPos          = Vector2.zero;
            LastFilterSelected = 1;
            CurrentCryptoItem  = new CryptoItem();
            HasListRefreshed   = true;
            IsSearchMode       = false;
            Whitelist          = new List <string>();
            NumToMelt          = 0;
            EnjReturned        = 0;
            EnjPerItem         = 0;
            MinWei             = System.Convert.ToInt64(GraphQLClient.GraphQuery.GetEndPointData(Enjin.MeltValueURL + 1));

            if (Pagination != null)
            {
                TotalPages     = (int)Mathf.Ceil((float)Pagination.cursor.total / (float)Pagination.cursor.perPage);
                CryptoItemList = new List <CryptoItem>(Pagination.items);
            }

            Reset();
            Properties = new Dictionary <string, object>();
        }
Пример #8
0
    private void Update()
    {
        // Sequence lock to wait for a successful callback on linking a wallet.
        if (sequenceOne)
        {
            sequenceOne = false;
            Debug.Log("(5/8) Sending an item from the developer account to the testing account ... ");
            Enjin.AccessToken = DEVELOPER_TOKEN;

            // Mint a new token directly from the developer wallet.
            CryptoItem item             = Enjin.GetCryptoItem(TESTING_ITEM_ID);
            string     reserveCount     = item.reserve;
            int        developerBalance = Enjin.GetCryptoItemBalance(DEVELOPER_IDENTITY_ID, TESTING_ITEM_ID);
            if (!reserveCount.Equals("0"))
            {
                Enjin.MintFungibleItem(DEVELOPER_IDENTITY_ID, new string[] { USER_ADDRESS }, TESTING_ITEM_ID, 1,
                                       (requestEvent) =>
                {
                    if (requestEvent.event_type.Equals("tx_executed"))
                    {
                        Debug.Log(" ... PASSED: MINTED.");
                        sequenceTwo = true;
                    }
                });
            }

            // If the developer wallet is unable to mint reward tokens from the reserve, try to send it from the developer wallet.
            else if (developerBalance > 0)
            {
                Enjin.SendCryptoItemRequest(DEVELOPER_IDENTITY_ID, TESTING_ITEM_ID, testingIdentityID, 1, sendData =>
                {
                    if (sendData.event_type.Equals("tx_executed"))
                    {
                        Debug.Log(" ... PASSED: SENT.");
                        sequenceTwo = true;
                    }
                });
            }

            // Otherwise there really is nothing of this token left for the developer to give out.
            else
            {
                Debug.Log(" ... FAILED: NO RESERVE TO MINT OR BALANCE TO SEND.");
            }
        }

        // Sequence lock to wait for a successful callback on sending an item.
        if (sequenceTwo)
        {
            sequenceTwo = false;
            Debug.Log("(6/8) Trading an item from the testing account to the developer account ... ");
            Enjin.AccessToken = TESTER_TOKEN;
            CryptoItem tradeToItem = new CryptoItem
            {
                token_id    = TESTING_ITEM_ID,
                nonFungible = false
            };
            CryptoItem tradeFromItem = new CryptoItem
            {
                token_id    = TESTING_ITEM_ID,
                nonFungible = false
            };
            testingIdentity = Enjin.GetIdentity(testingIdentityID);
            Identity developerIdentity = Enjin.GetIdentity(DEVELOPER_IDENTITY_ID);
            Enjin.CreateTradeRequest(testingIdentityID, new CryptoItem[] { tradeToItem }, new int[] { 1 },
                                     DEVELOPER_IDENTITY_ID, new CryptoItem[] { tradeFromItem }, new int[] { 1 }, tradeData =>
            {
                tradeId = tradeData.request_id;
                Debug.Log(" ... PASSED.");
                sequenceThree = true;
            });
        }

        // Sequence lock to wait for successful trade creation before completion.
        if (sequenceThree)
        {
            sequenceThree = false;
            Debug.Log("(7/8) Completing trade from the testing account to the developer account ... ");
            Enjin.AccessToken = DEVELOPER_TOKEN;
            Enjin.CompleteTradeRequest(DEVELOPER_IDENTITY_ID, "" + tradeId, tradeData =>
            {
                Debug.Log(" ... PASSED.");
                sequenceFour = true;
            });
        }

        // Sequence lock to wait for successful trade of item before melting.
        if (sequenceFour)
        {
            sequenceFour = false;
            Debug.Log("(8/8) Melting an item on the testing account ... ");
            Enjin.AccessToken = TESTER_TOKEN;
            Enjin.MeltTokens(testingIdentityID, TESTING_ITEM_ID, 1, meltData =>
            {
                Debug.Log(" ... PASSED.");
                sequenceFive = true;
            });
        }

        // Sequence lock to wait for successful completion of all tests before running static suite.
        if (sequenceFive)
        {
            sequenceFive = false;

            // Execute additional tests for non-runtime SDK calls.
            TestStaticEndpoints();
            Debug.Log("=== All tests executed successfully. ===");
        }
    }
Пример #9
0
    // Initialize the game state on start.
    private void Start()
    {
        pendingActions = new List <System.Action>();
        score          = 0;
        linkingCode    = "";
        identityId     = -1;
        userAddress    = "";
        user           = null;
        count          = 0;
        pending        = 0;
        tokenName      = "";

        // Initialize references to scene objects.
        status              = GameObject.Find("Status").GetComponent <Text>();
        tutorial            = GameObject.Find("Tutorial").GetComponent <Text>();
        authenticationPanel = GameObject.Find("Authentication Panel");
        registrationPanel   = GameObject.Find("Registration Panel");
        registrationEmail   = registrationPanel.transform.Find("Email").GetComponent <InputField>();
        proceedToLoginPanel = GameObject.Find("Proceed to Login Panel");
        loginPanel          = GameObject.Find("Login Panel");
        loginEmail          = loginPanel.transform.Find("Email").GetComponent <InputField>();
        loginPassword       = loginPanel.transform.Find("Password").GetComponent <InputField>();
        gamePanel           = GameObject.Find("Game Panel");
        inventory           = gamePanel.transform.Find("Inventory").GetComponent <Text>();
        rewardTokenImage    = gamePanel.transform.Find("Reward Image").GetComponent <Image>();
        rewardMask          = gamePanel.transform.Find("Reward Mask").gameObject;
        rewardMaskImage     = rewardMask.GetComponent <Image>();
        panelList           = new List <GameObject>
        {
            authenticationPanel,
            registrationPanel,
            proceedToLoginPanel,
            loginPanel,
            gamePanel
        };

        // Prepare the first scene.
        ShowPanel(authenticationPanel);
        tutorial.text = Resources.Load <TextAsset>("auth-method-tutorial").text;

        // Start the Enjin SDK.
        Enjin.StartPlatform(PLATFORM_URL, DEVELOPER_USERNAME, DEVELOPER_PASSWORD, APP_ID);
        Debug.Log("<color=aqua>[Simple Game]</color> Using app with ID " + Enjin.AppID);

        // Retrieve the specified reward token's metadata.
        CryptoItem rewardToken = Enjin.GetCryptoItem(REWARD_TOKEN_ID);

        StartCoroutine(rewardToken.GetMetadata((metadataInfo) =>
        {
            // Handle any potential errors in metadata retrieval.
            MetadataInfo.MetadataRequestState requestState = metadataInfo.state;
            switch (requestState)
            {
            case MetadataInfo.MetadataRequestState.PARSE_FAILED:
                SetStatus("Unable to parse the reward item's metadata.");
                break;

            case MetadataInfo.MetadataRequestState.RETRIEVAL_FAILED:
                SetStatus("Unable to retrieve the reward item's metadata.");
                break;

            case MetadataInfo.MetadataRequestState.SUCCESS:
                {
                    tokenName = metadataInfo.metadata.name;
                    StartCoroutine(rewardToken.GetImage((imageInfo) =>
                    {
                        // Handle any potential errors with retrieving the item image.
                        ImageInfo.ImageRequestState imageRequestState = imageInfo.state;
                        switch (imageRequestState)
                        {
                        case ImageInfo.ImageRequestState.BAD_METADATA:
                            SetStatus("Unable to handle item metadata for the image.");
                            break;

                        case ImageInfo.ImageRequestState.RETRIEVAL_FAILED:
                            SetStatus("Unable to retrieve the reward item's image.");
                            break;

                        case ImageInfo.ImageRequestState.SUCCESS:
                            rewardTokenImage.sprite = imageInfo.image;
                            break;
                        }
                    }));
                    break;
                }
            }
        }));
    }
Пример #10
0
    // On each update, check the current game state and handle logic appropriately.
    void Update()
    {
        // Handle any events posted here from an asynchronous Enjin task.
        for (int i = 0; i < pendingActions.Count; i++)
        {
            System.Action action = pendingActions[i];
            action();
        }
        pendingActions.Clear();

        // Reward the users with a token every time they get 15 clicks.
        if (score >= SCORE_THRESHOLD)
        {
            score = 0;
            SetStatus("Linked successfully.\nYour score is: " + score, false);
            rewardMask.transform.localScale = new Vector3(1, 1, 1);

            // Mint a new token directly from the developer wallet.
            CryptoItem item             = Enjin.GetCryptoItem(REWARD_TOKEN_ID);
            string     reserveCount     = item.reserve;
            int        developerBalance = Enjin.GetCryptoItemBalance(DEVELOPER_IDENTITY_ID, REWARD_TOKEN_ID);
            if (!reserveCount.Equals("0"))
            {
                pending += 1;
                Enjin.MintFungibleItem(DEVELOPER_IDENTITY_ID, new string[] { userAddress }, REWARD_TOKEN_ID, 1,
                                       (requestEvent) =>
                {
                    if (requestEvent.event_type.Equals("tx_executed"))
                    {
                        pending -= 1;
                        count   += 1;
                        pendingActions.Add(() =>
                        {
                            inventory.text = (tokenName + "\nYou have: " + count + "\nCurrently pending: " + pending);
                        });
                    }
                });
                inventory.text = (tokenName + "\nYou have: " + count + "\nCurrently pending: " + pending);
            }

            // If the developer wallet is unable to mint reward tokens from the reserve, try to send it from the developer wallet.
            else if (developerBalance > 0)
            {
                pending += 1;
                Enjin.SendCryptoItemRequest(DEVELOPER_IDENTITY_ID, REWARD_TOKEN_ID, identityId, 1,
                                            (requestEvent) =>
                {
                    if (requestEvent.event_type.Equals("tx_executed"))
                    {
                        pending -= 1;
                        count   += 1;
                        pendingActions.Add(() =>
                        {
                            inventory.text = (tokenName + "\nYou have: " + count + "\nCurrently pending: " + pending);
                        });
                    }
                });
                inventory.text = (tokenName + "\nYou have: " + count + "\nCurrently pending: " + pending);
            }

            // Otherwise there really is nothing of this token left for the developer to give out.
            else
            {
                SetStatus("Uh oh! The game developer is out of reward items!", true);
            }
        }
    }
Пример #11
0
 public CompoundQuery(ProcessTasks task, CryptoItem cryptoItem, Dictionary <string, object> properties)
 {
     this.Task       = task;
     this.CryptoItem = cryptoItem;
     this.Properties = properties;
 }
Пример #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cryptoItem"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private Request SendCreateRequest(CryptoItem cryptoItem, Action <RequestEvent> action)
        {
            Request request = Enjin.CreateCryptoItem(cryptoItem, EnjinEditor.CurrentUserIdentity.id, action);

            return(request);
        }
Пример #13
0
        public void HandleChainedRequestAction(Request request, RequestEvent requestEvent, ProcessTasks task, CryptoItem cryptoItem, Dictionary <string, object> properties)
        {
            Debug.Log("<color=violet>[Handler Request]</color> " + JsonUtility.ToJson(request));

            Result result = new Result
            {
                Type    = Result.Types.CRYPTOITEMS,
                Request = request,
                Refresh = true,
                Message = JsonUtility.ToJson(request),
                Status  = (EnjinEditor.IsRequestSuccessfull(request.state)) ? Status.SUCCESS : Status.FAILURE
            };

            CompoundQuery query = new CompoundQuery(task, requestEvent.data.token, properties);

            result.compoundQueries.Add(query);

            EnjinEditor.NotificationMonitor.ResultsQueue.Add(System.Guid.NewGuid().ToString(), result);
            //_resultQueue.Add(System.Guid.NewGuid().ToString(), result);
        }
Пример #14
0
        internal Request ProcessCryptoItem(ProcessTasks task, CryptoItem cryptoItem, Dictionary <string, object> properties)
        {
            Request request         = new Request();
            string  editMetaDataURI = "";

            switch (task)
            {
            case ProcessTasks.CREATE:
                string minValue = GraphQLClient.GraphQuery.GetEndPointData(Enjin.MeltValueURL + cryptoItem.reserve);

                if (properties.ContainsKey("MeltValue"))
                {
                    decimal actual = (decimal)((float)properties["MeltValue"] * Mathf.Pow(10, 18));

                    if (actual < System.Convert.ToInt64(minValue))
                    {
                        cryptoItem.meltValue = minValue;
                    }
                    else
                    {
                        cryptoItem.meltValue = actual.ToString("0");
                    }
                }
                else
                {
                    cryptoItem.meltValue = minValue;
                }


                if (properties.ContainsKey("MetaDataURI"))
                {
                    request = Enjin.CreateCryptoItem(cryptoItem, EnjinEditor.CurrentUserIdentity.id, ItemCreated => { HandleChainedRequestAction(request, ItemCreated, ProcessTasks.SETURI, cryptoItem, properties); });
                }
                else
                {
                    request = Enjin.CreateCryptoItem(cryptoItem, EnjinEditor.CurrentUserIdentity.id, ItemCreated => { HandleRequestAction(request); });
                }

                return(request);

            case ProcessTasks.DELETE:
                break;

            case ProcessTasks.EDIT:
                if (cryptoItem.isCreator)
                {
                    // handle name changes
                    if (properties.ContainsKey("ItemName"))
                    {
                        string editItemName = (string)properties["ItemName"];

                        if (editItemName != cryptoItem.name)
                        {
                            Debug.Log("running name change");
                            string temp = cryptoItem.name;
                            cryptoItem.name = editItemName;
                            request         = Enjin.UpdateCryptoItem(EnjinEditor.CurrentUserIdentity.id, cryptoItem, CryptoItemFieldType.NAME, ItemUpdated => { HandleRequestAction(request); });
                            cryptoItem.name = temp;
                        }
                    }

                    // handle metadata URI changes
                    if (properties.ContainsKey("MetaDataURI"))
                    {
                        editMetaDataURI = (string)properties["MetaDataURI"];

                        if (editMetaDataURI != cryptoItem.itemURI)
                        {
                            Debug.Log("running meta data URI update");
                            request = Enjin.SetCryptoItemURI(EnjinEditor.CurrentUserIdentity.id, cryptoItem, editMetaDataURI, URISet => { HandleRequestAction(request); });
                        }
                    }

                    return(request);
                }
                return(null);

            case ProcessTasks.MELT:
                int numToMelt = 1;
                if (properties.ContainsKey("NumToMelt"))
                {
                    numToMelt = (int)properties["NumToMelt"];
                }

                if (cryptoItem.nonFungible)
                {
                    Debug.Log("running melt request for non-fungible CI");
                    request = Enjin.MeltTokens(EnjinEditor.CurrentUserIdentity.id, cryptoItem.token_id, cryptoItem.index, numToMelt, MeltItem => { HandleRequestAction(request); });
                }
                else
                {
                    Debug.Log("running melt request for fungible CI");
                    request = Enjin.MeltTokens(EnjinEditor.CurrentUserIdentity.id, cryptoItem.token_id, numToMelt, MeltItem => { HandleRequestAction(request); });
                }

                return(request);

            case ProcessTasks.MINT:
                string[] addresses = new string[] { };
                if (properties.ContainsKey("RecieverAddress"))
                {
                    addresses = (string[])properties["RecieverAddress"];
                }

                if (!cryptoItem.nonFungible)
                {
                    int numToMint = 0;
                    if (properties.ContainsKey("NumToMint"))
                    {
                        numToMint = (int)properties["NumToMint"];
                    }

                    // Request should be pushed to event system to register the request by id, then the action callback should push to a method that fires off the seturi method once executed.
                    request = Enjin.MintFungibleItem(EnjinEditor.CurrentUserIdentity.id, addresses, cryptoItem.token_id, numToMint, ItemMinted => { HandleRequestAction(request); });
                }
                else
                {
                    // Request should be pushed to event system to register the request by id, then the action callback should push to a method that fires off the seturi method once executed.
                    request = Enjin.MintNonFungibleItem(EnjinEditor.CurrentUserIdentity.id, addresses, cryptoItem.token_id, ItemMinted => { HandleRequestAction(request); });
                }

                return(request);

            case ProcessTasks.SETURI:
                // handle metadata URI changes
                if (properties.ContainsKey("MetaDataURI"))
                {
                    editMetaDataURI = (string)properties["MetaDataURI"];

                    if (editMetaDataURI != cryptoItem.itemURI)
                    {
                        Debug.Log("running meta data URI update");
                        request = Enjin.SetCryptoItemURI(EnjinEditor.CurrentUserIdentity.id, cryptoItem, editMetaDataURI, URISet => { HandleRequestAction(request); });
                    }
                }

                return(request);

            default:
                break;
            }

            return(null);
        }