Beispiel #1
0
        /// <inheritdoc />
        public async Task <IEventLock?> LockEventForProcessingAsync(EthereumNetwork network,
                                                                    ContractAddress contractAddresses,
                                                                    EventSignature eventSignature,
                                                                    TransactionHash transactionHash,
                                                                    int eventIndex,
                                                                    BlockNumber blockNumber,
                                                                    GasLimit gasUsed,
                                                                    GasPrice gasPrice,
                                                                    EventRetrievalStrategy retrievalStrategy)
        {
            var param = new
            {
                Network         = network.Name,
                ContractAddress = contractAddresses,
                EventSignature  = eventSignature,
                TransactionHash = transactionHash,
                EventIndex      = eventIndex,
                MachineName     = this._machineName,
                BlockNumber     = (int)blockNumber.Value,
                GasUsed         = gasUsed,
                GasPrice        = gasPrice,
                Strategy        = retrievalStrategy.GetName()
            };

            return(await this._database.QuerySingleOrDefaultAsync <object, EventLockEntity>(storedProcedure : @"Ethereum.Event_Lock", param : param));
        }
 /// <summary>
 ///     Constructor.
 /// </summary>
 /// <param name="gameRoundId">The game round id</param>
 /// <param name="createdByAccount">The account that created the game.</param>
 /// <param name="network">The network.</param>
 /// <param name="gameManagerContract">The game manager contract.</param>
 /// <param name="gameContract">The game network contract</param>
 /// <param name="seedCommit">The commit seed</param>
 /// <param name="seedReveal">The reveal seed</param>
 /// <param name="status">Status of game round</param>
 /// <param name="roundDuration">Round duration in seconds.</param>
 /// <param name="bettingCloseDuration">Duration of how long the betting close period is in seconds.</param>
 /// <param name="roundTimeoutDuration">Round timeout duration in seconds.</param>
 /// <param name="dateCreated">The date/time the round was created (transaction submitted)</param>
 /// <param name="dateUpdated">The date/time the round last updated</param>
 /// <param name="dateStarted">The date/time the round was activated (mined)</param>
 /// <param name="dateClosed">The date/time the round was closed.</param>
 /// <param name="blockNumberCreated">The block number the round was activated.</param>
 public GameRound(GameRoundId gameRoundId,
                  AccountAddress createdByAccount,
                  EthereumNetwork network,
                  ContractAddress gameManagerContract,
                  ContractAddress gameContract,
                  Seed seedCommit,
                  Seed seedReveal,
                  GameRoundStatus status,
                  TimeSpan roundDuration,
                  TimeSpan bettingCloseDuration,
                  TimeSpan roundTimeoutDuration,
                  DateTime dateCreated,
                  DateTime dateUpdated,
                  DateTime?dateStarted,
                  DateTime?dateClosed,
                  BlockNumber blockNumberCreated)
 {
     this.GameRoundId         = gameRoundId ?? throw new ArgumentNullException(nameof(gameRoundId));
     this.CreatedByAccount    = createdByAccount ?? throw new ArgumentNullException(nameof(createdByAccount));
     this.Network             = network ?? throw new ArgumentNullException(nameof(network));
     this.GameManagerContract = gameManagerContract ?? throw new ArgumentNullException(nameof(gameManagerContract));
     this.GameContract        = gameContract ?? throw new ArgumentNullException(nameof(gameContract));
     this.SeedCommit          = seedCommit ?? throw new ArgumentNullException(nameof(seedCommit));
     this.SeedReveal          = seedReveal ?? throw new ArgumentNullException(nameof(seedReveal));
     this.Status               = status;
     this.RoundDuration        = roundDuration;
     this.BettingCloseDuration = bettingCloseDuration;
     this.RoundTimeoutDuration = roundTimeoutDuration;
     this.DateCreated          = dateCreated;
     this.DateUpdated          = dateUpdated;
     this.DateStarted          = dateStarted;
     this.DateClosed           = dateClosed;
     this.BlockNumberCreated   = blockNumberCreated;
 }
    /// <summary>
    /// Initializes the network manager by setting up the different networks.
    /// </summary>
    /// <param name="settings"> The <see cref="Settings"/> to apply to this <see cref="EthereumNetworkManager"/>. </param>
    public EthereumNetworkManager(Settings settings)
    {
        this.settings = settings;

        mainnet = new EthereumNetwork("https://mainnet.infura.io");
        rinkeby = new EthereumNetwork("https://rinkeby.infura.io");
    }
 /// <inheritdoc />
 public Task SaveStartRoundAsync(GameRoundId gameRoundId,
                                 EthereumNetwork network,
                                 AccountAddress createdByAccount,
                                 ContractAddress gameManagerContract,
                                 ContractAddress gameContract,
                                 Seed seedCommit,
                                 Seed seedReveal,
                                 TimeSpan roundDuration,
                                 TimeSpan bettingCloseDuration,
                                 TimeSpan roundTimeoutDuration,
                                 BlockNumber blockNumberCreated,
                                 TransactionHash transactionHash)
 {
     return(this._database.ExecuteAsync(storedProcedure: @"Games.GameRound_Insert",
                                        new
     {
         GameRoundId = gameRoundId,
         GameManagerContract = gameManagerContract,
         GameContract = gameContract,
         CreatedByAccount = createdByAccount,
         Network = network.Name,
         BlockNumberCreated = blockNumberCreated,
         SeedCommit = seedCommit,
         SeedReveal = seedReveal,
         BettingCloseDuration = bettingCloseDuration.TotalSeconds,
         RoundDuration = roundDuration.TotalSeconds,
         RoundTimeoutDuration = roundTimeoutDuration.TotalSeconds,
         TransactionHash = transactionHash
     }));
 }
