public void OpenMenu(Async.EventDelegate onFinish = null)
 {
     if (closed)
     {
         gameObject.SetActive(true);
         scaleMenuUp = GrowMenu(onFinish);
         StartCoroutine(scaleMenuUp);
     }
     else if (closing)
     {
         StopCoroutine(scaleMenuDown);
         scaleMenuUp = GrowMenu(onFinish);
         StartCoroutine(scaleMenuUp);
     }
 }
Exemple #2
0
        public static IEnumerator InitializeContracts(Async.EventDelegate onError = null)
        {
            using (WWW www = new WWW(artifactsURL))
            {
                yield return(www);

                if (www.error != null)
                {
                    Debug.Log("Error making request. Either your internet is down...or Cortex is down. Fingers crossed its the internet :)");
                    onError?.Invoke(www.error);
                    yield break;
                }

                var response = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                var data     = response["data"] as Dictionary <string, object>;

                var token        = data["token"] as Dictionary <string, object>;
                var tokenAbi     = serializer.SerializeString(token["abi"]);
                var tokenAddress = token["address"].ToString();
                if (MatryxToken.contract == null)
                {
                    MatryxToken.setContract(tokenAbi, tokenAddress);
                }

                var platform        = data["platform"] as Dictionary <string, object>;
                var platformAbi     = serializer.SerializeString(platform["abi"]);
                var platformAddress = platform["address"] as string;
                if (MatryxPlatform.contract == null)
                {
                    MatryxPlatform.setContract(platformAbi, platformAddress);
                }

                var commit        = data["commit"] as Dictionary <string, object>;
                var commitAbi     = serializer.SerializeString(commit["abi"]);
                var commitAddress = commit["address"] as string;
                if (MatryxCommit.contract == null)
                {
                    MatryxCommit.setContract(commitAbi, commitAddress);
                }

                var tournament    = data["tournament"] as Dictionary <string, object>;
                var tournamentAbi = serializer.SerializeString(tournament["abi"]);
                if (MatryxTournament.ABI == null)
                {
                    MatryxTournament.ABI = tournamentAbi;
                }
            }
        }
Exemple #3
0
        private static IEnumerator GetMyCommits(Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        {
            var url = myCommitsURL + NetworkSettings.currentAddress;

            using (var www = new WWW(url))
            {
                yield return(www);

                if (www.error != null)
                {
                    Debug.Log("Error getting commits: " + www.error);
                    onError?.Invoke(www.error);
                    yield break;
                }

                var commits = new List <MatryxCommit>();
                try
                {
                    Debug.Log(www.text);
                    var res         = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                    var data        = res["data"] as Dictionary <string, object>;
                    var jsonCommits = data["commits"] as List <object>;

                    foreach (Dictionary <string, object> jsonCommit in jsonCommits)
                    {
                        MatryxCommit commit = new MatryxCommit();
                        commit.hash            = jsonCommit["hash"] as string;
                        commit.owner           = jsonCommit["owner"] as string;
                        commit.parentHash      = jsonCommit["parentHash"] as string;
                        commit.ipfsContentHash = jsonCommit["ipfsContent"] as string;
                        commit.height          = BigInteger.Parse(jsonCommit["height"].ToString());
                        commit.value           = BigInteger.Parse(jsonCommit["value"].ToString());
                        commit.ownerTotalValue = BigInteger.Parse(jsonCommit["ownerTotalValue"].ToString());
                        commit.totalValue      = BigInteger.Parse(jsonCommit["totalValue"].ToString());
                        commit.timestamp       = BigInteger.Parse(jsonCommit["timestamp"].ToString());
                        commit.mine            = true;
                        commits.Add(commit);
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                    onError?.Invoke(commits);
                }

                onSuccess?.Invoke(commits);
            }
        }
Exemple #4
0
    public void PostFailure(MatryxTournament tournament, string message = null, Async.EventDelegate onReturn = null)
    {
        if (message != null)
        {
            SetStatus(message);
        }
        else
        {
            SetStatus("Failed to create " + tournament.title);
        }

        severalMinutesText.gameObject.SetActive(false);
        mayReturn.gameObject.SetActive(true);
        tryAgainButton.gameObject.SetActive(true);
        StartCoroutine(ReturnToCalcflowAfterSeconds(3f, onReturn));
    }
    IEnumerator ScaleTo(Transform obj, Vector3 start, Vector3 end, float overTime, Async.EventDelegate whenDone = null)
    {
        float startTime = Time.time;

        while (Time.time < startTime + overTime)
        {
            if (obj == null)
            {
                yield break;
            }
            obj.localScale = Vector3.Lerp(start, end, (Time.time - startTime) / overTime);
            yield return(null);
        }

        obj.localScale = end;
        whenDone?.Invoke(this);
    }
        public IEnumerator closeTournament(Async.EventDelegate onComplete = null)
        {
            var transactionRequest = new TransactionSignedUnityRequest(NetworkSettings.infuraProvider, NetworkSettings.currentPrivateKey);

            yield return(transactionRequest.SignAndSendTransaction <CloseTournamentFunction>(new CloseTournamentFunction()
            {
                Gas = NetworkSettings.txGas, GasPrice = NetworkSettings.txGasPrice
            }, address));

            var getTransactionStatus = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, Utils.GetTransactionStatus(transactionRequest, "closeTournament", null));

            yield return(getTransactionStatus);

            yield return(getTransactionStatus.result);

            onComplete?.Invoke(getTransactionStatus.result);
        }
        public IEnumerator updateNextRound(MatryxRound.RoundDetails newDetails, Async.EventDelegate onComplete = null)
        {
            var transactionRequest = new TransactionSignedUnityRequest(NetworkSettings.infuraProvider, NetworkSettings.currentPrivateKey);

            yield return(transactionRequest.SignAndSendTransaction <UpdateNextRoundFunction>(new UpdateNextRoundFunction()
            {
                RDetails = newDetails, Gas = NetworkSettings.txGas, GasPrice = NetworkSettings.txGasPrice
            }, address));

            var getTransactionStatus = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, Utils.GetTransactionStatus(transactionRequest, "updateNextRound", null));

            yield return(getTransactionStatus);

            yield return(getTransactionStatus.result);

            onComplete?.Invoke(getTransactionStatus.result);
        }
