Beispiel #1
0
        public RewardGoldTest()
        {
            _tableSheets = new TableSheets();
            _tableSheets.SetToSheet(nameof(WorldSheet), "test");
            _tableSheets.SetToSheet(nameof(QuestSheet), "test");
            _tableSheets.SetToSheet(nameof(QuestRewardSheet), "test");
            _tableSheets.SetToSheet(nameof(QuestItemRewardSheet), "test");
            _tableSheets.SetToSheet(nameof(EquipmentItemRecipeSheet), "test");
            _tableSheets.SetToSheet(nameof(EquipmentItemSubRecipeSheet), "test");
            _tableSheets.SetToSheet(
                nameof(CharacterSheet),
                "id,_name,size_type,elemental_type,hp,atk,def,cri,hit,spd,lv_hp,lv_atk,lv_def,lv_cri,lv_hit,lv_spd,attack_range,run_speed\n100010,전사,S,0,300,20,10,10,90,70,12,0.8,0.4,0,3.6,2.8,2,3");

            var privateKey   = new PrivateKey();
            var agentAddress = privateKey.PublicKey.ToAddress();

            var avatarAddress = agentAddress.Derive("avatar");

            _avatarState = new AvatarState(avatarAddress, agentAddress, 0, _tableSheets, new GameConfigState());

            var gold = new GoldCurrencyState(new Currency("NCG", minter: null));

            _baseState = (State) new State()
                         .SetState(GoldCurrencyState.Address, gold.Serialize())
                         .SetState(Addresses.GoldDistribution, GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize())
                         .MintAsset(GoldCurrencyState.Address, gold.Currency, 100000000000);
        }
Beispiel #2
0
        public void TransferAsset(
            [Argument("SENDER", Description = "An address of sender.")] string sender,
            [Argument("RECIPIENT", Description = "An address of recipient.")] string recipient,
            [Argument("AMOUNT", Description = "An amount of gold to transfer.")] int goldAmount,
            [Argument("GENESIS-BLOCK", Description = "A genesis block containing InitializeStates.")] string genesisBlock
            )
        {
            byte[] genesisBytes = File.ReadAllBytes(genesisBlock);
            var    genesisDict  = (Bencodex.Types.Dictionary)_codec.Decode(genesisBytes);
            IReadOnlyList <Transaction <NCAction> > genesisTxs =
                BlockMarshaler.UnmarshalBlockTransactions <NCAction>(genesisDict);
            var      initStates = (InitializeStates)genesisTxs.Single().Actions.Single().InnerAction;
            Currency currency   = new GoldCurrencyState(initStates.GoldCurrency).Currency;

            var action = new TransferAsset(
                new Address(sender),
                new Address(recipient),
                currency * goldAmount
                );

            var bencoded = new List(
                (Text)nameof(TransferAsset),
                action.PlainValue
                );

            byte[] raw = _codec.Encode(bencoded);
            Console.Write(ByteUtil.Hex(raw));
        }