Beispiel #5
0
        /// <inheritdoc />
        public async Task StartGamesForNetworkAsync(EthereumNetwork network, CancellationToken cancellationToken)
        {
            if (!this._contractInfo.Addresses.ContainsKey(network))
            {
                // Contract not supported on the network
                return;
            }

            INetworkBlockHeader?blockHeader = this._ethereumBlockStatus.GetLatestBlockRetrievedOnNetwork(network);

            if (blockHeader == null)
            {
                // not yet retrieved the latest block so can't do any transactions.
                this._logger.LogWarning($"{network.Name}: No current block - not starting game");

                return;
            }

            int playersOnline = await this._playerCountManager.GetCountAsync(network);

            if (playersOnline == 0)
            {
                this._logger.LogInformation($"{network.Name}: No players online - not starting any games");

                return;
            }

            IReadOnlyList <ContractAddress> gameContracts = this._gamesList.GetGamesForNetwork(network);

            foreach (ContractAddress gameContract in gameContracts)
            {
                await this.StartGameAsync(network : network, gameContract : gameContract, blockHeader : blockHeader, cancellationToken : cancellationToken);
            }
        }
Beispiel #6
0
        public Task GameRoundBrokenAsync(EthereumNetwork network, GameRoundId gameRoundId)
        {
            this._logger.LogInformation($"{network.Name}: Game {gameRoundId} broken.");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.GameRoundBroken(roundId: gameRoundId, (int)GameRoundParameters.InterGameDelay.TotalSeconds))));
        }
Beispiel #7
0
        /// <inheritdoc />
        public Task NoGamesAvailableAsync(EthereumNetwork network)
        {
            this._logger.LogInformation($"{network.Name}: No games available");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.NoGamesAvailable())));
        }
Beispiel #8
0
        /// <inheritdoc />
        public Task GameRoundEndingAsync(EthereumNetwork network, GameRoundId gameRoundId, TransactionHash transactionHash, Seed seedReveal)
        {
            this._logger.LogInformation($"{network.Name}: Game {gameRoundId} ending. Txn hash {transactionHash}");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.GameRoundEnding(roundId: gameRoundId, transactionHash: transactionHash, seedReveal: seedReveal))));
        }
        /// <inheritdoc />
        public Task AmountOfPlayersAsync(EthereumNetwork network, int players)
        {
            this._logger.LogInformation($"{network.Name}: Players Online: {players}");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: true, includeGlobalGroups: false);

            return(Task.WhenAll(hubs.Select(hub => hub.PlayersOnline(players))));
        }
Beispiel #10
0
        /// <inheritdoc />
        public Task BettingEndedAsync(EthereumNetwork network, GameRoundId gameRoundId, BlockNumber blockNumber, BlockNumber startBlockNumber)
        {
            this._logger.LogInformation($"{network.Name}: Game {gameRoundId} betting ended. Block number {blockNumber}");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.BettingEnded(roundId: gameRoundId, blockNumber: blockNumber))));
        }
        protected Task SubscribeAccountAsync(string connectionId, EthereumNetwork network, UserAccountId userAccountId)
        {
            if (userAccountId == null)
            {
                return(Task.CompletedTask);
            }

            return(Task.WhenAll(this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateGlobal(network: network, accountAddress: userAccountId)),
                                this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateLocal(network: network, accountAddress: userAccountId))));
        }
