< Summary

Class:TheGraph
Assembly:TheGraph
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/ServiceProviders/TheGraph/TheGraph.cs
Covered lines:54
Uncovered lines:40
Coverable lines:94
Total lines:211
Line coverage:57.4% (54 of 94)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
TheGraph()0%110100%
Query(...)0%2100%
Query(...)0%8.18088.24%
QueryLands(...)0%2100%
QueryLands(...)0%6.976070%
QueryPolygonMana(...)0%110100%
QueryNftCollections(...)0%12300%
Dispose()0%110100%
ProcessReceivedLandsData(...)0%3.173073.33%
ProcessReceivedNftData(...)0%12300%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/ServiceProviders/TheGraph/TheGraph.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Text.RegularExpressions;
 5using DCL;
 6using DCL.Helpers;
 7using Newtonsoft.Json.Linq;
 8using UnityEngine;
 9using UnityEngine.Networking;
 10
 11public class TheGraph : ITheGraph
 12{
 13    private const float DEFAULT_CACHE_TIME = 5 * 60;
 14    private const string LAND_SUBGRAPH_URL_ORG = "https://api.thegraph.com/subgraphs/name/decentraland/land-manager";
 15    private const string LAND_SUBGRAPH_URL_ZONE = "https://api.thegraph.com/subgraphs/name/decentraland/land-manager-rop
 16    private const string LAND_SUBGRAPH_URL_MATIC = "https://api.thegraph.com/subgraphs/name/decentraland/mana-matic-main
 17    private const string NFT_COLLECTIONS_SUBGRAPH_URL_ETHEREUM = "https://api.thegraph.com/subgraphs/name/decentraland/c
 18    private const string NFT_COLLECTIONS_SUBGRAPH_URL_MATIC = "https://api.thegraph.com/subgraphs/name/decentraland/coll
 19
 67120    private readonly IDataCache<List<Land>> landQueryCache = new DataCache<List<Land>>();
 21
 022    public Promise<string> Query(string url, string query) { return Query(url, query, null); }
 23
 24    public Promise<string> Query(string url, string query, QueryVariablesBase variables)
 25    {
 626        Promise<string> promise = new Promise<string>();
 27
 628        if (string.IsNullOrEmpty(query) || string.IsNullOrEmpty(url))
 29        {
 030            promise.Reject($"error: {(string.IsNullOrEmpty(url) ? "url" : "query")} is empty");
 031            return promise;
 32        }
 33
 634        string queryJson = $"\"query\":\"{Regex.Replace(query, @"\p{C}+", string.Empty)}\"";
 635        string variablesJson = variables != null ? $",\"variables\":{JsonUtility.ToJson(variables)}" : string.Empty;
 636        string bodyString = $"{{{queryJson}{variablesJson}}}";
 37
 638        var request = new UnityWebRequest();
 639        request.url = url;
 640        request.method = UnityWebRequest.kHttpVerbPOST;
 641        request.downloadHandler = new DownloadHandlerBuffer();
 642        request.uploadHandler = new UploadHandlerRaw(string.IsNullOrEmpty(bodyString) ? null : Encoding.UTF8.GetBytes(bo
 643        request.SetRequestHeader("Content-Type", "application/json");
 644        request.timeout = 60;
 45
 646        var operation = request.SendWebRequest();
 47
 648        operation.completed += asyncOperation =>
 49        {
 650            if (request.WebRequestSucceded())
 51            {
 652                promise.Resolve(request.downloadHandler.text);
 653            }
 54            else
 55            {
 056                promise.Reject($"error: {request.error} response: {request.downloadHandler.text}");
 57            }
 58
 659            request.Dispose();
 660        };
 61
 662        return promise;
 63    }
 64
 065    public Promise<List<Land>> QueryLands(string network, string address) { return QueryLands(network, address, DEFAULT_
 66
 67    public Promise<List<Land>> QueryLands(string network, string address, float cacheMaxAgeSeconds)
 68    {
 469        string lowerCaseAddress = address.ToLower();
 70
 471        Promise<List<Land>> promise = new Promise<List<Land>>();
 72
 473        if (cacheMaxAgeSeconds >= 0)
 74        {
 475            if (landQueryCache.TryGet(lowerCaseAddress, out List<Land> cacheValue, out float lastUpdate))
 76            {
 077                if (Time.unscaledTime - lastUpdate <= cacheMaxAgeSeconds)
 78                {
 079                    promise.Resolve(cacheValue);
 080                    return promise;
 81                }
 82            }
 83        }
 84
 485        string url = network == "mainnet" ? LAND_SUBGRAPH_URL_ORG : LAND_SUBGRAPH_URL_ZONE;
 86
 487        Query(url, TheGraphQueries.getLandQuery, new AddressVariable() { address = lowerCaseAddress })
 88            .Then(resultJson =>
 89            {
 490                ProcessReceivedLandsData(promise, resultJson, lowerCaseAddress, true);
 491            })
 092            .Catch(error => promise.Reject(error));
 93
 494        return promise;
 95    }
 96
 97    public Promise<double> QueryPolygonMana(string address)
 98    {
 299        Promise<double> promise = new Promise<double>();
 100
 2101        string lowerCaseAddress = address.ToLower();
 2102        Query(LAND_SUBGRAPH_URL_MATIC, TheGraphQueries.getPolygonManaQuery, new AddressVariable() { address = lowerCaseA
 103            .Then(resultJson =>
 104            {
 105                try
 106                {
 2107                    JObject result = JObject.Parse(resultJson);
 2108                    JToken manaObject = result["data"]?["accounts"].First?["mana"];
 2109                    if (manaObject == null || !double.TryParse(manaObject.Value<string>(), out double parsedMana))
 2110                        throw new Exception($"QueryMana response couldn't be parsed: {resultJson}");
 111
 0112                    promise.Resolve(parsedMana / 1e18);
 0113                }
 2114                catch (Exception e)
 115                {
 2116                    promise.Reject(e.ToString());
 2117                }
 2118            })
 0119            .Catch(error => promise.Reject(error));
 2120        return promise;
 121    }
 122
 123    public Promise<List<Nft>> QueryNftCollections(string address, NftCollectionsLayer layer)
 124    {
 0125        Promise<List<Nft>> promise = new Promise<List<Nft>>();
 126
 0127        string url = "";
 128        switch (layer)
 129        {
 130            case NftCollectionsLayer.ETHEREUM:
 0131                url = NFT_COLLECTIONS_SUBGRAPH_URL_ETHEREUM;
 0132                break;
 133            case NftCollectionsLayer.MATIC:
 0134                url = NFT_COLLECTIONS_SUBGRAPH_URL_MATIC;
 135                break;
 136        }
 137
 0138        Query(url, TheGraphQueries.getNftCollectionsQuery, new AddressVariable() { address = address.ToLower() })
 139            .Then(resultJson =>
 140            {
 0141                ProcessReceivedNftData(promise, resultJson);
 0142            })
 0143            .Catch(error => promise.Reject(error));
 144
 0145        return promise;
 146    }
 147
 1384148    public void Dispose() { landQueryCache.Dispose(); }
 149
 150    private void ProcessReceivedLandsData(Promise<List<Land>> landPromise, string jsonValue, string lowerCaseAddress, bo
 151    {
 4152        bool hasException = false;
 4153        List<Land> lands = null;
 154
 155        try
 156        {
 4157            LandQueryResultWrapped result = JsonUtility.FromJson<LandQueryResultWrapped>(jsonValue);
 4158            lands = LandHelper.ConvertQueryResult(result.data, lowerCaseAddress);
 159
 4160            if (cache)
 161            {
 4162                landQueryCache.Add(lowerCaseAddress, lands, DEFAULT_CACHE_TIME);
 163            }
 4164        }
 0165        catch (Exception exception)
 166        {
 0167            landPromise.Reject(exception.Message);
 0168            hasException = true;
 0169        }
 170        finally
 171        {
 4172            if (!hasException)
 173            {
 4174                landPromise.Resolve(lands);
 175            }
 4176        }
 4177    }
 178
 179    private void ProcessReceivedNftData(Promise<List<Nft>> nftPromise, string jsonValue)
 180    {
 0181        bool hasException = false;
 0182        List<Nft> nfts = new List<Nft>();
 183
 184        try
 185        {
 0186            NftQueryResultWrapped result = JsonUtility.FromJson<NftQueryResultWrapped>(jsonValue);
 187
 0188            foreach (var nft in result.data.nfts)
 189            {
 0190                nfts.Add(new Nft
 191                {
 192                    collectionId = nft.collection.id,
 193                    tokenId = nft.tokenId,
 194                    urn = nft.urn
 195                });
 196            }
 0197        }
 0198        catch (Exception exception)
 199        {
 0200            nftPromise.Reject(exception.Message);
 0201            hasException = true;
 0202        }
 203        finally
 204        {
 0205            if (!hasException)
 206            {
 0207                nftPromise.Resolve(nfts);
 208            }
 0209        }
 0210    }
 211}