Exemple #8
0
    public void fadeEarly(float fadeDuration, Async.EventDelegate onDone = null)
    {
        if (lifeCoroutine != null)
        {
            fadeOutDuration = fadeDuration;
            StopCoroutine(lifeCoroutine);
            lifeCoroutine = null;
        }

        try
        {
            fadeOut(onDone);
        }
        catch (System.Exception e)
        {
            Debug.Log("Your tippy callback tried to do something bad: " + e);
        }
    }
Exemple #9
0
        public IEnumerator get(Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
        {
            var url = MatryxCortex.submissionURL + hash;

            using (var submissionWWW = new WWW(url))
            {
                yield return(submissionWWW);

                var res        = MatryxCortex.serializer.Deserialize <object>(submissionWWW.bytes) as Dictionary <string, object>;
                var data       = res["data"] as Dictionary <string, object>;
                var submission = data["submission"] as Dictionary <string, object>;

                this.title              = submission["title"] as string;
                this.description        = submission["description"] as string;
                this.hash               = submission["hash"] as string;
                this.tournament.address = submission["tournament"] as string;
                this.commit.hash        = (submission["commit"] as Dictionary <string, object>)["hash"] as string;
                var ipfsHash = (submission["commit"] as Dictionary <string, object>)["ipfsContent"] as string;
                this.commit.ipfsContentHash = ipfsHash;
                this.dto.TournamentAddress  = submission["tournament"] as string;
                this.dto.RoundIndex         = BigInteger.Parse(submission["roundIndex"].ToString());
                this.dto.CommitHash         = Utils.HexStringToByteArray(this.commit.hash);
                this.dto.Content            = submission["ipfsContent"] as string;
                var reward = new BigInteger(decimal.Parse(submission["reward"].ToString()) * (decimal)1e18);
                this.dto.Reward    = reward;
                this.dto.Timestamp = BigInteger.Parse(submission["timestamp"].ToString());

                using (WWW ipfsWWW = new WWW(MatryxCortex.ipfsCatURL + ipfsHash))
                {
                    yield return(ipfsWWW);

                    if (submissionWWW.error != null)
                    {
                        onError?.Invoke(submissionWWW);
                    }
                    commit.content = Utils.Substring(ipfsWWW.text as string, '{', '}');
                }

                var ESSRegEx = "{.*rangeKeys.*rangePairs.*ExpressionKeys.*ExpressionValues.*}";
                calcflowCompatible = Regex.IsMatch(commit.content, ESSRegEx);

                onSuccess?.Invoke(this);
            }
        }
Exemple #10
0
        public IEnumerator claim(Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null, Async thread = null)
        {
            ResultsMenu.Instance?.SetStatus("Uploading Content...");
            var contentUploader = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, uploadContent());

            yield return(contentUploader);

            if (claims.ContainsKey(ipfsContentHash))
            {
                onError?.Invoke(null);
                yield return(false);

                yield break;
            }

            ResultsMenu.Instance?.SetStatus("Hashing Content to Matryx...");
            Claim claim = new Claim(ipfsContentHash, content);
            var   transactionRequest = new TransactionSignedUnityRequest(NetworkSettings.infuraProvider, NetworkSettings.currentPrivateKey);
            var   claimCommitMsg     = new ClaimCommitFunction()
            {
                ClaimHash = claim.claimHash, Gas = NetworkSettings.txGas, GasPrice = NetworkSettings.txGasPrice
            };

            yield return(transactionRequest.SignAndSendTransaction(claimCommitMsg, address));

            var txStatus = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, Utils.GetTransactionStatus(transactionRequest, "claimCommit", thread));

            yield return(txStatus);

            if (txStatus.result)
            {
                claims.Add(ipfsContentHash, claim);
                // Save screenshot and claimed content locally
                ExpressionSaveLoad.Instance.SaveClaim(this);
                storeClaimLocally(claim);
                onSuccess?.Invoke(claim);
            }
            else
            {
                onError?.Invoke(claim);
            }

            yield return(txStatus.result);
        }
        public IEnumerator getRoundDetails(BigInteger roundIndex, Async.EventDelegate onSuccess, Async.EventDelegate onFailure)
        {
            var request = new QueryUnityRequest <GetRoundDetailsFunction, MatryxRound.RoundDetails>(NetworkSettings.infuraProvider, NetworkSettings.currentAddress);

            yield return(request.Query(new GetRoundDetailsFunction()
            {
                RoundIndex = roundIndex
            }, address));

            yield return(request.Result);

            if (request.Result.Review > 0)
            {
                onSuccess?.Invoke(request.Result);
            }
            else
            {
                onFailure?.Invoke(request.Result);
            }
        }