Beispiel #12
0
        /// <inheritdoc />
        public Task GameRoundEndedAsync(EthereumNetwork network, GameRoundId gameRoundId, BlockNumber blockNumber, BlockNumber startBlockNumber)
        {
            this._logger.LogInformation($"{network.Name}: Game {gameRoundId} ended. Block number {blockNumber}");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.GameRoundEnded(roundId: gameRoundId,
                                                                      blockNumber: blockNumber,
                                                                      (int)GameRoundParameters.InterGameDelay.TotalSeconds,
                                                                      startBlockNumber: startBlockNumber))));
        }
Beispiel #13
0
        /// <inheritdoc />
        public Task GameRoundStartedAsync(EthereumNetwork network, GameRoundId gameRoundId, int timeLeftInSeconds, BlockNumber blockNumber)
        {
            this._logger.LogInformation($"{network.Name}: Game {gameRoundId} started using . Block number: {blockNumber}. Remaining time: {timeLeftInSeconds}");

            IEnumerable <IHub> hubs = this.GetAllHubs(network: network, includeLocalGroups: false, includeGlobalGroups: true);

            return(Task.WhenAll(hubs.Select(hub => hub.GameRoundStarted(roundId: gameRoundId,
                                                                        timeLeftInSeconds: timeLeftInSeconds,
                                                                        blockNumber: blockNumber,
                                                                        (int)GameRoundParameters.InterGameDelay.TotalSeconds))));
        }
        private IEnumerable <IHub> GetAllHubs(EthereumNetwork network, bool includeLocalGroups, bool includeGlobalGroups)
        {
            if (includeLocalGroups)
            {
                yield return(this._publicHubContext.Clients.Group(this._groupNameGenerator.GenerateLocal(network)));

                yield return(this._authenticatedHubContext.Clients.Group(this._groupNameGenerator.GenerateLocal(network)));
            }

            if (includeGlobalGroups)
            {
                yield return(this._publicHubContext.Clients.Group(this._groupNameGenerator.GenerateGlobal(network)));

                yield return(this._authenticatedHubContext.Clients.Group(this._groupNameGenerator.GenerateGlobal(network)));
            }
        }