Beispiel #3
0
        public RewardGoldTest()
        {
            var sheets = TableSheetsImporter.ImportSheets();

            sheets[nameof(CharacterSheet)] = string.Join(
                Environment.NewLine,
                "id,_name,size_type,elemental_type,hp,atk,def,cri,hit,spd,lv_hp,lv_atk,lv_def,lv_cri,lv_hit,lv_spd,attack_range,run_speed",
                "100010,전사,S,0,300,20,10,10,90,70,12,0.8,0.4,0,3.6,2.8,2,3");

            var privateKey   = new PrivateKey();
            var agentAddress = privateKey.PublicKey.ToAddress();

            var avatarAddress = agentAddress.Derive("avatar");

            _tableSheets = new TableSheets(sheets);

            _avatarState = new AvatarState(
                avatarAddress,
                agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                default
                );

            var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            _baseState = (State) new State()
                         .SetState(GoldCurrencyState.Address, gold.Serialize())
                         .SetState(Addresses.GoldDistribution, GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize())
                         .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000);
        }
        public ClaimMonsterCollectionReward0Test()
        {
            _signer        = default;
            _avatarAddress = _signer.Derive("avatar");
            _state         = new State();
            Dictionary <string, string> sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);
            var rankingMapAddress = new PrivateKey().ToAddress();
            var agentState        = new AgentState(_signer);
            var avatarState       = new AvatarState(
                _avatarAddress,
                _signer,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress);

            agentState.avatarAddresses[0] = _avatarAddress;

            var currency          = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(currency);

            _state = _state
                     .SetState(_signer, agentState.Serialize())
                     .SetState(_avatarAddress, avatarState.Serialize())
                     .SetState(Addresses.GoldCurrency, goldCurrencyState.Serialize());

            foreach ((string key, string value) in sheets)
            {
                _state = _state
                         .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Beispiel #5
0
        public void TransferAsset(
            [Argument("SENDER", Description = "An address of sender.")] string sender,
            [Argument("RECIPIENT", Description = "An address of recipient.")] string recipient,
            [Argument("AMOUNT", Description = "An amount of gold to transfer.")] int goldAmount,
            [Argument("GENESIS-BLOCK", Description = "A genesis block containing InitializeStates.")] string genesisBlock
            )
        {
            Block <NCAction> genesis = Block <NCAction> .Deserialize(File.ReadAllBytes(genesisBlock));

            var      initStates = (InitializeStates)genesis.Transactions.Single().Actions.Single().InnerAction;
            Currency currency   = new GoldCurrencyState(initStates.GoldCurrency).Currency;

            var action = new TransferAsset(
                new Address(sender),
                new Address(recipient),
                currency * goldAmount
                );

            var bencoded = new List(
                new IValue[]
            {
                (Text)nameof(TransferAsset),
                action.PlainValue
            }
                );

            byte[] raw = _codec.Encode(bencoded);
            Console.Write(ByteUtil.Hex(raw));
        }
        public async Task <ActionResult> Get(string currency, string address)
        {
            try
            {
                var codec = new Codec();
                var goldCurrencyStateBytes =
                    await this.BlockChainService.GetState(GoldCurrencyState.Address.ToByteArray());

                var goldCurrency = new GoldCurrencyState(
                    (Dictionary)codec.Decode(goldCurrencyStateBytes)).Currency;
                var bytes = await this.BlockChainService.GetBalance(
                    this.ParseHex(address),
                    codec.Encode(goldCurrency.Serialize()));

                var state = codec.Decode(bytes);
                return(this.Content(
                           JsonSerializer.Serialize(state, new JsonSerializerOptions
                {
                    Converters =
                    {
                        new BencodexValueConverter(),
                    },
                }), "application/json"));
            }
            catch (Exception)
            {
                return(new StatusCodeResult(500));
            }
        }
        public async Task TransferNCGHistories()
        {
            PrivateKey minerPrivateKey = new PrivateKey();
            Address    sender = minerPrivateKey.ToAddress(), recipient = new PrivateKey().ToAddress();

            await BlockChain.MineBlock(sender);

            await BlockChain.MineBlock(recipient);

            var currency = new GoldCurrencyState((Dictionary)BlockChain.GetState(Addresses.GoldCurrency)).Currency;
            var transferAsset = new TransferAsset(sender, recipient, new FungibleAssetValue(currency, 10, 0));
            var tx       = BlockChain.MakeTransaction(minerPrivateKey, new PolymorphicAction <ActionBase>[] { transferAsset });
            var block    = await BlockChain.MineBlock(minerPrivateKey.ToAddress(), append : false);

            BlockChain.Append(block);
            Assert.NotNull(StandaloneContextFx.Store?.GetTxExecution(block.Hash, tx.Id));

            var blockHashHex = ByteUtil.Hex(block.Hash.ToByteArray());
            var result       =
                await ExecuteQueryAsync(
                    $"{{ transferNCGHistories(blockHash: \"{blockHashHex}\") {{ blockHash txId sender recipient amount }} }}");

            Assert.Null(result.Errors);
            Assert.Equal(new List <object>
            {
                new Dictionary <string, object>
                {
                    ["blockHash"] = block.Hash.ToString(),
                    ["txId"]      = tx.Id.ToString(),
                    ["sender"]    = transferAsset.Sender.ToString(),
                    ["recipient"] = transferAsset.Recipient.ToString(),
                    ["amount"]    = transferAsset.Amount.GetQuantityString(),
                }
            }, result.Data.As <Dictionary <string, object> >()["transferNCGHistories"]);
        }
Beispiel #8
0
        public void Execute(bool backward)
        {
            var       privateKey           = new PrivateKey();
            PublicKey publicKey            = privateKey.PublicKey;
            var       prevRedeemCodesState = new RedeemCodeState(new Dictionary <PublicKey, Reward>()
            {
                [publicKey] = new Reward(1),
            });
            var gameConfigState = new GameConfigState();
            var agentState      = new AgentState(_agentAddress);

            agentState.avatarAddresses[0] = _avatarAddress;
            var avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                1,
                _tableSheets.GetAvatarSheets(),
                gameConfigState,
                default
                );

            var goldState = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            var initialState = new State()
                               .SetState(_agentAddress, agentState.Serialize())
                               .SetState(RedeemCodeState.Address, prevRedeemCodesState.Serialize())
                               .SetState(GoldCurrencyState.Address, goldState.Serialize())
                               .MintAsset(GoldCurrencyState.Address, goldState.Currency * 100000000);

            if (backward)
            {
                initialState = initialState.SetState(_avatarAddress, avatarState.Serialize());
            }
            else
            {
                initialState = initialState
                               .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize())
                               .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize())
                               .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize())
                               .SetState(_avatarAddress, avatarState.SerializeV2());
            }

            foreach (var(key, value) in _sheets)
            {
                initialState = initialState.SetState(
                    Addresses.TableSheet.Derive(key),
                    value.Serialize()
                    );
            }

            var redeemCode = new RedeemCode(
                ByteUtil.Hex(privateKey.ByteArray),
                _avatarAddress
                );

            IAccountStateDelta nextState = redeemCode.Execute(new ActionContext()
            {
                BlockIndex     = 1,
                Miner          = default,
        public SellCancellation2Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _initialState = new State();
            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            var tableSheets = new TableSheets(sheets);

            var currency          = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(currency);

            _agentAddress = new PrivateKey().ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = new PrivateKey().ToAddress();
            var rankingMapAddress = new PrivateKey().ToAddress();
            var avatarState       = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress)
            {
                worldInformation = new WorldInformation(
                    0,
                    tableSheets.WorldSheet,
                    GameConfig.RequireClearedStageLevel.ActionsInShop),
            };

            agentState.avatarAddresses[0] = _avatarAddress;

            var equipment = ItemFactory.CreateItemUsable(
                tableSheets.EquipmentItemSheet.First,
                Guid.NewGuid(),
                0);
            var shopState = new ShopState();

            shopState.Register(new ShopItem(
                                   _agentAddress,
                                   _avatarAddress,
                                   Guid.NewGuid(),
                                   new FungibleAssetValue(goldCurrencyState.Currency, 100, 0),
                                   equipment));

            var result = new CombinationConsumable.ResultModel()
            {
                id          = default,
Beispiel #10
0
        public void Serialize()
        {
            var currency   = new Currency("NCG", 2, default(Address));
            var state      = new GoldCurrencyState(currency);
            var serialized = (Dictionary)state.Serialize();
            GoldCurrencyState deserialized = new GoldCurrencyState(serialized);

            Assert.Equal(currency.Hash, deserialized.Currency.Hash);
        }
Beispiel #11
0
        public Sell0Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _initialState = new State();
            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            _tableSheets = new TableSheets(sheets);

            _currency = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(_currency);

            var shopState = new ShopState();

            _agentAddress = new PrivateKey().ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = new PrivateKey().ToAddress();
            var rankingMapAddress = new PrivateKey().ToAddress();

            _avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress)
            {
                worldInformation = new WorldInformation(
                    0,
                    _tableSheets.WorldSheet,
                    GameConfig.RequireClearedStageLevel.ActionsInShop),
            };
            agentState.avatarAddresses[0] = _avatarAddress;

            var equipment = ItemFactory.CreateItemUsable(
                _tableSheets.EquipmentItemSheet.First,
                Guid.NewGuid(),
                0);

            _avatarState.inventory.AddItem2(equipment);

            _initialState = _initialState
                            .SetState(GoldCurrencyState.Address, goldCurrencyState.Serialize())
                            .SetState(Addresses.Shop, shopState.Serialize())
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, _avatarState.Serialize());
        }
        public CombinationEquipment6Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _agentAddress  = default;
            _avatarAddress = _agentAddress.Derive("avatar");
            var slotAddress = _avatarAddress.Derive(
                string.Format(
                    CultureInfo.InvariantCulture,
                    CombinationSlotState.DeriveFormat,
                    0
                    )
                );
            var sheets = TableSheetsImporter.ImportSheets();

            _random      = new TestRandom();
            _tableSheets = new TableSheets(sheets);
            var agentState = new AgentState(_agentAddress);

            agentState.avatarAddresses[0] = _avatarAddress;

            var gameConfigState = new GameConfigState();

            _avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                1,
                _tableSheets.GetAvatarSheets(),
                gameConfigState,
                default
                );
            var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            _initialState = new State()
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, _avatarState.Serialize())
                            .SetState(
                slotAddress,
                new CombinationSlotState(
                    slotAddress,
                    GameConfig.RequireClearedStageLevel.CombinationEquipmentAction
                    ).Serialize())
                            .SetState(GoldCurrencyState.Address, gold.Serialize())
                            .MintAsset(_agentAddress, gold.Currency * 300);

            foreach (var(key, value) in sheets)
            {
                _initialState =
                    _initialState.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Beispiel #13
0
        public BuyMultipleTest(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _initialState = new State();
            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            _tableSheets = new TableSheets(sheets);

            var currency = new Currency("NCG", 2, minters: null);

            _goldCurrencyState = new GoldCurrencyState(currency);

            _sellerAgentStateMap = new Dictionary <AvatarState, AgentState>();

            _buyerAgentAddress = new PrivateKey().ToAddress();
            var buyerAgentState = new AgentState(_buyerAgentAddress);

            _buyerAvatarAddress = new PrivateKey().ToAddress();
            var rankingMapAddress = new PrivateKey().ToAddress();

            _buyerAvatarState = new AvatarState(
                _buyerAvatarAddress,
                _buyerAgentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress)
            {
                worldInformation = new WorldInformation(
                    0,
                    _tableSheets.WorldSheet,
                    GameConfig.RequireClearedStageLevel.ActionsInShop),
            };
            buyerAgentState.avatarAddresses[0] = _buyerAvatarAddress;

            var shopState = new ShopState();

            _initialState = _initialState
                            .SetState(GoldCurrencyState.Address, _goldCurrencyState.Serialize())
                            .SetState(Addresses.Shop, shopState.Serialize())
                            .SetState(_buyerAgentAddress, buyerAgentState.Serialize())
                            .SetState(_buyerAvatarAddress, _buyerAvatarState.Serialize())
                            .MintAsset(_buyerAgentAddress, _goldCurrencyState.Currency * 100);
        }
Beispiel #14
0
        public async Task TransferGold()
        {
            NineChroniclesNodeService service = StandaloneContextFx.NineChroniclesNodeService !;
            Currency goldCurrency             = new GoldCurrencyState(
                (Dictionary)BlockChain.GetState(GoldCurrencyState.Address)
                ).Currency;

            Address senderAddress = service.MinerPrivateKey !.ToAddress();

            var store = service.Store;
            await BlockChain.MineBlock(service.MinerPrivateKey);

            await BlockChain.MineBlock(service.MinerPrivateKey);

            // 10 + 10 (mining rewards)
            Assert.Equal(
                20 * goldCurrency,
                BlockChain.GetBalance(senderAddress, goldCurrency)
                );

            var             recipientKey = new PrivateKey();
            Address         recipient    = recipientKey.ToAddress();
            var             query        = $"mutation {{ transferGold(recipient: \"{recipient}\", amount: \"17.5\") }}";
            ExecutionResult result       = await ExecuteQueryAsync(query);

            var stagedTxIds = BlockChain.GetStagedTransactionIds().ToImmutableList();

            Assert.Single(stagedTxIds);

            var expectedResult = new Dictionary <string, object>
            {
                ["transferGold"] = stagedTxIds.Single().ToString(),
            };

            Assert.Null(result.Errors);
            Assert.Equal(expectedResult, result.Data);

            await BlockChain.MineBlock(recipientKey);

            // 10 + 10 - 17.5(transfer)
            Assert.Equal(
                FungibleAssetValue.Parse(goldCurrency, "2.5"),
                BlockChain.GetBalance(senderAddress, goldCurrency)
                );

            // 0 + 17.5(transfer) + 10(mining reward)
            Assert.Equal(
                FungibleAssetValue.Parse(goldCurrency, "27.5"),
                BlockChain.GetBalance(recipient, goldCurrency)
                );
        }
Beispiel #15
0
        public void Execute()
        {
            var action = new CreateAvatar()
            {
                avatarAddress = _avatarAddress,
                index         = 0,
                hair          = 0,
                ear           = 0,
                lens          = 0,
                tail          = 0,
                name          = "test",
            };

            var gold    = new GoldCurrencyState(new Currency("NCG", 2, minter: null));
            var ranking = new RankingState();

            for (var i = 0; i < RankingState.RankingMapCapacity; i++)
            {
                ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet();
            }

            var sheets = TableSheetsImporter.ImportSheets();
            var state  = new State()
                         .SetState(GoldCurrencyState.Address, gold.Serialize())
                         .SetState(
                Addresses.GoldDistribution,
                GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize()
                )
                         .SetState(
                Addresses.GameConfig,
                new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize()
                )
                         .SetState(Addresses.Ranking, ranking.Serialize())
                         .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000);

            foreach (var(key, value) in sheets)
            {
                state = state.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            var nextState = action.Execute(new ActionContext()
            {
                PreviousStates = state,
                Signer         = _agentAddress,
                BlockIndex     = 0,
            });

            Assert.Equal(
                0,
                nextState.GetBalance(default, gold.Currency).MajorUnit
Beispiel #16
0
        public void SerializeWithDotnetAPI()
        {
            var currency  = new Currency("NCG", 2, default(Address));
            var state     = new GoldCurrencyState(currency);
            var formatter = new BinaryFormatter();

            using var ms = new MemoryStream();
            formatter.Serialize(ms, state);

            ms.Seek(0, SeekOrigin.Begin);
            var deserialized = (GoldCurrencyState)formatter.Deserialize(ms);

            Assert.Equal(currency.Hash, deserialized.Currency.Hash);
        }
        public CombinationConsumableTest()
        {
            _agentAddress  = new PrivateKey().ToAddress();
            _avatarAddress = _agentAddress.Derive("avatar");
            var slotAddress = _avatarAddress.Derive(
                string.Format(
                    CultureInfo.InvariantCulture,
                    CombinationSlotState.DeriveFormat,
                    0
                    )
                );
            var sheets = TableSheetsImporter.ImportSheets();

            _random      = new TestRandom();
            _tableSheets = new TableSheets(sheets);

            var agentState = new AgentState(_agentAddress);

            agentState.avatarAddresses[0] = _avatarAddress;

            var gameConfigState = new GameConfigState();

            var avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                1,
                _tableSheets.GetAvatarSheets(),
                gameConfigState,
                default
                );

            var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            _initialState = new State()
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, avatarState.Serialize())
                            .SetState(
                slotAddress,
                new CombinationSlotState(
                    slotAddress,
                    GameConfig.RequireClearedStageLevel.CombinationConsumableAction).Serialize())
                            .SetState(GameConfigState.Address, gold.Serialize());

            foreach (var(key, value) in sheets)
            {
                _initialState =
                    _initialState.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Beispiel #18
0
 protected override void LoadPlainValueInternal(IImmutableDictionary <string, IValue> plainValue)
 {
     RankingState           = new RankingState((Bencodex.Types.Dictionary)plainValue["ranking_state"]);
     ShopState              = new ShopState((Bencodex.Types.Dictionary)plainValue["shop_state"]);
     TableSheetsState       = new TableSheetsState((Bencodex.Types.Dictionary)plainValue["table_sheets_state"]);
     GameConfigState        = new GameConfigState((Bencodex.Types.Dictionary)plainValue["game_config_state"]);
     RedeemCodeState        = new RedeemCodeState((Bencodex.Types.Dictionary)plainValue["redeem_code_state"]);
     AdminAddressState      = new AdminState((Bencodex.Types.Dictionary)plainValue["admin_address_state"]);
     ActivatedAccountsState = new ActivatedAccountsState(
         (Bencodex.Types.Dictionary)plainValue["activated_accounts_state"]
         );
     GoldCurrencyState = new GoldCurrencyState(
         (Bencodex.Types.Dictionary)plainValue["gold_currency_state"]
         );
 }
Beispiel #19
0
        public ItemEnhancementTest()
        {
            var sheets = TableSheetsImporter.ImportSheets();

            _random      = new TestRandom();
            _tableSheets = new TableSheets(sheets);
            var privateKey = new PrivateKey();

            _agentAddress = privateKey.PublicKey.ToAddress();
            var agentState = new AgentState(_agentAddress);

            _avatarAddress = _agentAddress.Derive("avatar");
            _avatarState   = new AvatarState(
                _avatarAddress,
                _agentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                default
                );

            agentState.avatarAddresses.Add(0, _avatarAddress);

            _currency = new Currency("NCG", 2, minter: null);
            var gold = new GoldCurrencyState(_currency);

            _slotAddress =
                _avatarAddress.Derive(string.Format(CultureInfo.InvariantCulture, CombinationSlotState.DeriveFormat, 0));

            _initialState = new State()
                            .SetState(_agentAddress, agentState.Serialize())
                            .SetState(_avatarAddress, _avatarState.Serialize())
                            .SetState(_slotAddress, new CombinationSlotState(_slotAddress, 0).Serialize())
                            .SetState(GoldCurrencyState.Address, gold.Serialize())
                            .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000)
                            .TransferAsset(Addresses.GoldCurrency, _agentAddress, gold.Currency * 1000);

            Assert.Equal(gold.Currency * 99999999000, _initialState.GetBalance(Addresses.GoldCurrency, gold.Currency));
            Assert.Equal(gold.Currency * 1000, _initialState.GetBalance(_agentAddress, gold.Currency));

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Beispiel #20
0
        public MonsterCollectTest()
        {
            Dictionary <string, string> sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);
            _signer      = default;
            var currency          = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(currency);

            _initialState = new State()
                            .SetState(Addresses.GoldCurrency, goldCurrencyState.Serialize());
            foreach ((string key, string value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize())
                                .SetState(_signer, new AgentState(_signer).Serialize());
            }
        }
Beispiel #21
0
        public ClaimMonsterCollectionReward2Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _signer        = default;
            _avatarAddress = _signer.Derive("avatar");
            _state         = new State();
            Dictionary <string, string> sheets = TableSheetsImporter.ImportSheets();

            _tableSheets = new TableSheets(sheets);
            var rankingMapAddress = new PrivateKey().ToAddress();
            var agentState        = new AgentState(_signer);
            var avatarState       = new AvatarState(
                _avatarAddress,
                _signer,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress);

            agentState.avatarAddresses[0] = _avatarAddress;

            var currency          = new Currency("NCG", 2, minters: null);
            var goldCurrencyState = new GoldCurrencyState(currency);

            _state = _state
                     .SetState(_signer, agentState.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyInventoryKey), avatarState.inventory.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyWorldInformationKey), avatarState.worldInformation.Serialize())
                     .SetState(_avatarAddress.Derive(LegacyQuestListKey), avatarState.questList.Serialize())
                     .SetState(_avatarAddress, avatarState.SerializeV2())
                     .SetState(Addresses.GoldCurrency, goldCurrencyState.Serialize());

            foreach ((string key, string value) in sheets)
            {
                _state = _state
                         .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }
        }