Exemple #12
0
        public IEnumerator create(Async.EventDelegate onSuccess = null, Async.EventDelegate onFailure = null)
        {
            ResultsMenu.Instance?.SetStatus("Committing Content to Matryx...");
            Claim claim = getClaim(ipfsContentHash);
            var   transactionRequest = new TransactionSignedUnityRequest(NetworkSettings.infuraProvider, NetworkSettings.currentPrivateKey);
            var   createCommitMsg    = new CreateCommitFunction()
            {
                ParentHash  = parentHash,
                IsFork      = fork,
                Salt        = claim.salt,
                ContentHash = ipfsContentHash,
                Value       = value,
                Gas         = NetworkSettings.txGas,
                GasPrice    = NetworkSettings.txGasPrice
            };

            yield return(transactionRequest.SignAndSendTransaction <CreateCommitFunction>(createCommitMsg, address));

            var txStatus = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, Utils.GetTransactionStatus(transactionRequest, "createCommit", null));

            yield return(txStatus);

            if (!txStatus.result)
            {
                onFailure?.Invoke(null);
                yield break;
            }

            // Get commit hash and assign to this commit
            var getCommit = new Utils.CoroutineWithData <CommitOutputDTO>(MatryxCortex.Instance, getCommitByContent(ipfsContentHash));

            yield return(getCommit);

            hash = getCommit.result.outCommit.CommitHash.ToHex(true);
            yield return(txStatus.result);

            onSuccess?.Invoke(hash);
        }