Beispiel #15
0
        public void RestoreEndpoints(bool restoreName)
        {
            //this.phantasmaRPCURL = this.GetDefaultValue(PhantasmaRPCTag);
            this.phantasmaRPCURL      = this.GetDefaultValue(PhantasmaRPCTag);
            this.phantasmaExplorer    = this.GetDefaultValue(PhantasmaExplorerTag);
            this.phantasmaNftExplorer = this.GetDefaultValue(PhantasmaNftExplorerTag);
            this.neoRPCURL            = this.GetDefaultValue(NeoRPCTag);
            this.neoscanURL           = this.GetDefaultValue(NeoscanAPITag);
            this.ethereumRPCURL       = this.GetDefaultValue(EthereumRPCTag);

            if (restoreName)
            {
                this.nexusName = this.GetDefaultValue(NexusNameTag);

                // Reset ethereum network on nexus change (except custom nexus).
                switch (this.nexusKind)
                {
                case NexusKind.Main_Net:
                    this.ethereumNetwork = EthereumNetwork.Main_Net;
                    break;

                case NexusKind.Test_Net:
                    this.ethereumNetwork = EthereumNetwork.Ropsten;
                    break;

                case NexusKind.Mankini_Test_Net:
                    this.ethereumNetwork = EthereumNetwork.Ropsten;
                    break;

                case NexusKind.Local_Net:
                    this.ethereumNetwork = EthereumNetwork.Ropsten;
                    break;
                }
            }

            Log.Write("Settings: Restore endpoints: restoreName mode: " + restoreName + "\n" +
                      "                             Phantasma RPC: " + this.phantasmaRPCURL + "\n" +
                      "                             Phantasma Explorer: " + this.phantasmaExplorer + "\n" +
                      "                             Phantasma NFT Explorer: " + this.phantasmaNftExplorer + "\n" +
                      "                             Neo RPC: " + this.neoRPCURL + "\n" +
                      "                             Neoscan: " + this.neoscanURL + "\n" +
                      "                             Ethereum RPC: " + this.ethereumRPCURL + "\n" +
                      "                             Nexus name: " + this.nexusName,
                      Log.Level.Debug1);
        }
        private async Task PublishGameStateAsync(EthereumNetwork network, INetworkBlockHeader?networkBlockHeader)
        {
            IReadOnlyList <GameRound> games = await this._gameRoundDataManager.GetAllRunningAsync(network);

            bool anyPublished = false;

            if (networkBlockHeader != null)
            {
                foreach (GameRound game in games)
                {
                    IReadOnlyList <string> gameHistory = await this.GetGameHistoryAsync(game : game);

                    int timeLeft = this._gameRoundTimeCalculator.CalculateTimeLeft(game);

                    await this.Clients.Caller.GameRoundStarted(roundId : game.GameRoundId,
                                                               timeLeftInSeconds : timeLeft,
                                                               blockNumber : game.BlockNumberCreated,
                                                               (int)GameRoundParameters.InterGameDelay.TotalSeconds);

                    await this.Clients.Caller.History(gameHistory);

                    anyPublished = true;
                }
            }

            if (!anyPublished)
            {
                GameRound?gameRound = await this._gameRoundDataManager.GetLastCompletedForNetworkAsync(network);

                if (gameRound != null && networkBlockHeader != null)
                {
                    IReadOnlyList <string> gameHistory = await this.GetGameHistoryAsync(game : gameRound);

                    int timeUntilNextRound = this._gameRoundTimeCalculator.CalculateSecondsUntilNextRound(gameRound);

                    await this.Clients.Caller.LastGameRoundEnded(gameRoundId : gameRound.GameRoundId, startBlockNumber : gameRound.BlockNumberCreated, timeToNextRound : timeUntilNextRound);

                    await this.Clients.Caller.History(gameHistory);
                }
                else
                {
                    await this.Clients.Caller.NoGamesAvailable();
                }
            }
        }
Beispiel #17
0
        public async Task SubscribeAsync(string networkName)
        {
            EthereumNetwork network = this.VerifyNetwork(networkName);

            UserAccountId userAccountId = this.JwtUser()
                                          .Id;

            string connectionId = this.Context.ConnectionId;

            this.Logger.LogInformation($"Client {connectionId} subscribing to network {network.Name}");

            // temporary for dummy data
            await this.SubscribeNetworkAsync(connectionId : this.Context.ConnectionId, network : network);

            this.Logger.LogInformation($"Client {connectionId} subscribed to network {network.Name} and user account id {userAccountId}");

            int playerCount = await this._playerCountManager.AddPlayerAsync(playerId : this.Context.ConnectionId, newNetwork : network);

            await this.Clients.Caller.PlayersOnline(playerCount);
        }
        public async Task SubscribeAsync(string networkName)
        {
            EthereumNetwork network = this.VerifyNetwork(networkName);

            JwtUser       user          = this.JwtUser();
            UserAccountId userAccountId = user.Id;

            string connectionId = this.Context.ConnectionId;

            this.Logger.LogInformation($"Client {connectionId} subscribing to network {network.Name}");

            await this.SubscribeNetworkAsync(connectionId : this.Context.ConnectionId, network : network);

            this.Logger.LogInformation($"Client {connectionId} subscribed to network {network.Name} and user account id {userAccountId}");

            int playerCount = await this._playerCountManager.AddPlayerAsync(playerId : this.Context.ConnectionId, newNetwork : network);

            await this.Clients.Caller.PlayersOnline(playerCount);

            INetworkBlockHeader?networkBlockHeader = this._ethereumBlockStatus.GetLatestBlockRetrievedOnNetwork(network);

            await this.PublishGameStateAsync(network : network, networkBlockHeader : networkBlockHeader);
        }
        /// <summary>
        ///     Add player into count.
        /// </summary>
        /// <param name="playerId"></param>
        /// <param name="newNetwork"></param>
        /// <returns></returns>
        public async Task <int> AddPlayerAsync(string playerId, EthereumNetwork newNetwork)
        {
            // is it already registered player we need to check if he changed network or not
            // in case he did we need to decrement count for old network and increment for new.
            if (this._players.TryGetValue(key: playerId, out EthereumNetwork? network))
            {
                if (newNetwork != network)
                {
                    this._logger.LogInformation($"It is existing player, old network: {network} and new network: {newNetwork}");
                    await this._playerCountDataManager.DecrementAsync(machineName : Environment.MachineName, network !);

                    return(await this._playerCountDataManager.IncrementAsync(machineName : Environment.MachineName, network : newNetwork));
                }

                this._logger.LogInformation($"It is existing player, no network change, network: {newNetwork}");

                return(await this._playerCountDataManager.GetAsync(network));
            }

            this._logger.LogInformation($"New player, increment count for network: {newNetwork}");
            this._players.TryAdd(key: playerId, value: newNetwork);

            return(await this._playerCountDataManager.IncrementAsync(machineName: Environment.MachineName, network : newNetwork));
        }