Beispiel #22
0
        public void Execute()
        {
            var action = new CreateAvatar()
            {
                index = 0,
                hair  = 0,
                ear   = 0,
                lens  = 0,
                tail  = 0,
                name  = "test",
            };

            var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            var sheets = TableSheetsImporter.ImportSheets();
            var state  = new State()
                         .SetState(
                Addresses.GameConfig,
                new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize()
                );

            foreach (var(key, value) in sheets)
            {
                state = state.SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            var nextState = action.Execute(new ActionContext()
            {
                PreviousStates = state,
                Signer         = _agentAddress,
                BlockIndex     = 0,
            });

            var avatarAddress = _agentAddress.Derive(
                string.Format(
                    CultureInfo.InvariantCulture,
                    CreateAvatar2.DeriveFormat,
                    0
                    )
                );

            Assert.True(nextState.TryGetAgentAvatarStatesV2(
Beispiel #23
0
        public void Execute()
        {
            var privateKey   = new PrivateKey();
            var agentAddress = privateKey.PublicKey.ToAddress();
            var agent        = new AgentState(agentAddress);

            var avatarAddress = agentAddress.Derive("avatar");
            var avatar        = new AvatarState(avatarAddress, agentAddress, 0, _tableSheets, new GameConfigState());

            agent.avatarAddresses.Add(0, avatarAddress);

            var weekly = new WeeklyArenaState(default(Address));

            weekly.Set(avatar, _tableSheets.CharacterSheet);
            weekly.End();

            var gold = new GoldCurrencyState(new Currency("NCG", minter: null));

            var state = new State(ImmutableDictionary <Address, IValue> .Empty
                                  .Add(default, weekly.Serialize())
Beispiel #24
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx              = context;
            var            states           = ctx.PreviousStates;
            var            weeklyArenaState = new WeeklyArenaState(0);

            if (ctx.Rehearsal)
            {
                states = states.SetState(RankingState.Address, MarkChanged);
                states = states.SetState(ShopState.Address, MarkChanged);
                states = states.SetState(TableSheetsState.Address, MarkChanged);
                states = states.SetState(weeklyArenaState.address, MarkChanged);
                states = states.SetState(GameConfigState.Address, MarkChanged);
                states = states.SetState(RedeemCodeState.Address, MarkChanged);
                states = states.SetState(AdminState.Address, MarkChanged);
                states = states.SetState(ActivatedAccountsState.Address, MarkChanged);
                states = states.SetState(GoldCurrencyState.Address, MarkChanged);
                states = states.SetState(Addresses.GoldDistribution, MarkChanged);
                return(states);
            }

            if (ctx.BlockIndex != 0)
            {
                return(states);
            }

            states = states
                     .SetState(weeklyArenaState.address, weeklyArenaState.Serialize())
                     .SetState(RankingState.Address, RankingState.Serialize())
                     .SetState(ShopState.Address, ShopState.Serialize())
                     .SetState(TableSheetsState.Address, TableSheetsState.Serialize())
                     .SetState(GameConfigState.Address, GameConfigState.Serialize())
                     .SetState(RedeemCodeState.Address, RedeemCodeState.Serialize())
                     .SetState(AdminState.Address, AdminAddressState.Serialize())
                     .SetState(ActivatedAccountsState.Address, ActivatedAccountsState.Serialize())
                     .SetState(GoldCurrencyState.Address, GoldCurrencyState.Serialize())
                     .SetState(Addresses.GoldDistribution, GoldDistributions.Select(v => v.Serialize()).Serialize());

            states = states.MintAsset(GoldCurrencyState.Address, GoldCurrencyState.Currency, 1000000000);
            return(states);
        }
Beispiel #25
0
 public MakeInitialStateResult(
     IAccountStateDelta state,
     CreateTestbed testbed,
     AgentState agentState,
     AvatarState avatarState,
     GoldCurrencyState goldCurrencyState,
     Address rankingMapAddress,
     TableSheets tableSheets,
     FungibleAssetValue currencyGold,
     FungibleAssetValue agentCurrencyGold)
 {
     _state             = state;
     _testbed           = testbed;
     _agentState        = agentState;
     _avatarState       = avatarState;
     _goldCurrencyState = goldCurrencyState;
     _rankingMapAddress = rankingMapAddress;
     _tableSheets       = tableSheets;
     _currencyGold      = currencyGold;
     _agentCurrencyGold = agentCurrencyGold;
 }
Beispiel #26
0
        public void Execute()
        {
            var       privateKey           = new PrivateKey();
            PublicKey publicKey            = privateKey.PublicKey;
            var       prevRedeemCodesState = new RedeemCodeState(new Dictionary <PublicKey, Reward>()
            {
                [publicKey] = new Reward(1),
            });
            var gameConfigState = new GameConfigState();
            var agentState      = new AgentState(_agentAddress);

            agentState.avatarAddresses[0] = _avatarAddress;
            var avatarState = new AvatarState(
                _avatarAddress,
                _agentAddress,
                1,
                _tableSheets,
                gameConfigState
                );

            var goldState = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            var initialState = new State()
                               .SetState(_agentAddress, agentState.Serialize())
                               .SetState(_avatarAddress, avatarState.Serialize())
                               .SetState(TableSheetsState.Address, _tableSheetsState.Serialize())
                               .SetState(RedeemCodeState.Address, prevRedeemCodesState.Serialize())
                               .SetState(GoldCurrencyState.Address, goldState.Serialize())
                               .MintAsset(GoldCurrencyState.Address, goldState.Currency * 100000000);
            var redeemCode = new RedeemCode(
                ByteUtil.Hex(privateKey.ByteArray),
                _avatarAddress
                );

            IAccountStateDelta nextState = redeemCode.Execute(new ActionContext()
            {
                BlockIndex     = 1,
                Miner          = default,
Beispiel #27
0
        public InitializeStates(
            RankingState rankingState,
            ShopState shopState,
            Dictionary <string, string> tableSheets,
            GameConfigState gameConfigState,
            RedeemCodeState redeemCodeState,
            AdminState adminAddressState,
            ActivatedAccountsState activatedAccountsState,
            GoldCurrencyState goldCurrencyState,
            GoldDistribution[] goldDistributions,
            PendingActivationState[] pendingActivationStates,
            AuthorizedMinersState authorizedMinersState = null,
            CreditsState creditsState = null)
        {
            Ranking           = (Bencodex.Types.Dictionary)rankingState.Serialize();
            Shop              = (Bencodex.Types.Dictionary)shopState.Serialize();
            TableSheets       = tableSheets;
            GameConfig        = (Bencodex.Types.Dictionary)gameConfigState.Serialize();
            RedeemCode        = (Bencodex.Types.Dictionary)redeemCodeState.Serialize();
            AdminAddress      = (Bencodex.Types.Dictionary)adminAddressState.Serialize();
            ActivatedAccounts = (Bencodex.Types.Dictionary)activatedAccountsState.Serialize();
            GoldCurrency      = (Bencodex.Types.Dictionary)goldCurrencyState.Serialize();
            GoldDistributions = new Bencodex.Types.List(
                goldDistributions.Select(d => d.Serialize()).Cast <Bencodex.Types.IValue>()
                );
            PendingActivations = new Bencodex.Types.List(pendingActivationStates.Select(p => p.Serialize()));

            if (!(authorizedMinersState is null))
            {
                AuthorizedMiners = (Bencodex.Types.Dictionary)authorizedMinersState.Serialize();
            }

            if (!(creditsState is null))
            {
                Credits = (Bencodex.Types.Dictionary)creditsState.Serialize();
            }
        }
Beispiel #28
0
        public async Task Sell(Address sellerAvatarAddress, Guid itemId, int price)
        {
            var playerPrivateKey = new PrivateKey();
            var query            = $@"mutation {{
                action {{
                    sell(sellerAvatarAddress: ""{sellerAvatarAddress}"", itemId: ""{itemId}"", price: {price})
                }}
            }}";
            var result           = await ExecuteQueryAsync(query);

            Assert.Null(result.Errors);

            var txIds = BlockChain.GetStagedTransactionIds();

            Assert.Single(txIds);
            var tx       = BlockChain.GetTransaction(txIds.First());
            var expected = new Dictionary <string, object>
            {
                ["action"] = new Dictionary <string, object>
                {
                    ["sell"] = tx.Id.ToString(),
                }
            };

            Assert.Equal(expected, result.Data);
            Assert.Single(tx.Actions);
            var action = (Sell3)tx.Actions.First().InnerAction;

            Assert.Equal(sellerAvatarAddress, action.sellerAvatarAddress);
            Assert.Equal(itemId, action.itemId);
            var currency = new GoldCurrencyState(
                (Dictionary)BlockChain.GetState(GoldCurrencyState.Address)
                ).Currency;

            Assert.Equal(price * currency, action.price);
        }
        public WeeklyArenaStateUpdateScenarioTest()
        {
            _initialState = new Tests.Action.State();

            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState.SetState(
                    Addresses.TableSheet.Derive(key),
                    value.Serialize());
            }

            var tableSheets = new TableSheets(sheets);

            var rankingMapAddress = new PrivateKey().ToAddress();

            _agent1Address  = new PrivateKey().ToAddress();
            _avatar1Address = new PrivateKey().ToAddress();

            var agentState  = new AgentState(_agent1Address);
            var avatarState = new AvatarState(
                _avatar1Address,
                _agent1Address,
                0,
                tableSheets.GetAvatarSheets(),
                new GameConfigState(sheets[nameof(GameConfigSheet)]),
                rankingMapAddress
                )
            {
                worldInformation = new WorldInformation(
                    0,
                    tableSheets.WorldSheet,
                    Math.Max(
                        tableSheets.StageSheet.First?.Id ?? 1,
                        GameConfig.RequireClearedStageLevel.ActionsInRankingBoard)),
                level = 100,
            };

            agentState.avatarAddresses.Add(0, _avatar1Address);

            var agent2Address = new PrivateKey().ToAddress();

            _avatar2Address = new PrivateKey().ToAddress();

            var agent2State  = new AgentState(agent2Address);
            var avatar2State = new AvatarState(
                _avatar2Address,
                agent2Address,
                0,
                tableSheets.GetAvatarSheets(),
                new GameConfigState(sheets[nameof(GameConfigSheet)]),
                rankingMapAddress
                )
            {
                worldInformation = new WorldInformation(
                    0,
                    tableSheets.WorldSheet,
                    Math.Max(
                        tableSheets.StageSheet.First?.Id ?? 1,
                        GameConfig.RequireClearedStageLevel.ActionsInRankingBoard)),
                level = 100,
            };

            agent2State.avatarAddresses.Add(0, _avatar2Address);

            var agent3Address = new PrivateKey().ToAddress();

            _avatar3Address = new PrivateKey().ToAddress();

            var agent3State  = new AgentState(agent3Address);
            var avatar3State = new AvatarState(
                _avatar3Address,
                agent2Address,
                0,
                tableSheets.GetAvatarSheets(),
                new GameConfigState(sheets[nameof(GameConfigSheet)]),
                rankingMapAddress
                )
            {
                worldInformation = new WorldInformation(
                    0,
                    tableSheets.WorldSheet,
                    Math.Max(
                        tableSheets.StageSheet.First?.Id ?? 1,
                        GameConfig.RequireClearedStageLevel.ActionsInRankingBoard)),
                level = 100,
            };

            agent3State.avatarAddresses.Add(0, _avatar3Address);

            var prevWeeklyArenaState = new WeeklyArenaState(RankingBattle.UpdateTargetWeeklyArenaIndex - 2);
            var weeklyArenaState     = new WeeklyArenaState(RankingBattle.UpdateTargetWeeklyArenaIndex - 1);

            weeklyArenaState.SetV2(avatarState, tableSheets.CharacterSheet, tableSheets.CostumeStatSheet);
            weeklyArenaState[_avatar1Address].Activate();
            weeklyArenaState.SetV2(avatar2State, tableSheets.CharacterSheet, tableSheets.CostumeStatSheet);
            weeklyArenaState[_avatar2Address].Activate();
            _weeklyArenaAddress = WeeklyArenaState.DeriveAddress(RankingBattle.UpdateTargetWeeklyArenaIndex);

            var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null));

            _initialState = _initialState
                            .SetState(_agent1Address, agentState.Serialize())
                            .SetState(_avatar1Address, avatarState.Serialize())
                            .SetState(agent2Address, agent2State.Serialize())
                            .SetState(_avatar2Address, avatar2State.Serialize())
                            .SetState(agent3Address, agent2State.Serialize())
                            .SetState(_avatar3Address, avatar2State.Serialize())
                            .SetState(Addresses.GameConfig, new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize())
                            .SetState(prevWeeklyArenaState.address, prevWeeklyArenaState.Serialize())
                            .SetState(weeklyArenaState.address, weeklyArenaState.Serialize())
                            .SetState(_weeklyArenaAddress, new WeeklyArenaState(RankingBattle.UpdateTargetWeeklyArenaIndex).Serialize())
                            .SetState(GoldCurrencyState.Address, gold.Serialize())
                            .SetState(Addresses.GoldDistribution, GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize())
                            .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000);
        }
Beispiel #30
0
        public Buy3Test(ITestOutputHelper outputHelper)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.TestOutput(outputHelper)
                         .CreateLogger();

            _initialState = new State();
            var sheets = TableSheetsImporter.ImportSheets();

            foreach (var(key, value) in sheets)
            {
                _initialState = _initialState
                                .SetState(Addresses.TableSheet.Derive(key), value.Serialize());
            }

            _tableSheets = new TableSheets(sheets);

            var currency = new Currency("NCG", 2, minters: null);

            _goldCurrencyState = new GoldCurrencyState(currency);

            _sellerAgentAddress = new PrivateKey().ToAddress();
            var sellerAgentState = new AgentState(_sellerAgentAddress);

            _sellerAvatarAddress = new PrivateKey().ToAddress();
            var rankingMapAddress = new PrivateKey().ToAddress();
            var sellerAvatarState = new AvatarState(
                _sellerAvatarAddress,
                _sellerAgentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress)
            {
                worldInformation = new WorldInformation(
                    0,
                    _tableSheets.WorldSheet,
                    GameConfig.RequireClearedStageLevel.ActionsInShop),
            };

            sellerAgentState.avatarAddresses[0] = _sellerAvatarAddress;

            _buyerAgentAddress = new PrivateKey().ToAddress();
            var buyerAgentState = new AgentState(_buyerAgentAddress);

            _buyerAvatarAddress = new PrivateKey().ToAddress();
            _buyerAvatarState   = new AvatarState(
                _buyerAvatarAddress,
                _buyerAgentAddress,
                0,
                _tableSheets.GetAvatarSheets(),
                new GameConfigState(),
                rankingMapAddress)
            {
                worldInformation = new WorldInformation(
                    0,
                    _tableSheets.WorldSheet,
                    GameConfig.RequireClearedStageLevel.ActionsInShop),
            };
            buyerAgentState.avatarAddresses[0] = _buyerAvatarAddress;

            var equipment = ItemFactory.CreateItemUsable(
                _tableSheets.EquipmentItemSheet.First,
                Guid.NewGuid(),
                0);

            var consumable = ItemFactory.CreateItemUsable(
                _tableSheets.ConsumableItemSheet.First,
                Guid.NewGuid(),
                0);

            var costume = ItemFactory.CreateCostume(
                _tableSheets.CostumeItemSheet.First,
                Guid.NewGuid());

            var shopState = new ShopState();

            shopState.Register(new ShopItem(
                                   _sellerAgentAddress,
                                   _sellerAvatarAddress,
                                   Guid.NewGuid(),
                                   new FungibleAssetValue(_goldCurrencyState.Currency, ProductPrice, 0),
                                   equipment));

            shopState.Register(new ShopItem(
                                   _sellerAgentAddress,
                                   _sellerAvatarAddress,
                                   Guid.NewGuid(),
                                   new FungibleAssetValue(_goldCurrencyState.Currency, ProductPrice, 0),
                                   consumable));

            shopState.Register(new ShopItem(
                                   _sellerAgentAddress,
                                   _sellerAvatarAddress,
                                   Guid.NewGuid(),
                                   new FungibleAssetValue(_goldCurrencyState.Currency, ProductPrice, 0),
                                   costume));

            _initialState = _initialState
                            .SetState(GoldCurrencyState.Address, _goldCurrencyState.Serialize())
                            .SetState(Addresses.Shop, shopState.Serialize())
                            .SetState(_sellerAgentAddress, sellerAgentState.Serialize())
                            .SetState(_sellerAvatarAddress, sellerAvatarState.Serialize())
                            .SetState(_buyerAgentAddress, buyerAgentState.Serialize())
                            .SetState(_buyerAvatarAddress, _buyerAvatarState.Serialize())
                            .MintAsset(_buyerAgentAddress, shopState.Products
                                       .Select(pair => pair.Value.Price)
                                       .Aggregate((totalPrice, next) => totalPrice + next));
        }