Exemple #13
0
        private static IEnumerator GetTournaments(long page, float waitTime, bool onlyMine, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
        {
            if (waitTime > 0)
            {
                yield return(new WaitForSeconds(waitTime));
            }

            var tournaments = new List <MatryxTournament>();
            var offset      = page * 10;
            var url         = onlyMine ? myTournamentsURL + NetworkSettings.currentAddress : tournamentsURL;

            using (WWW www = new WWW(url))
            {
                yield return(www);

                if (www.error != null)
                {
                    Debug.Log("Error making request. Matryx Cortex down!!");
                    onError?.Invoke(www.error);
                    yield break;
                }

                var response = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                var data     = response["data"] as Dictionary <string, object>;

                var tournamentList = data["tournaments"] as List <object>;
                for (int i = 0; i < tournamentList.Count; i++)
                {
                    var jsonTournament = tournamentList[i] as Dictionary <string, object>;
                    var jsonRound      = jsonTournament["round"] as Dictionary <string, object>;

                    string category = jsonTournament["category"] as string;
                    if (!supportedCalcflowCategories.Contains(category))
                    {
                        continue;
                    }

                    var owner = jsonTournament["owner"] as string;
                    if (onlyMine && !owner.Equals(NetworkSettings.currentAddress, StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }
                    else if (!onlyMine)
                    {
                        var status = jsonRound["status"] as string;
                        if (!status.Equals("open", StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                    }

                    var tournamentTitle = jsonTournament["title"] as string;
                    var bounty          = new BigInteger((long)Convert.ToDouble(jsonTournament["bounty"])) * new BigInteger(1e18);
                    var entryFee        = new BigInteger((long)Convert.ToDouble(jsonTournament["entryFee"])) * new BigInteger(1e18);
                    var tournament      = new MatryxTournament(jsonTournament["address"] as string, tournamentTitle, bounty, entryFee);
                    tournament.description = jsonTournament["description"] as string;
                    tournament.owner       = owner;

                    var idx               = Convert.ToInt32(jsonRound["index"] as string);
                    var roundStart        = DateTime.Parse(jsonRound["startDate"] as string);
                    var roundEnd          = DateTime.Parse(jsonRound["endDate"] as string);
                    var roundReviewEnd    = DateTime.Parse(jsonRound["reviewEndDate"] as string);
                    var roundBounty       = Convert.ToDecimal(jsonRound["bounty"]);
                    var roundParticipants = Convert.ToInt32(jsonRound["totalParticipants"]);
                    var roundSubmissions  = Convert.ToInt32(jsonRound["totalSubmissions"]);
                    tournament.currentRound = new MatryxRound()
                    {
                        tournament        = tournament,
                        index             = idx,
                        startDate         = roundStart,
                        endDate           = roundEnd,
                        reviewEndDate     = roundReviewEnd,
                        Bounty            = roundBounty,
                        totalParticipants = roundParticipants,
                        totalSubmissions  = roundSubmissions
                    };

                    tournaments.Add(tournament);
                }

                onSuccess?.Invoke(tournaments);
            }
        }
Exemple #14
0
        // UPLOAD SUBMISSION
        public static void RunUploadSubmission(MatryxSubmission submission, Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        {
            // Schedule query
            Async submit = Async.runInCoroutine(delegate(Async thread, object param)
            {
                return(submission.submit());
            });

            submit.onEvent("submit", onSuccess);
        }
Exemple #15
0
        //public static IEnumerator GetIPFSJSONContent(string ipfsHash, string elementName = "", Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        //{
        //    var objectURL = ipfsObjURL + ipfsHash;
        //    using (var contwww = new WWW(objectURL))
        //    {
        //        yield return contwww;
        //        try
        //        {
        //            var res = serializer.Deserialize<object>(contwww.bytes) as Dictionary<string, object>;
        //            var data = res["Data"] as string;

        //            var jsonRegex = "{.*}";
        //            var json = data.


        //        }
        //        catch(System.Exception e)
        //        {
        //            onError("Could not fetch json: " + e);
        //        }
        //    }
        //}

        public static IEnumerator GetIPFSFilesContent(string ipfsHash, string elementName = "", Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        {
            var objectURL = ipfsObjURL + ipfsHash;
            Dictionary <string, object> res;
            List <object> links;
            int           index;
            Dictionary <string, object> theEntry;
            string linkUrl = "";

            bool error = false;
            bool link  = false;

            using (var contwww = new WWW(objectURL))
            {
                yield return(contwww);

                try
                {
                    res   = serializer.Deserialize <object>(contwww.bytes) as Dictionary <string, object>;
                    links = res["Links"] as List <object>;
                    index = links.IndexOfElementMatchingRegex <object, string>(@"^Qm[0-9a-zA-Z]{44}$");
                    if (index != -1)
                    {
                        link     = true;
                        theEntry = links[index] as Dictionary <string, object>;
                        linkUrl  = ipfsCatURL + theEntry["Hash"] as string;
                    }
                    else
                    {
                        onSuccess(res["Data"]);
                    }
                }
                catch (System.Exception e)
                {
                    onError?.Invoke(null);
                    error = true;
                }
            }

            if (error)
            {
                yield break;
            }

            var catURL = link ? linkUrl : ipfsCatURL + ipfsHash;

            using (var itemWWW = new WWW(catURL))
            {
                yield return(itemWWW);

                onSuccess?.Invoke(itemWWW.text);
                yield break;
            }
        }
Exemple #16
0
 public static void RunGetRound(MatryxTournament tournament, int roundIndex, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
 {
     Async main = Async.runInCoroutine(delegate(Async thread, object param)
     {
         return(GetRound(tournament, roundIndex, onSuccess, onError));
     });
 }
Exemple #17
0
 public static void GetMTXBalance(Async.EventDelegate onSuccess)
 {
     Instance.StartCoroutine(MTXBalanceCoroutine(onSuccess));
 }
Exemple #18
0
 public static void RunGetMyCommits(Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
 {
     queue(GetMyCommits(onSuccess, onError));
 }
Exemple #19
0
 public static void RunGetCommit(string commitHash, bool getContent, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
 {
     queue(GetCommit(commitHash, getContent, onSuccess, onError));
 }
Exemple #20
0
        public static IEnumerator GetMySubmissions(MatryxTournament tournament, float waitTime, Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        {
            if (waitTime > 0)
            {
                yield return(new WaitForSeconds(waitTime));
            }

            var url = mySubmissionsURL + NetworkSettings.currentAddress;

            using (var www = new WWW(url))
            {
                yield return(www);

                var submissions = new List <MatryxSubmission>();
                try
                {
                    var res            = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                    var data           = res["data"] as Dictionary <string, object>;
                    var submissionData = data["submissions"] as List <object>;

                    foreach (Dictionary <string, object> submissionDictionary in submissionData)
                    {
                        if (submissionDictionary["tournament"] as string != tournament.address)
                        {
                            continue;
                        }
                        var title                   = submissionDictionary["title"] as string;
                        var description             = submissionDictionary["description"] as string;
                        var hash                    = submissionDictionary["hash"] as string;
                        MatryxSubmission submission = new MatryxSubmission(tournament, title, hash, description);
                        submissions.Add(submission);
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                    onError?.Invoke(submissions);
                }

                onSuccess?.Invoke(submissions);
            }
        }
Exemple #21
0
 public static void RunGetMySubmissions(MatryxTournament tournament, float waitTime = 0, Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
 {
     queue(GetMySubmissions(tournament, waitTime, onSuccess, onError));
 }
Exemple #22
0
 public static void GetSubmission(MatryxSubmission submission, Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
 {
     queue(submission.get(onSuccess, onError));
 }
Exemple #23
0
        public static IEnumerator GetRound(MatryxTournament tournament, int roundIndex, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
        {
            var round = new MatryxRound(roundIndex);

            round.tournament = tournament;
            var winningSubmissions = new List <MatryxSubmission>();

            using (WWW www = new WWW(tournamentURL + tournament.address + "/round/" + roundIndex))
            {
                yield return(www);

                if (www.error != null)
                {
                    Debug.Log("Error making request. Matryx Cortex down!!");
                    onError?.Invoke(www.error);
                    yield break;
                }

                try
                {
                    var jsonObj = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                    if (jsonObj.ContainsKey("error"))
                    {
                        onError?.Invoke(null);
                    }
                    else if (jsonObj.ContainsKey("success"))
                    {
                        var data      = jsonObj["data"] as Dictionary <string, object>;
                        var jsonRound = data["round"] as Dictionary <string, object>;
                        round.Details.Bounty = new BigInteger(Convert.ToDecimal(jsonRound["bounty"])) * new BigInteger(1e18);
                        var startDate = DateTime.Parse(jsonRound["startDate"] as string);
                        var endDate   = DateTime.Parse(jsonRound["endDate"] as string);
                        round.Details.Start    = new BigInteger(Utils.Time.ToUnixTime(startDate));
                        round.Details.Duration = new BigInteger((endDate - startDate).TotalSeconds);

                        var roundWinners = jsonRound["winners"] as List <object>;
                        for (int i = 0; i < roundWinners.Count; i++)
                        {
                            var submission = new MatryxSubmission(roundWinners[i] as string);
                            winningSubmissions.Add(submission);
                        }
                        round.winningSubmissions = winningSubmissions;

                        onSuccess(round);
                    }
                }
                catch (System.Exception e)
                {
                    Debug.Log(e);
                    onError?.Invoke(null);
                }
            }
        }
Exemple #24
0
        public IEnumerator submit(Async.EventDelegate callback = null)
        {
            StatisticsTracking.StartEvent("Matryx", "Submission Creation");

            ResultsMenu.transactionObject = this;
            var isEntrant = new Utils.CoroutineWithData <EthereumTypes.Bool>(MatryxCortex.Instance, tournament.isEntrant(NetworkSettings.currentAddress));

            yield return(isEntrant);

            var tournamentInfo = new Utils.CoroutineWithData <TournamentInfo>(MatryxCortex.Instance, tournament.getInfo());

            yield return(tournamentInfo);

            if (tournament.owner.Equals(NetworkSettings.currentAddress, System.StringComparison.CurrentCultureIgnoreCase))
            {
                ResultsMenu.Instance.PostFailure(this, "You own this tournament; Unable to create submission.");
                yield break;
            }

            if (!isEntrant.result.Value)
            {
                var allowance = new Utils.CoroutineWithData <BigInteger>(MatryxCortex.Instance, MatryxToken.allowance(NetworkSettings.currentAddress, MatryxPlatform.address));
                yield return(allowance);

                var balance = new Utils.CoroutineWithData <BigInteger>(MatryxCortex.Instance, MatryxToken.balanceOf(NetworkSettings.currentAddress));
                yield return(balance);

                if (balance.result < tournament.entryFee)
                {
                    ResultsMenu.Instance.SetStatus("Insufficient MTX. Please visit <link=https://app.matryx.ai/><u>our Matryx Dapp</u></link> for MTX Tokens.", true);
                    yield break;
                }

                if (allowance.result < tournament.entryFee)
                {
                    ResultsMenu.Instance.SetStatus("Approving entry fee...");

                    if (allowance.result != BigInteger.Zero)
                    {
                        var approveZero = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, MatryxToken.approve(MatryxPlatform.address, BigInteger.Zero));
                        yield return(approveZero);

                        if (!approveZero.result)
                        {
                            Debug.Log("Failed to reset tournament's allowance to zero for this user. Please check the allowance this user has granted the tournament");
                            ResultsMenu.Instance.PostFailure(this);
                            yield break;
                        }
                    }

                    var approveEntryFee = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, MatryxToken.approve(MatryxPlatform.address, tournament.entryFee));
                    yield return(approveEntryFee);

                    if (!approveEntryFee.result)
                    {
                        Debug.Log("Failed to set the tournament's allowance from this user to the tournament's entry fee");
                        ResultsMenu.Instance.PostFailure(this);
                        yield break;
                    }
                }

                ResultsMenu.Instance.SetStatus("Entering Tournament...");

                var enterTournament = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, tournament.enter());
                yield return(enterTournament);

                if (!enterTournament.result)
                {
                    Debug.Log("Failed to enter tournament");
                    ResultsMenu.Instance.PostFailure(this);
                    yield break;
                }
            }

            ResultsMenu.Instance.SetStatus("Claiming Content...");
            bool shouldBreak = false;

            yield return(commit.claim((res) => { },
                                      (nada) =>
            {
                ResultsMenu.Instance.PostFailure(this, "Could not claim your content on Matryx...");
                shouldBreak = true;
            }));

            if (shouldBreak)
            {
                yield break;
            }

            ResultsMenu.Instance.SetStatus("Hashing to Matryx...");
            yield return(commit.create());

            ResultsMenu.Instance.SetStatus("Uploading submission content...");
            yield return(uploadContent());

            if (!dto.Content.Contains("Qm"))
            {
                Debug.Log("Failed to upload file to IPFS");
                ResultsMenu.Instance.PostFailure(this);
                yield break;
            }

            ResultsMenu.Instance.SetStatus("Creating Submission in Matryx...");
            var createSubmission = new Utils.CoroutineWithData <bool>(MatryxCortex.Instance, tournament.createSubmission(this));

            yield return(createSubmission);

            callback?.Invoke(createSubmission.result);

            if (!createSubmission.result)
            {
                Debug.Log("Failed to create submission");
                yield break;
            }
        }
Exemple #25
0
 public static void RunGetTournament(string tournamentAddress, bool getDescription, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
 {
     // Schedule query
     Async main = Async.runInCoroutine(delegate(Async thread, object param)
     {
         return(GetTournament(tournamentAddress, getDescription, onSuccess, onError));
     });
 }
Exemple #26
0
        public static IEnumerator uploadFiles(List <string> fileNames, List <string> contents, string urlModifier = "", Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
        {
            List <IMultipartFormSection> formData = new List <IMultipartFormSection>();

            for (var i = 0; i < fileNames.Count; i++)
            {
                formData.Add(new MultipartFormFileSection("path", contents[i], Encoding.UTF8, fileNames[i]));
            }

            UnityWebRequest request = UnityWebRequest.Post(filesUploadURL + urlModifier, formData);

            yield return(request.SendWebRequest());

            Debug.Log("request completed with code: " + request.responseCode);
            if (request.isNetworkError || request.responseCode != 200)
            {
                Debug.Log("Error: " + request.error);
                onError?.Invoke(request);
            }
            else
            {
                var lastLine = Encoding.UTF8.GetBytes(request.downloadHandler.text.Trim().Split('\n').Last());
                var res      = serializer.Deserialize <object>(lastLine) as Dictionary <string, object>;

                string multiHash = res["Hash"] as string;

                onSuccess?.Invoke(multiHash);
                yield return(multiHash);
            }

            yield return("You should never see this :)");
        }
Exemple #27
0
 public static void RunGetMyTournaments(long page, float waitTime, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
 {
     // Schedule query
     Async main = Async.runInCoroutine(delegate(Async thread, object param)
     {
         return(GetTournaments(page, waitTime, true, onSuccess, onError));
     });
 }
Exemple #28
0
 public static void RunGetJSONContent(string ipfsHash, Async.EventDelegate onSuccess = null, Async.EventDelegate onError = null)
 {
     queueMetered(GetIPFSFilesContent(ipfsHash, "Qm", onSuccess, onError));
 }
Exemple #29
0
        private static IEnumerator GetCommit(string commitHash, bool getContent, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
        {
            var url = commitURL + commitHash;

            using (var www = new WWW(url))
            {
                yield return(www);

                MatryxCommit commit = new MatryxCommit();
                try
                {
                    Debug.Log(www.text);
                    var res        = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                    var data       = res["data"] as Dictionary <string, object>;
                    var commitData = data["commit"] as Dictionary <string, object>;

                    commit.hash            = commitData["hash"] as string;
                    commit.owner           = commitData["owner"] as string;
                    commit.parentHash      = commitData["parentHash"] as string;
                    commit.ipfsContentHash = commitData["ipfsContent"] as string;
                    commit.height          = BigInteger.Parse(commitData["height"].ToString());
                    commit.value           = BigInteger.Parse(commitData["value"].ToString());
                    commit.ownerTotalValue = BigInteger.Parse(commitData["ownerTotalValue"].ToString());
                    commit.totalValue      = BigInteger.Parse(commitData["totalValue"].ToString());
                    commit.timestamp       = BigInteger.Parse(commitData["timestamp"].ToString());

                    if (getContent)
                    {
                        RunGetJSONContent(commit.ipfsContentHash,
                                          (cont) =>
                        {
                            commit.content = Utils.Substring(cont as string, '{', '}');
                            if (commit.content == "")
                            {
                                onError(cont);
                            }
                            else
                            {
                                onSuccess?.Invoke(commit);
                            }
                        }, onError);
                    }
                    else
                    {
                        onSuccess?.Invoke(commit);
                    }
                }
                catch (Exception e)
                {
                    Debug.Log("Could not fetch details of commit with content: " + commitHash);
                    Debug.Log(e);
                    onError?.Invoke(null);
                }

                yield return(commit);
            }
        }
Exemple #30
0
        private static IEnumerator GetTournament(string tournamentAddress, bool getDescription, Async.EventDelegate onSuccess, Async.EventDelegate onError = null)
        {
            var tournament         = new MatryxTournament(tournamentAddress);
            var winningSubmissions = new List <MatryxSubmission>();

            using (WWW www = new WWW(tournamentURL + tournamentAddress))
            {
                yield return(www);

                if (www.error != null)
                {
                    Debug.Log("Error making request. Matryx Cortex down!!");
                    onError?.Invoke(www.error);
                    yield break;
                }

                try
                {
                    var jsonObj = serializer.Deserialize <object>(www.bytes) as Dictionary <string, object>;
                    if (jsonObj.ContainsKey("error"))
                    {
                        onError?.Invoke(null);
                    }
                    else if (jsonObj.ContainsKey("success"))
                    {
                        var data           = jsonObj["data"] as Dictionary <string, object>;
                        var jsonTournament = data["tournament"] as Dictionary <string, object>;
                        tournament.owner       = jsonTournament["owner"] as string;
                        tournament.contentHash = jsonTournament["ipfsContent"] as string;
                        tournament.title       = jsonTournament["title"] as string;
                        tournament.Bounty      = new BigInteger(Convert.ToDecimal(jsonTournament["bounty"]));
                        tournament.description = jsonTournament["description"] as string;

                        var jsonRound = jsonTournament["round"] as Dictionary <string, object>;
                        tournament.currentRound = new MatryxRound(Convert.ToInt32(jsonRound["index"]));
                        var        idx               = Convert.ToInt32(jsonRound["index"] as string);
                        var        roundClosed       = (jsonRound["status"] as string).Equals("closed");
                        var        roundStart        = DateTime.Parse(jsonRound["startDate"] as string);
                        var        roundEnd          = DateTime.Parse(jsonRound["endDate"] as string);
                        BigInteger duration          = new BigInteger((roundEnd - roundStart).TotalSeconds);
                        var        roundReviewEnd    = DateTime.Parse(jsonRound["reviewEndDate"] as string);
                        var        roundBounty       = Convert.ToDecimal(jsonRound["bounty"]);
                        var        roundParticipants = Convert.ToInt32(jsonRound["totalParticipants"]);
                        var        roundSubmissions  = Convert.ToInt32(jsonRound["totalSubmissions"]);
                        tournament.currentRound = new MatryxRound()
                        {
                            tournament        = tournament,
                            index             = idx,
                            closed            = roundClosed,
                            startDate         = roundStart,
                            endDate           = roundEnd,
                            reviewEndDate     = roundReviewEnd,
                            Bounty            = roundBounty,
                            totalParticipants = roundParticipants,
                            totalSubmissions  = roundSubmissions
                        };

                        tournament.currentRound.Details.Start    = new BigInteger(Utils.Time.ToUnixTime(roundStart));
                        tournament.currentRound.Details.Duration = duration;

                        Dictionary <string, MatryxSubmission> submissionDictionary = new Dictionary <string, MatryxSubmission>();
                        if (roundEnd < DateTime.Now)
                        {
                            var tournamentSubmissions = jsonRound["submissions"] as List <object>;
                            for (int i = 0; i < tournamentSubmissions.Count; i++)
                            {
                                var jsonSubmission = tournamentSubmissions[i] as Dictionary <string, object>;
                                var subHash        = jsonSubmission["hash"] as string;
                                var subOwner       = jsonSubmission["owner"] as string;
                                var subTitle       = jsonSubmission["title"] as string;
                                var subDesc        = jsonSubmission["description"] as string;
                                var subReward      = Convert.ToInt32(jsonSubmission["reward"] as string);
                                var subTimestamp   = Convert.ToDecimal(jsonSubmission["timestamp"] as string);

                                var submission = new MatryxSubmission(tournament, subTitle, subHash, subDesc)
                                {
                                    owner     = subOwner,
                                    Reward    = subReward,
                                    Timestamp = subTimestamp
                                };

                                tournament.currentRound.allSubmissions.Add(submission);
                                submissionDictionary.Add(submission.hash, submission);
                            }
                        }

                        var roundWinners = jsonRound["winners"] as List <object>;
                        for (int i = 0; i < roundWinners.Count; i++)
                        {
                            var winningSubmission = submissionDictionary[roundWinners[i] as string];
                            winningSubmissions.Add(winningSubmission);
                        }

                        tournament.currentRound.winningSubmissions = winningSubmissions;
                        onSuccess(tournament);
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                    onError?.Invoke(null);
                }
            }
        }