Beispiel #20
0
 private static string BuildKey(string context, EthereumNetwork network, params string[] data)
 {
     return(string.Join(separator: @"::", new[] { context, network.Name }.Concat(data))
            .ToLowerInvariant());
 }
Beispiel #21
0
        private DateTime GetCurrentTime(EthereumNetwork network)
        {
            BlockStatus blockStatus = this.GetBlockStatus(network);

            return(blockStatus.UtcNow());
        }
Beispiel #22
0
 private BlockStatus GetBlockStatus(EthereumNetwork network)
 {
     return(this._blockStatus.GetOrAdd(key: network, new BlockStatus(this._dateTimeSource)));
 }
 protected Task SubscribeNetworkAsync(string connectionId, EthereumNetwork network)
 {
     return(Task.WhenAll(this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateLocal(network)),
                         this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateGlobal(network))));
 }
Beispiel #24
0
        public void Load()
        {
            Log.Write("Settings: Loading...");

            var nexusKind = PlayerPrefs.GetString(NexusKindTag, NexusKind.Main_Net.ToString());

            if (!Enum.TryParse <NexusKind>(nexusKind, true, out this.nexusKind))
            {
                this.nexusKind = NexusKind.Unknown;
            }

            //this.phantasmaRPCURL = PlayerPrefs.GetString(PhantasmaRPCTag, GetDefaultValue(PhantasmaRPCTag));
            this.phantasmaBPURL = PlayerPrefs.GetString(PhantasmaBPTag, GetDefaultValue(PhantasmaBPTag));
            this.neoRPCURL      = PlayerPrefs.GetString(NeoRPCTag, GetDefaultValue(NeoRPCTag));
            this.neoscanURL     = PlayerPrefs.GetString(NeoscanAPITag, GetDefaultValue(NeoscanAPITag));
            this.nexusName      = PlayerPrefs.GetString(NexusNameTag, GetDefaultValue(NexusNameTag));

            this.currency = PlayerPrefs.GetString(CurrencyTag, "USD");
            this.sfx      = PlayerPrefs.GetInt(SFXTag, 0) != 0;

            this.phantasmaRPCURL = this.phantasmaBPURL;

            var defaultGasPrice = 100000;

            if (!BigInteger.TryParse(PlayerPrefs.GetString(GasPriceTag, defaultGasPrice.ToString()), out feePrice))
            {
                this.feePrice = 100000;
            }

            // Doing it in a bit more complex way to avoid decimal parsing problem for different cultures.
            var neoGasFeeString = PlayerPrefs.GetString(NeoGasFeeTag, null);

            if (!String.IsNullOrEmpty(neoGasFeeString))
            {
                if (!Decimal.TryParse(neoGasFeeString, out neoGasFee))
                {
                    this.neoGasFee = 0.001m;
                }
            }
            else
            {
                this.neoGasFee = 0.001m;
            }

            // Ethereum
            var ethereumNetwork = PlayerPrefs.GetString(EthereumNetworkTag, EthereumNetwork.Main_Net.ToString());

            if (!Enum.TryParse <EthereumNetwork>(ethereumNetwork, true, out this.ethereumNetwork))
            {
                this.ethereumNetwork = EthereumNetwork.Unknown;
            }

            this.ethereumLocalnetSoulContract = PlayerPrefs.GetString(EthereumLocalnetSoulContractTag, GetDefaultValue(EthereumLocalnetSoulContractTag));
            this.ethereumLocalnetKcalContract = PlayerPrefs.GetString(EthereumLocalnetKcalContractTag, GetDefaultValue(EthereumLocalnetKcalContractTag));

            this.ethereumRPCURL = PlayerPrefs.GetString(EthereumRPCTag, GetDefaultValue(EthereumRPCTag));
            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumGasPriceGweiTag, "100"), out ethereumGasPriceGwei))
            {
                this.ethereumGasPriceGwei = 100;
            }
            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumTransferGasLimitTag, "21000"), out ethereumTransferGasLimit))
            {
                this.ethereumTransferGasLimit = 21000;
            }
            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumTokenTransferGasLimitTag, "100000"), out ethereumTokenTransferGasLimit))
            {
                this.ethereumTokenTransferGasLimit = 100000;
            }

            this.uiThemeName = PlayerPrefs.GetString(UiThemeNameTag, UiThemes.Phantasia.ToString());

            LoadLogSettings();

            this.ttrsNftSortMode  = PlayerPrefs.GetInt(TtrsNftSortModeTag, 0);
            this.nftSortDirection = PlayerPrefs.GetInt(NftSortDirectionTag, 0);

            Log.Write("Settings: Load: Nexus kind: " + this.nexusKind.ToString() + "\n" +
                      "                Phantasma BP: " + this.phantasmaBPURL + "\n" +
                      "                Phantasma RPC: " + this.phantasmaRPCURL + "\n" +
                      "                Fee price: " + this.feePrice + "\n" +
                      "                Neo RPC: " + this.neoRPCURL + "\n" +
                      "                Neoscan: " + this.neoscanURL + "\n" +
                      "                Neo GAS fee: " + this.neoGasFee + "\n" +
                      "                Ethereum network: " + this.ethereumNetwork + "\n" +
                      "                Ethereum localnet SOUL contract: " + this.ethereumLocalnetSoulContract + "\n" +
                      "                Ethereum localnet KCAL contract: " + this.ethereumLocalnetKcalContract + "\n" +
                      "                Ethereum RPC: " + this.ethereumRPCURL + "\n" +
                      "                Ethereum gas price (Gwei): " + this.ethereumGasPriceGwei + "\n" +
                      "                Ethereum transfer gas limit: " + this.ethereumTransferGasLimit + "\n" +
                      "                Ethereum token transfer gas limit: " + this.ethereumTokenTransferGasLimit + "\n" +
                      "                Nexus name: " + this.nexusName + "\n" +
                      "                Currency: " + this.currency + "\n" +
                      "                Sfx: " + this.sfx + "\n" +
                      "                UI theme: " + this.uiThemeName + "\n" +
                      "                Log level: " + this.logLevel + "\n" +
                      "                Log overwrite: " + this.logOverwriteMode + "\n" +
                      "                TTRS NFT sort mode: " + this.ttrsNftSortMode + "\n" +
                      "                NFT sort direction: " + this.nftSortDirection
                      );
        }
 /// <inheritdoc />
 public Task <int> GetCountAsync(EthereumNetwork network)
 {
     return(this._playerCountDataManager.GetAsync(network: network));
 }
Beispiel #26
0
        public void Load()
        {
            Log.Write("Settings: Loading...");

            var nexusKind = PlayerPrefs.GetString(NexusKindTag, NexusKind.Main_Net.ToString());

            if (!Enum.TryParse <NexusKind>(nexusKind, true, out this.nexusKind))
            {
                this.nexusKind = NexusKind.Unknown;
            }

            if (this.nexusKind == NexusKind.Main_Net || this.nexusKind == NexusKind.Test_Net || this.nexusKind == NexusKind.Mankini_Test_Net)
            {
                // For mainnet/testnet we always load defaults for hidden settings,
                // to avoid dealing with "stuck" values from old PG version that had different defaults.
                this.phantasmaRPCURL      = GetDefaultValue(PhantasmaRPCTag);
                this.phantasmaExplorer    = GetDefaultValue(PhantasmaExplorerTag);
                this.phantasmaNftExplorer = GetDefaultValue(PhantasmaNftExplorerTag);
                this.neoRPCURL            = GetDefaultValue(NeoRPCTag);
                this.neoscanURL           = GetDefaultValue(NeoscanAPITag);
                this.nexusName            = GetDefaultValue(NexusNameTag);
            }
            else
            {
                this.phantasmaRPCURL      = PlayerPrefs.GetString(PhantasmaRPCTag, GetDefaultValue(PhantasmaRPCTag));
                this.phantasmaExplorer    = PlayerPrefs.GetString(PhantasmaExplorerTag, GetDefaultValue(PhantasmaExplorerTag));
                this.phantasmaNftExplorer = PlayerPrefs.GetString(PhantasmaNftExplorerTag, GetDefaultValue(PhantasmaNftExplorerTag));
                this.neoRPCURL            = PlayerPrefs.GetString(NeoRPCTag, GetDefaultValue(NeoRPCTag));
                this.neoscanURL           = PlayerPrefs.GetString(NeoscanAPITag, GetDefaultValue(NeoscanAPITag));
                this.nexusName            = PlayerPrefs.GetString(NexusNameTag, GetDefaultValue(NexusNameTag));
            }

            this.currency = PlayerPrefs.GetString(CurrencyTag, "USD");
            this.sfx      = PlayerPrefs.GetInt(SFXTag, 0) != 0;

            var defaultGasPrice = 100000;

            if (!BigInteger.TryParse(PlayerPrefs.GetString(GasPriceTag, defaultGasPrice.ToString()), out feePrice))
            {
                this.feePrice = defaultGasPrice;
            }

            var defaultGasLimit = 1600;

            if (!BigInteger.TryParse(PlayerPrefs.GetString(GasLimitTag, defaultGasLimit.ToString()), out feeLimit))
            {
                this.feeLimit = defaultGasLimit;
            }

            // Doing it in a bit more complex way to avoid decimal parsing problem for different cultures.
            var neoGasFeeString = PlayerPrefs.GetString(NeoGasFeeTag, null);

            if (!String.IsNullOrEmpty(neoGasFeeString))
            {
                if (!Decimal.TryParse(neoGasFeeString, out neoGasFee))
                {
                    this.neoGasFee = 0.001m;
                }
            }
            else
            {
                this.neoGasFee = 0.001m;
            }

            // Ethereum
            var ethereumNetwork = PlayerPrefs.GetString(EthereumNetworkTag, EthereumNetwork.Main_Net.ToString());

            if (!Enum.TryParse <EthereumNetwork>(ethereumNetwork, true, out this.ethereumNetwork))
            {
                this.ethereumNetwork = EthereumNetwork.Unknown;
            }

            this.ethereumLocalnetSoulContract = PlayerPrefs.GetString(EthereumLocalnetSoulContractTag, GetDefaultValue(EthereumLocalnetSoulContractTag));
            this.ethereumLocalnetKcalContract = PlayerPrefs.GetString(EthereumLocalnetKcalContractTag, GetDefaultValue(EthereumLocalnetKcalContractTag));
            this.ethereumLocalnetDankContract = PlayerPrefs.GetString(EthereumLocalnetDankContractTag, GetDefaultValue(EthereumLocalnetDankContractTag));
            this.ethereumLocalnetDytContract  = PlayerPrefs.GetString(EthereumLocalnetDytContractTag, GetDefaultValue(EthereumLocalnetDytContractTag));

            if (this.ethereumNetwork == EthereumNetwork.Main_Net || this.ethereumNetwork == EthereumNetwork.Ropsten)
            {
                // For mainnet/testnet we always load defaults for hidden settings,
                // to avoid dealing with "stuck" values from old PG version that had different defaults.
                this.ethereumRPCURL = GetDefaultValue(EthereumRPCTag);
            }
            else
            {
                this.ethereumRPCURL = PlayerPrefs.GetString(EthereumRPCTag, GetDefaultValue(EthereumRPCTag));
            }

            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumGasPriceGweiTag, "100"), out ethereumGasPriceGwei))
            {
                this.ethereumGasPriceGwei = 100;
            }
            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumTransferGasLimitTag, "21000"), out ethereumTransferGasLimit))
            {
                this.ethereumTransferGasLimit = 21000;
            }
            if (!BigInteger.TryParse(PlayerPrefs.GetString(EthereumTokenTransferGasLimitTag, "100000"), out ethereumTokenTransferGasLimit))
            {
                this.ethereumTokenTransferGasLimit = 100000;
            }

            this.uiThemeName = PlayerPrefs.GetString(UiThemeNameTag, UiThemes.Phantasia.ToString());

            LoadLogSettings();

            this.ttrsNftSortMode  = PlayerPrefs.GetInt(TtrsNftSortModeTag, 0);
            this.nftSortMode      = PlayerPrefs.GetInt(NftSortModeTag, 0);
            this.nftSortDirection = PlayerPrefs.GetInt(NftSortDirectionTag, 0);

            var documentFolderPath = GetDocumentPath();

            this.lastVisitedFolder = PlayerPrefs.GetString(LastVisitedFolderTag, documentFolderPath);
            if (!System.IO.Directory.Exists(this.lastVisitedFolder))
            {
                this.lastVisitedFolder = documentFolderPath;
            }

            Log.Write("Settings: Load: " + ToString());
        }
Beispiel #27
0
        /// <inheritdoc />
        public Task StartGameAsync(EthereumNetwork network, ContractAddress gameContract, INetworkBlockHeader blockHeader, CancellationToken cancellationToken)
        {
            INetworkSigningAccount account = this._ethereumAccountManager.GetAccount(network);

            return(this.TryToStartGameAsync(networkSigningAccount: account, gameContract: gameContract, blockHeader: blockHeader, cancellationToken: cancellationToken));
        }
Beispiel #28
0
        private async Task <IActionResult> RequestFromFaucetAsync(OpenFaucetDto request, CancellationToken cancellationToken)
        {
            try
            {
                JwtUser?jwtUser = this.JwtUser;

                if (jwtUser == null)
                {
                    return(ResultHelpers.ExceptionResult(message: "Not authorised (1).", nameof(FaucetController), statusCode: HttpStatusCode.Unauthorized));
                }

                IPAddress ipAddress = this._remoteIpAddressRetriever.Get(this.HttpContext);

                EthereumNetwork network = request.Network;

                if (!this._faucetContractInfo.IsSupported(network))
                {
                    return(ResultHelpers.ExceptionResult(message: "Faucet is not supported on network.", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
                }

                INetworkBlockHeader?networkBlockHeader = this._ethereumBlockStatus.GetLatestBlockRetrievedOnNetwork(network);

                if (networkBlockHeader == null)
                {
                    return(ResultHelpers.ExceptionResult($"Network {network.Name} is not ready [BNF].", nameof(FaucetController), statusCode: HttpStatusCode.ServiceUnavailable));
                }

                if (this._networkManager.Supported.All(x => x.Name != network.Name))
                {
                    return(ResultHelpers.ExceptionResult(message: "Faucet is not supported on network.", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
                }

                AccountAddress address = new(request.Address.ToSpan());

                if (jwtUser.AccountAddress != address)
                {
                    return(ResultHelpers.ExceptionResult(message: "Not authorised (2).", nameof(FaucetController), statusCode: HttpStatusCode.Unauthorized));
                }

                INetworkAccount account = new NetworkAccount(network: network, address: address);

                if (this._ethereumAccountManager.IsAccountConfiguredForUse(account))
                {
                    return(ResultHelpers.ExceptionResult(message: "Server cannot give itself token or eth.", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
                }

                FaucetDrip drip = await this._faucetManager.OpenAsync(ipAddress : ipAddress, recipient : account, networkBlockHeader : networkBlockHeader, cancellationToken : cancellationToken);

                return(ResultHelpers.JsonResult(drip.ToDto(), statusCode: HttpStatusCode.OK));
            }
            catch (TooMuchTokenException)
            {
                return(ResultHelpers.ExceptionResult(message: "Too much token!", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
            }
            catch (TooFrequentTokenException)
            {
                return(ResultHelpers.ExceptionResult(message: "Too much token!", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
            }
            catch (InsufficientTokenException)
            {
                return(ResultHelpers.ExceptionResult(message: "Insufficient token!", nameof(FaucetController), statusCode: HttpStatusCode.Forbidden));
            }
        }
Beispiel #29
0
        /// <inheritdoc />
        public Task <IReadOnlyList <AwaitingConfirmationsTransaction> > GetHighRiskTransactionsReadyForProcessingAsync(EthereumNetwork network, BlockNumber currentBlock)
        {
            var parameters = new { Network = network.Name, BlockNumber = (int)currentBlock.Value };

            return(this._database.QueryAsync(builder: this._eventRiskyTransactionsBuilder, storedProcedure: @"Ethereum.EventRiskyTransaction_GetReadyForProcessing", param: parameters));
        }
Beispiel #30
0
        public Task SubscribeAsync(string networkName)
        {
            EthereumNetwork network = this.VerifyNetwork(networkName);

            return(this.SubscribeNetworkAsync(connectionId: this.Context.ConnectionId, network: network));
        }