From 221f6c5fd1d64a86efd9c7a8279d09683a462c00 Mon Sep 17 00:00:00 2001 From: eugene-hong <58686228+eugene-doobu@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:19:44 +0900 Subject: [PATCH 1/3] apply code style rule to test code --- .../Action/AccountStateDeltaExtensionsTest.cs | 6 +- .../Action/AccountStateViewExtensionsTest.cs | 32 +- .Lib9c.Tests/Action/ActionContext.cs | 15 +- .../Action/ActionContextExtensionsTest.cs | 2 +- .Lib9c.Tests/Action/ActionEvaluationTest.cs | 8 +- .Lib9c.Tests/Action/ActivateCollectionTest.cs | 7 +- .Lib9c.Tests/Action/AddRedeemCodeTest.cs | 6 +- .../ClaimAdventureBossRewardTest.cs | 16 +- .../AdventureBoss/ExploreAdventureBossTest.cs | 10 +- .../AdventureBoss/SweepAdventureBossTest.cs | 6 +- .../Action/AdventureBoss/UnlockFloorTest.cs | 4 +- .../Action/AdventureBoss/WantedTest.cs | 26 +- .Lib9c.Tests/Action/ApprovePledgeTest.cs | 6 +- .Lib9c.Tests/Action/ArenahelperTest.cs | 2 +- .Lib9c.Tests/Action/BattleArenaTest.cs | 22 +- .Lib9c.Tests/Action/BurnAssetTest.cs | 14 +- .Lib9c.Tests/Action/BuyMultipleTest.cs | 14 +- .Lib9c.Tests/Action/BuyProductTest.cs | 15 +- .Lib9c.Tests/Action/BuyTest.cs | 293 ++++---- .../Action/CancelProductRegistrationTest.cs | 4 +- .Lib9c.Tests/Action/ChargeActionPointTest.cs | 2 +- .Lib9c.Tests/Action/ClaimItemsTest.cs | 20 +- .Lib9c.Tests/Action/ClaimRaidRewardTest.cs | 6 +- .Lib9c.Tests/Action/ClaimStakeRewardTest.cs | 2 +- .../Action/ClaimWorldBossKillRewardTest.cs | 4 +- .../Action/CombinationConsumableTest.cs | 2 +- .../Action/CombinationEquipmentTest.cs | 12 +- .Lib9c.Tests/Action/Coupons/CouponsFixture.cs | 21 +- .../Action/Coupons/IssueCouponsTest.cs | 32 +- .../Action/Coupons/RedeemCouponTest.cs | 78 +-- .../Action/Coupons/TransferCouponsTest.cs | 32 +- .../Action/CreatePendingActivationTest.cs | 4 +- .../Action/CreatePendingActivationsTest.cs | 13 +- .Lib9c.Tests/Action/CreatePledgeTest.cs | 6 +- .../CustomEquipmentCraftTest.cs | 8 +- .Lib9c.Tests/Action/DailyRewardTest.cs | 4 +- .Lib9c.Tests/Action/EndPledgeTest.cs | 10 +- .Lib9c.Tests/Action/EventDungeonBattleTest.cs | 24 +- .../Factory/ClaimStakeRewardFactoryTest.cs | 2 +- .../Garages/BulkUnloadFromGaragesTest.cs | 12 +- .../Garages/DeliverToOthersGaragesTest.cs | 20 +- .../Action/Garages/LoadIntoMyGaragesTest.cs | 23 +- .../Action/Garages/UnloadFromMyGaragesTest.cs | 18 +- .Lib9c.Tests/Action/GoldDistributionTest.cs | 16 +- .Lib9c.Tests/Action/GrindingTest.cs | 32 +- .../Guild/AcceptGuildApplicationTest.cs | 2 +- .Lib9c.Tests/Action/Guild/ApplyGuildTest.cs | 4 +- .../Action/Guild/BanGuildMemberTest.cs | 2 +- .../Guild/CancelGuildApplicationTest.cs | 2 +- .Lib9c.Tests/Action/Guild/MakeGuildTest.cs | 27 +- .../Guild/Migration/GuildMigrationCtrlTest.cs | 2 +- .../Migration/MigratePledgeToGuildTest.cs | 2 +- .Lib9c.Tests/Action/Guild/QuitGuildTest.cs | 2 +- .../Guild/RejectGuildApplicationTest.cs | 2 +- .Lib9c.Tests/Action/HackAndSlashSweepTest.cs | 24 +- .Lib9c.Tests/Action/HackAndSlashTest.cs | 62 +- .Lib9c.Tests/Action/HitHelperTest.cs | 4 +- .Lib9c.Tests/Action/InitializeStatesTest.cs | 106 +-- .../Action/InvalidSignatureExceptionTest.cs | 4 +- .Lib9c.Tests/Action/IssueTokenTest.cs | 8 +- .../Action/IssueTokensFromGarageTest.cs | 12 +- .Lib9c.Tests/Action/ItemEnhancementTest.cs | 18 +- .Lib9c.Tests/Action/JoinArena1Test.cs | 4 +- .Lib9c.Tests/Action/JoinArena3Test.cs | 12 +- .Lib9c.Tests/Action/JoinArenaTest.cs | 633 ++++++++--------- .Lib9c.Tests/Action/MarketValidationTest.cs | 12 +- .Lib9c.Tests/Action/MigrateFeeTest.cs | 241 +++---- .../Action/MigrateMonsterCollectionTest.cs | 40 +- .../MigrationActivatedAccountsStateTest.cs | 4 +- .Lib9c.Tests/Action/MintAssetsTest.cs | 26 +- .Lib9c.Tests/Action/PatchTableSheetTest.cs | 4 +- .Lib9c.Tests/Action/PetEnhancement0Test.cs | 4 +- .../Action/PrepareRewardAssetsTest.cs | 2 +- .Lib9c.Tests/Action/PurchaseInfoTest.cs | 2 +- .Lib9c.Tests/Action/RaidTest.cs | 74 +- .Lib9c.Tests/Action/RapidCombinationTest.cs | 26 +- .Lib9c.Tests/Action/ReRegisterProductTest.cs | 6 +- .Lib9c.Tests/Action/RedeemCodeTest.cs | 23 +- .Lib9c.Tests/Action/RegisterProduct0Test.cs | 11 +- .Lib9c.Tests/Action/RegisterProductTest.cs | 11 +- .Lib9c.Tests/Action/RenewAdminStateTest.cs | 4 +- .Lib9c.Tests/Action/RequestPledgeTest.cs | 12 +- .../Action/RetrieveAvatarAssetsTest.cs | 8 +- .Lib9c.Tests/Action/RewardGoldTest.cs | 43 +- .Lib9c.Tests/Action/RuneEnhancementTest.cs | 34 +- .Lib9c.Tests/Action/RuneHelperTest.cs | 3 +- .../Action/Scenario/ArenaScenarioTest.cs | 8 +- .../Action/Scenario/AuraScenarioTest.cs | 18 +- .../Action/Scenario/CollectionScenarioTest.cs | 12 +- .../Action/Scenario/GrimoireScenarioTest.cs | 20 +- .Lib9c.Tests/Action/Scenario/ItemCraftTest.cs | 20 +- .../Action/Scenario/MarketScenarioTest.cs | 40 +- .../Action/Scenario/MeadScenarioTest.cs | 20 +- .../AdditionalOptionRateByFixedValueTest.cs | 2 +- .../Action/Scenario/Pet/CommonTest.cs | 2 +- .../Pet/DiscountMaterialCostCrystalTest.cs | 2 +- .../Pet/IncreaseBlockPerHourglassTest.cs | 8 +- .../Scenario/Pet/ReduceRequiredBlockTest.cs | 4 +- .../Action/Scenario/RuneScenarioTest.cs | 10 +- .../SellAndCancellationAndSellTest.cs | 8 +- .../Scenario/WorldUnlockScenarioTest.cs | 2 +- .Lib9c.Tests/Action/SecureMiningRewardTest.cs | 28 +- .Lib9c.Tests/Action/Snapshot/ActionUtils.cs | 4 +- .Lib9c.Tests/Action/Stake2Test.cs | 12 +- .Lib9c.Tests/Action/StakeTest.cs | 40 +- .Lib9c.Tests/Action/Summon/AuraSummonTest.cs | 20 +- .Lib9c.Tests/Action/Summon/RuneSummonTest.cs | 18 +- .Lib9c.Tests/Action/TransferAssetTest.cs | 82 +-- .Lib9c.Tests/Action/TransferAssetsTest.cs | 60 +- .../Action/UnlockCombinationSlotTest.cs | 589 ++++++++-------- .../Action/UnlockEquipmentRecipeTest.cs | 34 +- .Lib9c.Tests/Action/UnlockRuneSlotTest.cs | 2 +- .Lib9c.Tests/Action/UnlockWorldTest.cs | 26 +- .../Action/ValidatorSetOperateTest.cs | 10 +- .Lib9c.Tests/Action/WorldBossHelperTest.cs | 3 +- .Lib9c.Tests/AddressesTest.cs | 117 ++-- .Lib9c.Tests/Battle/CPHelperTest.cs | 16 +- .../Battle/SimplePriorityQueueTest.cs | 116 ++-- .Lib9c.Tests/CrystalCalculatorTest.cs | 18 +- .Lib9c.Tests/CurrenciesTest.cs | 20 +- .../Extensions/BencodexTypesExtensionsTest.cs | 47 +- .../Extensions/EventDungeonExtensionsTest.cs | 8 +- .../Extensions/EventScheduleExtensionsTest.cs | 8 +- .../TableCSV/CollectionSheetFixture.cs | 10 +- .../TableCSV/EquipmentItemSheetFixture.cs | 3 +- .../TableCSV/RuneOptionSheetFixture.cs | 9 +- .../TableCSV/Summon/SummonSheetFixtures.cs | 3 +- .Lib9c.Tests/JsonStatesLoader.cs | 6 +- .Lib9c.Tests/JsonStatesLoaderTest.cs | 2 +- .Lib9c.Tests/Model/ActivationKeyTest.cs | 12 +- .../Model/Arena/ArenaParticipantTest.cs | 79 +-- .Lib9c.Tests/Model/Arena/PlayerDigestTest.cs | 8 +- .Lib9c.Tests/Model/ArenaSimulatorTest.cs | 8 +- .Lib9c.Tests/Model/BattleLogTest.cs | 2 +- .Lib9c.Tests/Model/CharacterStatsTest.cs | 4 +- .Lib9c.Tests/Model/Coupons/CouponTest.cs | 2 +- .Lib9c.Tests/Model/Coupons/RewardSetTest.cs | 2 +- .../Model/Event/EventDungeonInfoTest.cs | 4 +- .../Model/Garages/FungibleItemGarageTest.cs | 4 +- .Lib9c.Tests/Model/Item/CostumeTest.cs | 4 +- .Lib9c.Tests/Model/Item/EquipmentTest.cs | 2 +- .Lib9c.Tests/Model/Item/InventoryTest.cs | 2 +- .Lib9c.Tests/Model/Item/ShopItemTest.cs | 15 +- .Lib9c.Tests/Model/ItemUsableTest.cs | 4 +- .../Model/Mail/CustomCraftMailTest.cs | 59 +- .../Model/Mail/MonsterCollectMailTest.cs | 34 +- .../UnloadFromMyGaragesRecipientMailTest.cs | 10 +- .Lib9c.Tests/Model/MonsterCollectSheetTest.cs | 2 +- .../Model/MonsterCollectionRewardSheetTest.cs | 8 +- .Lib9c.Tests/Model/Order/FungibleOrderTest.cs | 637 +++++++++--------- .../Model/Order/NonFungibleOrderTest.cs | 321 ++++----- .../Model/Order/OrderDigestListStateTest.cs | 6 +- .Lib9c.Tests/Model/Order/OrderDigestTest.cs | 8 +- .Lib9c.Tests/Model/Order/OrderFactoryTest.cs | 12 +- .Lib9c.Tests/Model/Order/OrderReceiptTest.cs | 6 +- .Lib9c.Tests/Model/PlayerTest.cs | 18 +- .Lib9c.Tests/Model/QuestListTest.cs | 9 +- .Lib9c.Tests/Model/RankingSimulatorV1Test.cs | 2 +- .Lib9c.Tests/Model/Rune/AllRuneStateTest.cs | 4 +- .Lib9c.Tests/Model/SimulatorTest.cs | 2 +- .../Model/Skill/Adventure/CombatTest.cs | 12 +- .../Skill/Adventure/ShatterStrikeTest.cs | 4 +- .../Model/Skill/Arena/ArenaCombatTest.cs | 4 +- .../Skill/Arena/ArenaShatterStrikeTest.cs | 4 +- .Lib9c.Tests/Model/Skill/BuffFactoryTest.cs | 26 +- .../Model/Skill/Raid/NormalAttackTest.cs | 2 +- .../Model/State/AuthorizedMinersStateTest.cs | 6 +- .Lib9c.Tests/Model/State/AvatarStateTest.cs | 73 +- .Lib9c.Tests/Model/State/CreditsStateTest.cs | 2 +- .../State/CrystalRandomSkillStateTest.cs | 2 +- .../Model/State/GameConfigStateTest.cs | 2 +- .../Model/State/GoldCurrencyStateTest.cs | 6 +- .Lib9c.Tests/Model/State/LazyStateTest.cs | 9 +- .../State/MonsterCollectionState0Test.cs | 46 +- .../Model/State/PendingActivationStateTest.cs | 4 +- .../Model/State/RankingMapStateTest.cs | 2 +- .../Model/State/ShardedShopStateTest.cs | 20 +- .../Model/State/ShardedShopStateV2Test.cs | 20 +- .Lib9c.Tests/Model/State/SheetStateTest.cs | 8 +- .../Model/State/StateExtensionsTest.cs | 12 +- .Lib9c.Tests/Model/WeightedSelectorTest.cs | 10 +- .Lib9c.Tests/Module/CollectionModuleTest.cs | 2 +- .Lib9c.Tests/Policy/BlockPolicySourceTest.cs | 10 +- .Lib9c.Tests/Policy/BlockPolicyTest.cs | 318 ++++----- .Lib9c.Tests/Policy/ConcreteSubPolicy.cs | 6 +- .Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs | 16 +- .Lib9c.Tests/Policy/SpannedSubPolicyTest.cs | 2 +- .Lib9c.Tests/SerializeKeysTest.cs | 14 +- .Lib9c.Tests/StagePolicyTest.cs | 57 +- .Lib9c.Tests/TableData/CollectionSheetTest.cs | 16 +- .../CustomEquipmentCraftOptionSheetTest.cs | 8 +- ...stomEquipmentCraftRelationshipSheetTest.cs | 2 +- .../Event/EventDungeonStageSheetTest.cs | 3 +- .../Event/EventMaterialItemRecipeSheetTest.cs | 3 +- .../Garages/LoadIntoMyGaragesCostSheetTest.cs | 2 +- .../Item/EquipmentItemRecipeSheetTest.cs | 2 +- .../Item/EquipmentItemSubRecipeSheetTest.cs | 3 +- .../Item/EquipmentItemSubRecipeSheetV2Test.cs | 3 +- .../WorldAndStage/WorldUnlockSheetTest.cs | 2 +- .Lib9c.Tests/TableSheets.cs | 36 +- .Lib9c.Tests/TableSheetsImporter.cs | 13 +- .Lib9c.Tests/TestHelper/BencodexHelper.cs | 32 +- .Lib9c.Tests/TestHelper/BlockChainHelper.cs | 20 +- .Lib9c.Tests/Types/BencodexTypesListTest.cs | 4 +- .Lib9c.Tests/Util/CsvUtil.cs | 4 +- .Lib9c.Tests/Util/InitializeUtil.cs | 337 ++++----- 206 files changed, 3235 insertions(+), 3164 deletions(-) diff --git a/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs b/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs index 70d2e66fab..567526bf55 100644 --- a/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs +++ b/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs @@ -49,7 +49,7 @@ public void SetWorldBossKillReward(int level, int expectedRune, int expectedCrys IWorld states = new World(MockUtil.MockModernWorldState); var rewardInfoAddress = new PrivateKey().Address; var rewardRecord = new WorldBossKillRewardRecord(); - for (int i = 0; i < level; i++) + for (var i = 0; i < level; i++) { rewardRecord[i] = false; } @@ -176,8 +176,8 @@ public void Mead(int agentBalance) var agentContractAddress = _agentAddress.GetPledgeAddress(); var mead = Currencies.Mead; var price = RequestPledge.DefaultRefillMead * mead; - ActionContext context = new ActionContext(); - IWorld states = new World(MockUtil.MockModernWorldState) + var context = new ActionContext(); + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState( agentContractAddress, List.Empty.Add(patron.Serialize()).Add(true.Serialize())) diff --git a/.Lib9c.Tests/Action/AccountStateViewExtensionsTest.cs b/.Lib9c.Tests/Action/AccountStateViewExtensionsTest.cs index 424fd0afe2..7400da96a9 100644 --- a/.Lib9c.Tests/Action/AccountStateViewExtensionsTest.cs +++ b/.Lib9c.Tests/Action/AccountStateViewExtensionsTest.cs @@ -67,10 +67,10 @@ public void TryGetAvatarStateKeyNotFoundException() { var states = new World(MockUtil.MockModernWorldState) .SetLegacyState( - default, - Dictionary.Empty - .Add("agentAddress", default(Address).Serialize()) - ); + default, + Dictionary.Empty + .Add("agentAddress", default(Address).Serialize()) + ); Assert.False(states.TryGetAvatarState(default, default, out _)); } @@ -110,7 +110,7 @@ public void GetAvatarStateV2() [InlineData("questList")] public void GetAvatarStateV2_Throw_FailedLoadStateException(string account) { - Address accountAddress = account switch + var accountAddress = account switch { "inventory" => Addresses.Inventory, "worldInformation" => Addresses.WorldInformation, @@ -131,7 +131,7 @@ public void GetAvatarStateV2_Throw_FailedLoadStateException(string account) [Fact] public void TryGetAvatarState() { - IWorld states = new World(MockUtil.MockModernWorldState).SetAvatarState(_avatarAddress, _avatarState); + var states = new World(MockUtil.MockModernWorldState).SetAvatarState(_avatarAddress, _avatarState); Assert.True(states.TryGetAvatarState(_agentAddress, _avatarAddress, out _)); } @@ -193,8 +193,8 @@ public void GetSheets() public void GetCrystalCostState(bool exist) { IWorld states = new World(MockUtil.MockModernWorldState); - int expectedCount = exist ? 1 : 0; - FungibleAssetValue expectedCrystal = exist + var expectedCount = exist ? 1 : 0; + var expectedCrystal = exist ? 100 * CrystalCalculator.CRYSTAL : 0 * CrystalCalculator.CRYSTAL; Address address = default; @@ -205,7 +205,7 @@ public void GetCrystalCostState(bool exist) states = states.SetLegacyState(address, crystalCostState.Serialize()); } - CrystalCostState actual = states.GetCrystalCostState(address); + var actual = states.GetCrystalCostState(address); Assert.Equal(expectedCount, actual.Count); Assert.Equal(expectedCrystal, actual.CRYSTAL); } @@ -217,15 +217,15 @@ public void GetCrystalCostState(bool exist) [InlineData(151_200L, true)] public void GetCrystalCostStates(long blockIndex, bool previousWeeklyExist) { - long interval = _tableSheets.CrystalFluctuationSheet.Values.First(r => r.Type == CrystalFluctuationSheet.ServiceType.Combination).BlockInterval; + var interval = _tableSheets.CrystalFluctuationSheet.Values.First(r => r.Type == CrystalFluctuationSheet.ServiceType.Combination).BlockInterval; var weeklyIndex = (int)(blockIndex / interval); - Address dailyCostAddress = + var dailyCostAddress = Addresses.GetDailyCrystalCostAddress((int)(blockIndex / CrystalCostState.DailyIntervalIndex)); - Address weeklyCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex); - Address previousCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex - 1); - Address beforePreviousCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex - 2); + var weeklyCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex); + var previousCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex - 1); + var beforePreviousCostAddress = Addresses.GetWeeklyCrystalCostAddress(weeklyIndex - 2); var crystalCostState = new CrystalCostState(default, 100 * CrystalCalculator.CRYSTAL); - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(dailyCostAddress, crystalCostState.Serialize()) .SetLegacyState(weeklyCostAddress, crystalCostState.Serialize()) .SetLegacyState(previousCostAddress, crystalCostState.Serialize()) @@ -311,7 +311,7 @@ public void GetCouponWallet() states = states.SetLegacyState( agentAddress1.Derive(CouponWalletKey), - (Bencodex.Types.Binary)new byte[] { 0x00 }); + (Bencodex.Types.Binary)new byte[] { 0x00, }); Assert.Throws(() => states.GetCouponWallet(agentAddress1)); Assert.Throws(() => states.GetCouponWallet(agentAddress2)); diff --git a/.Lib9c.Tests/Action/ActionContext.cs b/.Lib9c.Tests/Action/ActionContext.cs index c366d29099..1b074426d7 100644 --- a/.Lib9c.Tests/Action/ActionContext.cs +++ b/.Lib9c.Tests/Action/ActionContext.cs @@ -60,11 +60,20 @@ public void UseGas(long gas) _gasUsed += gas; } - public IRandom GetRandom() => _random ?? new TestRandom(RandomSeed); + public IRandom GetRandom() + { + return _random ?? new TestRandom(RandomSeed); + } - public long GasUsed() => _gasUsed; + public long GasUsed() + { + return _gasUsed; + } - public long GasLimit() => 0; + public long GasLimit() + { + return 0; + } // FIXME: Temporary measure to allow inheriting already mutated IRandom. public void SetRandom(IRandom random) diff --git a/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs b/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs index 6af16f6417..0808e021e5 100644 --- a/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs +++ b/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs @@ -74,7 +74,7 @@ public static IEnumerable IsMainNetTestcases() Currency.Legacy("BTC", 2, new Address("47d082a115c63e7b58b1532d20e631538eafadde"))), false, }; - #pragma warning restore CS0618 +#pragma warning restore CS0618 } public static IEnumerable IsPreviewNetTestcases() diff --git a/.Lib9c.Tests/Action/ActionEvaluationTest.cs b/.Lib9c.Tests/Action/ActionEvaluationTest.cs index 543224a969..ad019ed82b 100644 --- a/.Lib9c.Tests/Action/ActionEvaluationTest.cs +++ b/.Lib9c.Tests/Action/ActionEvaluationTest.cs @@ -171,7 +171,7 @@ private ActionBase GetAction(Type type) new PrivateKey().Address, ItemSubType.Armor, #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 Currency.Legacy("NCG", 2, null) * 10 #pragma warning restore CS0618 ), @@ -181,7 +181,7 @@ private ActionBase GetAction(Type type) CombinationConsumable _ => new CombinationConsumable(), CombinationEquipment _ => new CombinationEquipment(), CreatePendingActivation _ => new CreatePendingActivation( - new PendingActivationState(new byte[] { 0x0 }, new PrivateKey().PublicKey) + new PendingActivationState(new byte[] { 0x0, }, new PrivateKey().PublicKey) ), DailyReward _ => new DailyReward(), InitializeStates _ => new InitializeStates @@ -437,7 +437,7 @@ private ActionBase GetAction(Type type) CreatePledge _ => new CreatePledge { PatronAddress = new PrivateKey().Address, - AgentAddresses = new[] { (new PrivateKey().Address, new PrivateKey().Address) }, + AgentAddresses = new[] { (new PrivateKey().Address, new PrivateKey().Address), }, Mead = 4, }, TransferAssets _ => new TransferAssets(_sender, new List<(Address, FungibleAssetValue)> @@ -476,7 +476,7 @@ private ActionBase GetAction(Type type) ), }, }, - RetrieveAvatarAssets _ => new RetrieveAvatarAssets(avatarAddress: new PrivateKey().Address), + RetrieveAvatarAssets _ => new RetrieveAvatarAssets(new PrivateKey().Address), MigrateFee _ => new MigrateFee { TransferData = new List<(Address sender, Address recipient, BigInteger amount)> diff --git a/.Lib9c.Tests/Action/ActivateCollectionTest.cs b/.Lib9c.Tests/Action/ActivateCollectionTest.cs index 4e711cb44a..54ce33e927 100644 --- a/.Lib9c.Tests/Action/ActivateCollectionTest.cs +++ b/.Lib9c.Tests/Action/ActivateCollectionTest.cs @@ -26,7 +26,8 @@ public ActivateCollectionTest() { var sheets = TableSheetsImporter.ImportSheets(); // Fix csv data for test - sheets[nameof(CollectionSheet)] = @"id,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value + sheets[nameof(CollectionSheet)] = + @"id,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value 1,10110000,1,0,,302000,2,,,200000,2,,,40100000,1,,,,,,,,,,,ATK,Add,1,,,,,, 2,10110000,1,0,,,,,,,,,,,,,,,,,,,,,,ATK,Percentage,1,,,,,,"; @@ -84,7 +85,7 @@ public void Execute() } else { - for (int i = 0; i < material.Count; i++) + for (var i = 0; i < material.Count; i++) { var item = ItemFactory.CreateItem(itemRow, random); var nonFungibleId = ((INonFungibleItem)item).NonFungibleId; @@ -120,7 +121,7 @@ public void Execute() PreviousState = state, Signer = _agentAddress, }; - ActivateCollection activateCollection = new ActivateCollection() + var activateCollection = new ActivateCollection() { AvatarAddress = _avatarAddress, CollectionData = diff --git a/.Lib9c.Tests/Action/AddRedeemCodeTest.cs b/.Lib9c.Tests/Action/AddRedeemCodeTest.cs index 7e04a39cdf..4487362445 100644 --- a/.Lib9c.Tests/Action/AddRedeemCodeTest.cs +++ b/.Lib9c.Tests/Action/AddRedeemCodeTest.cs @@ -24,7 +24,7 @@ public void CheckPermission() redeemCsv = "New Value", }; - PolicyExpiredException exc1 = Assert.Throws(() => + var exc1 = Assert.Throws(() => { action.Execute( new ActionContext @@ -37,7 +37,7 @@ public void CheckPermission() }); Assert.Equal(101, exc1.BlockIndex); - PermissionDeniedException exc2 = Assert.Throws(() => + var exc2 = Assert.Throws(() => { action.Execute( new ActionContext @@ -91,7 +91,7 @@ public void ExecuteThrowSheetRowValidateException() sheet.Set(csv); var state = new World(MockUtil.MockModernWorldState) - .SetLegacyState(Addresses.RedeemCode, new RedeemCodeState(sheet).Serialize()); + .SetLegacyState(Addresses.RedeemCode, new RedeemCodeState(sheet).Serialize()); var action = new AddRedeemCode { diff --git a/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs b/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs index 598b36b047..04ae818cb6 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs @@ -29,7 +29,7 @@ public class ClaimAdventureBossRewardTest private static readonly Dictionary Sheets = TableSheetsImporter.ImportSheets(); - private static readonly TableSheets TableSheets = new TableSheets(Sheets); + private static readonly TableSheets TableSheets = new (Sheets); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1419 private static readonly Currency NCG = Currency.Legacy("NCG", 2, null); @@ -47,7 +47,7 @@ public class ClaimAdventureBossRewardTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "wanted" + "wanted" ); private static readonly AgentState WantedState = new (WantedAddress) @@ -68,7 +68,7 @@ public class ClaimAdventureBossRewardTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "explorer" + "explorer" ); private static readonly AgentState ExplorerState = new (ExplorerAddress) @@ -92,7 +92,7 @@ public class ClaimAdventureBossRewardTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "Tester" + "Tester" ); private static readonly AgentState TesterState = new (TesterAddress) @@ -454,7 +454,7 @@ public void WantedMultipleSeason() NcgReward = 0 * NCG, // No Raffle Reward FavReward = new Dictionary { - { 10035, 84 }, // 100NCG * 1.2 * 0.7 Fixed / 1 NCG Ratio * 100% contribution for season 3 + { 10035, 84 }, // 100NCG * 1.2 * 0.7 Fixed / 1 NCG Ratio * 100% contribution for season 3 }, ItemReward = new Dictionary { @@ -699,9 +699,9 @@ FungibleAssetValue expectedRemainingNcg { var avatarState = resultState.GetAvatarState( TesterAvatarAddress, - getInventory: true, - getWorldInformation: false, - getQuestList: false + true, + false, + false ); Assert.IsType(avatarState.mailBox.First()); } diff --git a/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs b/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs index fcd117fa13..6508ade694 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs @@ -27,7 +27,7 @@ public class ExploreAdventureBossTest private static readonly Dictionary Sheets = TableSheetsImporter.ImportSheets(); - private static readonly TableSheets TableSheets = new TableSheets(Sheets); + private static readonly TableSheets TableSheets = new (Sheets); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1419 private static readonly Currency NCG = Currency.Legacy("NCG", 2, null); @@ -45,7 +45,7 @@ public class ExploreAdventureBossTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "wanted" + "wanted" ); private static readonly AgentState WantedState = new (WantedAddress) @@ -66,7 +66,7 @@ public class ExploreAdventureBossTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "Tester" + "Tester" ); private static readonly AgentState TesterState = new (TesterAddress) @@ -170,7 +170,7 @@ Type exc ); state = Stake(state, WantedAddress); - var sheets = state.GetSheets(sheetTypes: new[] + var sheets = state.GetSheets(new[] { typeof(MaterialItemSheet), typeof(RuneSheet), @@ -227,7 +227,7 @@ Type exc var expectedFavRewards = new List<(int, int)>(); var firstRewardSheet = TableSheets.AdventureBossFloorFirstRewardSheet; foreach (var row in firstRewardSheet.Values.Where(r => - r.FloorId > floor && r.FloorId <= expectedFloor)) + r.FloorId > floor && r.FloorId <= expectedFloor)) { foreach (var reward in row.Rewards) { diff --git a/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs b/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs index 93bf24913d..80b6f3e82d 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs @@ -43,7 +43,7 @@ public class SweepAdventureBossTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "wanted" + "wanted" ); private static readonly AgentState WantedState = new (WantedAddress) @@ -64,7 +64,7 @@ public class SweepAdventureBossTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "Tester" + "Tester" ); private static readonly AgentState TesterState = new (TesterAddress) @@ -131,7 +131,7 @@ public void Execute( } state = Stake(state, WantedAddress); - var sheets = state.GetSheets(sheetTypes: new[] + var sheets = state.GetSheets(new[] { typeof(MaterialItemSheet), }); diff --git a/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs b/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs index 80b2f201b1..675da8368a 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs @@ -41,7 +41,7 @@ public class UnlockFloorTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "wanted" + "wanted" ); private static readonly AgentState WantedState = new (WantedAddress) @@ -62,7 +62,7 @@ public class UnlockFloorTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "Tester" + "Tester" ); private static readonly AgentState TesterState = new (TesterAddress) diff --git a/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs b/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs index 60528d50c6..82a78d5e86 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs @@ -27,7 +27,7 @@ public class WantedTest private static readonly Dictionary Sheets = TableSheetsImporter.ImportSheets(); - private static readonly TableSheets TableSheets = new TableSheets(Sheets); + private static readonly TableSheets TableSheets = new (Sheets); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1419 private static readonly Currency NCG = Currency.Legacy("NCG", 2, null); @@ -41,7 +41,7 @@ public class WantedTest 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "avatar1" + "avatar1" ); private static readonly Address @@ -53,7 +53,7 @@ private static readonly Address 0L, TableSheets.GetAvatarSheets(), new PrivateKey().Address, - name: "avatar2" + "avatar2" ); private static readonly GoldCurrencyState GoldCurrencyState = new (NCG); @@ -405,7 +405,7 @@ public void InsufficientBalance() // Burn all balance to test state = state.BurnAsset( - new ActionContext { PreviousState = state }, + new ActionContext { PreviousState = state, }, AgentAddress, state.GetBalance(AgentAddress, NCG) ); @@ -485,8 +485,8 @@ public void WantedForMultipleSeasons() var currentStakeRegularRewardSheetAddr = Addresses.GetSheetAddress( state.GetSheet().StakeRegularRewardSheetValue); if (!state.TryGetSheet( - currentStakeRegularRewardSheetAddr, - out var stakeRegularRewardSheet)) + currentStakeRegularRewardSheetAddr, + out var stakeRegularRewardSheet)) { throw new StateNullException( ReservedAddresses.LegacyAccount, @@ -514,10 +514,10 @@ public void WantedForMultipleSeasons() } [Theory] - [InlineData(new int[] { 211000, 211001 }, new[] { 211002, 211003 })] - [InlineData(new int[] { 211002, 211003 }, new[] { 211000, 211001 })] - [InlineData(new int[] { 211000, 211002 }, new[] { 211001, 211003 })] - [InlineData(new int[] { 211001, 211003 }, new[] { 211000, 211002 })] + [InlineData(new int[] { 211000, 211001, }, new[] { 211002, 211003, })] + [InlineData(new int[] { 211002, 211003, }, new[] { 211000, 211001, })] + [InlineData(new int[] { 211000, 211002, }, new[] { 211001, 211003, })] + [InlineData(new int[] { 211001, 211003, }, new[] { 211000, 211002, })] public void PrevSeason(int[] prevBossId, int[] candidate) { var state = Stake(_initialState); @@ -526,7 +526,7 @@ public void PrevSeason(int[] prevBossId, int[] candidate) for (var i = 0; i < prevBossId.Length; i++) { var season = new SeasonInfo(i + 1, 10 * i, 10 * i + 10, 10 * i + 10) - { BossId = prevBossId[i] }; + { BossId = prevBossId[i], }; state = state.SetSeasonInfo(season); state = state.SetLatestAdventureBossSeason(season); } @@ -562,8 +562,8 @@ private IWorld Stake(IWorld world, long amount = 0) var currentStakeRegularRewardSheetAddr = Addresses.GetSheetAddress( world.GetSheet().StakeRegularRewardSheetValue); if (!world.TryGetSheet( - currentStakeRegularRewardSheetAddr, - out var stakeRegularRewardSheet)) + currentStakeRegularRewardSheetAddr, + out var stakeRegularRewardSheet)) { throw new StateNullException( ReservedAddresses.LegacyAccount, diff --git a/.Lib9c.Tests/Action/ApprovePledgeTest.cs b/.Lib9c.Tests/Action/ApprovePledgeTest.cs index a2b9179a29..e93d530af8 100644 --- a/.Lib9c.Tests/Action/ApprovePledgeTest.cs +++ b/.Lib9c.Tests/Action/ApprovePledgeTest.cs @@ -25,7 +25,7 @@ public void Execute(int mead) var address = new PrivateKey().Address; var patron = new PrivateKey().Address; var contractAddress = address.Derive(nameof(RequestPledge)); - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState( contractAddress, List.Empty.Add(patron.Serialize()).Add(false.Serialize()).Add(mead.Serialize()) @@ -57,7 +57,7 @@ public void Execute_JoinGuild(int mead) var patron = MeadConfig.PatronAddress; var contractAddress = address.Derive(nameof(RequestPledge)); var guildAddress = AddressUtil.CreateGuildAddress(); - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState( contractAddress, List.Empty.Add(patron.Serialize()).Add(false.Serialize()).Add(mead.Serialize()) @@ -103,7 +103,7 @@ public void Execute_Throw_Exception(bool invalidPatron, bool alreadyContract, Ty contract = List.Empty.Add(patron.Serialize()).Add(true.Serialize()); } - IWorld states = new World(MockUtil.MockModernWorldState).SetLegacyState(contractAddress, contract); + var states = new World(MockUtil.MockModernWorldState).SetLegacyState(contractAddress, contract); var action = new ApprovePledge { diff --git a/.Lib9c.Tests/Action/ArenahelperTest.cs b/.Lib9c.Tests/Action/ArenahelperTest.cs index c97dbd1313..e695449e0e 100644 --- a/.Lib9c.Tests/Action/ArenahelperTest.cs +++ b/.Lib9c.Tests/Action/ArenahelperTest.cs @@ -156,7 +156,7 @@ public void ExecuteGetTicketPrice() additionalTicketPrice = 40; } - var sum = ticketPrice + (additionalTicketPrice * arenaInformation.PurchasedTicketCount); + var sum = ticketPrice + additionalTicketPrice * arenaInformation.PurchasedTicketCount; var major = sum / 100; var miner = sum % 100; var expectedPrice = new FungibleAssetValue(_state.GetGoldCurrency(), major, miner); diff --git a/.Lib9c.Tests/Action/BattleArenaTest.cs b/.Lib9c.Tests/Action/BattleArenaTest.cs index 5f32742b15..48b4eaf0b9 100644 --- a/.Lib9c.Tests/Action/BattleArenaTest.cs +++ b/.Lib9c.Tests/Action/BattleArenaTest.cs @@ -871,11 +871,11 @@ public void Execute_CoolDownBlockException() public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2, int runeId2, Type exception) { long nextBlockIndex = 4; - int championshipId = 1; - int round = 1; - int ticket = 1; - int arenaInterval = 5; - int randomSeed = 3; + var championshipId = 1; + var round = 1; + var ticket = 1; + var arenaInterval = 5; + var randomSeed = 3; var context = new ActionContext(); var previousStates = _initialStates; @@ -944,8 +944,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 equipments = new List(), runeInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, }; @@ -1080,7 +1080,7 @@ public void Execute_ValidateDuplicateTicketPurchaseException() [InlineData(-1, typeof(ArgumentException))] public void PlainValue(int ticket, Type exc) { - BattleArena action = new BattleArena + var action = new BattleArena { myAvatarAddress = _avatar1Address, enemyAvatarAddress = _avatar2Address, @@ -1091,8 +1091,8 @@ public void PlainValue(int ticket, Type exc) equipments = new List(), runeInfos = new List(), }; - IValue plainValue = action.PlainValue; - BattleArena des = new BattleArena(); + var plainValue = action.PlainValue; + var des = new BattleArena(); if (exc is null) { des.LoadPlainValue(plainValue); @@ -1316,7 +1316,7 @@ private void Execute( } var materialCount = myAvatarStateNext.inventory.Materials.Count(); - var high = (ArenaHelper.GetRewardCount(beforeMyScore.Score) * ticket) + medalCount; + var high = ArenaHelper.GetRewardCount(beforeMyScore.Score) * ticket + medalCount; Assert.InRange(materialCount, 0, high); var myArenaAvatarStateAddr = ArenaAvatarState.DeriveAddress(myAvatarAddress); diff --git a/.Lib9c.Tests/Action/BurnAssetTest.cs b/.Lib9c.Tests/Action/BurnAssetTest.cs index 5d90e088b0..3e028313b8 100644 --- a/.Lib9c.Tests/Action/BurnAssetTest.cs +++ b/.Lib9c.Tests/Action/BurnAssetTest.cs @@ -122,14 +122,14 @@ public void LoadPlainValue_Throws_MemoLengthOverflowException() [Fact] public void Execute() { - IWorld prevState = _prevState; + var prevState = _prevState; var action = new BurnAsset( _signer, Currencies.Crystal * 42, "42" ); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, @@ -147,8 +147,8 @@ public void Execute() [Fact] public void Execute_With_AvatarAddress() { - IWorld prevState = _prevState; - Address avatarAddress = _signer.Derive( + var prevState = _prevState; + var avatarAddress = _signer.Derive( string.Format( CultureInfo.InvariantCulture, CreateAvatar.DeriveFormat, @@ -161,7 +161,7 @@ public void Execute_With_AvatarAddress() Currencies.DailyRewardRune * 10, "10" ); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, @@ -179,7 +179,7 @@ public void Execute_With_AvatarAddress() [Fact] public void Execute_Throws_InsufficientBalanceException() { - IWorld prevState = _prevState; + var prevState = _prevState; var action = new BurnAsset( _signer, @@ -202,7 +202,7 @@ public void Execute_Throws_InsufficientBalanceException() [Fact] public void Execute_Throws_InvalidActionFieldException() { - IWorld prevState = _prevState; + var prevState = _prevState; var action = new BurnAsset( default, // Wrong address diff --git a/.Lib9c.Tests/Action/BuyMultipleTest.cs b/.Lib9c.Tests/Action/BuyMultipleTest.cs index 93ab015891..4638dd5f66 100644 --- a/.Lib9c.Tests/Action/BuyMultipleTest.cs +++ b/.Lib9c.Tests/Action/BuyMultipleTest.cs @@ -282,9 +282,9 @@ public void Execute(params ShopItemData[] productDatas) { ++buyCount; var purchaseInfo = new BuyMultiple.PurchaseInfo( - shopItem.ProductId, - shopItem.SellerAgentAddress, - shopItem.SellerAvatarAddress); + shopItem.ProductId, + shopItem.SellerAgentAddress, + shopItem.SellerAvatarAddress); itemsToBuy.Add(purchaseInfo); } } @@ -307,7 +307,7 @@ public void Execute(params ShopItemData[] productDatas) .SetAvatarState(avatarState.address, avatarState); } - IWorld previousStates = _initialState; + var previousStates = _initialState; var buyerGold = previousStates.GetBalance(_buyerAgentAddress, goldCurrency); var priceSumData = productDatas @@ -375,8 +375,8 @@ public void ExecuteThrowInvalidAddressException() { var shopState = _initialState.GetShopState(); var costume = ItemFactory.CreateCostume( - _tableSheets.CostumeItemSheet.First, - Guid.NewGuid()); + _tableSheets.CostumeItemSheet.First, + Guid.NewGuid()); shopState.Register(new ShopItem( _buyerAgentAddress, _buyerAvatarAddress, @@ -559,7 +559,7 @@ public void ExecuteThrowShopItemExpiredError() var sellerAgentAddress = new PrivateKey().Address; var (avatarState, agentState) = CreateAvatarState(sellerAgentAddress, sellerAvatarAddress); - IWorld previousStates = _initialState; + var previousStates = _initialState; var shopState = previousStates.GetShopState(); var productId = Guid.NewGuid(); diff --git a/.Lib9c.Tests/Action/BuyProductTest.cs b/.Lib9c.Tests/Action/BuyProductTest.cs index 40d0b806a3..0233c55c64 100644 --- a/.Lib9c.Tests/Action/BuyProductTest.cs +++ b/.Lib9c.Tests/Action/BuyProductTest.cs @@ -24,13 +24,14 @@ namespace Lib9c.Tests.Action public class BuyProductTest { - private static readonly Address BuyerAgentAddress = new Address("47d082a115c63e7b58b1532d20e631538eafadde"); - private static readonly Address BuyerAvatarAddress = new Address("340f110b91d0577a9ae0ea69ce15269436f217da"); - private static readonly Address SellerAgentAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); - private static readonly Address SellerAvatarAddress = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"); + private static readonly Address BuyerAgentAddress = new ("47d082a115c63e7b58b1532d20e631538eafadde"); + private static readonly Address BuyerAvatarAddress = new ("340f110b91d0577a9ae0ea69ce15269436f217da"); + private static readonly Address SellerAgentAddress = new ("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); + private static readonly Address SellerAvatarAddress = new ("Fb90278C67f9b266eA309E6AE8463042f5461449"); private static readonly Guid ProductId = Guid.NewGuid(); private static readonly Currency Gold = Currency.Legacy("NCG", 2, null); - private static readonly TableSheets TableSheets = new TableSheets(TableSheetsImporter.ImportSheets()); + private static readonly TableSheets TableSheets = new (TableSheetsImporter.ImportSheets()); + private static readonly ITradableItem TradableItem = (ITradableItem)ItemFactory.CreateItemUsable(TableSheets.EquipmentItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Armor), Guid.NewGuid(), 1L); @@ -297,7 +298,7 @@ public void Execute_Throw_Exception(params ExecuteMember[] validateMembers) var action = new BuyProduct { AvatarAddress = BuyerAvatarAddress, - ProductInfos = new[] { productInfo }, + ProductInfos = new[] { productInfo, }, }; Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext { @@ -313,7 +314,7 @@ public void Execute_Throw_Exception(params ExecuteMember[] validateMembers) public void Execute_Throw_ArgumentOutOfRangeException() { var productInfos = new List(); - for (int i = 0; i < BuyProduct.Capacity + 1; i++) + for (var i = 0; i < BuyProduct.Capacity + 1; i++) { productInfos.Add(new ItemProductInfo()); } diff --git a/.Lib9c.Tests/Action/BuyTest.cs b/.Lib9c.Tests/Action/BuyTest.cs index 446209e98d..e4f686f4a7 100644 --- a/.Lib9c.Tests/Action/BuyTest.cs +++ b/.Lib9c.Tests/Action/BuyTest.cs @@ -219,19 +219,19 @@ public static IEnumerable GetReconfigureFungibleItemMemberData() [MemberData(nameof(GetExecuteMemberData))] public void Execute(params OrderData[] orderDataList) { - AvatarState buyerAvatarState = _initialState.GetAvatarState(_buyerAvatarAddress); - List purchaseInfos = new List(); - List productInfos = new List(); - ShopState legacyShopState = _initialState.GetShopState(); + var buyerAvatarState = _initialState.GetAvatarState(_buyerAvatarAddress); + var purchaseInfos = new List(); + var productInfos = new List(); + var legacyShopState = _initialState.GetShopState(); foreach (var orderData in orderDataList) { - (AvatarState sellerAvatarState, AgentState sellerAgentState) = CreateAvatarState( + (var sellerAvatarState, var sellerAgentState) = CreateAvatarState( orderData.SellerAgentAddress, orderData.SellerAvatarAddress ); ITradableItem tradableItem; - Guid orderId = orderData.OrderId; - Guid itemId = orderData.TradableId; + var orderId = orderData.OrderId; + var itemId = orderData.TradableId; ItemSubType itemSubType; if (orderData.ItemType == ItemType.Equipment) { @@ -269,7 +269,7 @@ public void Execute(params OrderData[] orderDataList) buyerAvatarState.Update(mail); } - Address shardedShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); + var shardedShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); var shopState = _initialState.GetLegacyState(shardedShopAddress) is null ? new ShardedShopStateV2(shardedShopAddress) : new ShardedShopStateV2((Dictionary)_initialState.GetLegacyState(shardedShopAddress)); @@ -364,39 +364,39 @@ public void Execute(params OrderData[] orderDataList) Assert.Empty(buyAction.errors); - foreach (var nextState in new[] { expectedState, actualState }) + foreach (var nextState in new[] { expectedState, actualState, }) { - FungibleAssetValue totalTax = 0 * _goldCurrencyState.Currency; - FungibleAssetValue totalPrice = 0 * _goldCurrencyState.Currency; - Currency goldCurrencyState = nextState.GetGoldCurrency(); - AvatarState nextBuyerAvatarState = nextState.GetAvatarState(_buyerAvatarAddress); + var totalTax = 0 * _goldCurrencyState.Currency; + var totalPrice = 0 * _goldCurrencyState.Currency; + var goldCurrencyState = nextState.GetGoldCurrency(); + var nextBuyerAvatarState = nextState.GetAvatarState(_buyerAvatarAddress); foreach (var purchaseInfo in purchaseInfos) { - Address shardedShopAddress = + var shardedShopAddress = ShardedShopStateV2.DeriveAddress(purchaseInfo.ItemSubType, purchaseInfo.OrderId); var nextShopState = new ShardedShopStateV2((Dictionary)nextState.GetLegacyState(shardedShopAddress)); Assert.DoesNotContain(nextShopState.OrderDigestList, o => o.OrderId.Equals(purchaseInfo.OrderId)); - Order order = + var order = OrderFactory.Deserialize( (Dictionary)nextState.GetLegacyState(Order.DeriveAddress(purchaseInfo.OrderId))); - FungibleAssetValue tax = order.GetTax(); - FungibleAssetValue taxedPrice = order.Price - tax; + var tax = order.GetTax(); + var taxedPrice = order.Price - tax; totalTax += tax; totalPrice += order.Price; - int itemCount = order is FungibleOrder fungibleOrder ? fungibleOrder.ItemCount : 1; + var itemCount = order is FungibleOrder fungibleOrder ? fungibleOrder.ItemCount : 1; Assert.True( nextBuyerAvatarState.inventory.TryGetTradableItems( purchaseInfo.TradableId, 100, itemCount, - out List inventoryItems) + out var inventoryItems) ); Assert.Single(inventoryItems); - Inventory.Item inventoryItem = inventoryItems.First(); - ITradableItem tradableItem = (ITradableItem)inventoryItem.item; + var inventoryItem = inventoryItems.First(); + var tradableItem = (ITradableItem)inventoryItem.item; Assert.Equal(100, tradableItem.RequiredBlockIndex); - int expectedCount = tradableItem is TradableMaterial + var expectedCount = tradableItem is TradableMaterial ? orderDataList.Sum(i => i.ItemCount) : itemCount; Assert.Equal(expectedCount, inventoryItem.count); @@ -421,7 +421,7 @@ public void Execute(params OrderData[] orderDataList) .Single(i => i.OrderId.Equals(order.OrderId)); Assert.Equal(order.OrderId, buyerMail.OrderId); - FungibleAssetValue sellerGold = + var sellerGold = nextState.GetBalance(purchaseInfo.SellerAgentAddress, goldCurrencyState); Assert.Equal(taxedPrice, sellerGold); @@ -455,7 +455,7 @@ public void Execute(params OrderData[] orderDataList) [InlineData(true, false, typeof(NotEnoughClearedStageLevelException))] public void Execute_Throw_Exception(bool equalAvatarAddress, bool clearStage, Type exc) { - PurchaseInfo purchaseInfo = new PurchaseInfo( + var purchaseInfo = new PurchaseInfo( default, default, _buyerAgentAddress, @@ -481,7 +481,7 @@ public void Execute_Throw_Exception(bool equalAvatarAddress, bool clearStage, Ty var action = new Buy { buyerAvatarAddress = avatarAddress, - purchaseInfos = new[] { purchaseInfo }, + purchaseInfos = new[] { purchaseInfo, }, }; Assert.Throws(exc, () => action.Execute(new ActionContext() @@ -587,7 +587,7 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) _initialState = _initialState.BurnAsset(context, _buyerAgentAddress, balance); } - PurchaseInfo purchaseInfo = new PurchaseInfo( + var purchaseInfo = new PurchaseInfo( _orderId, tradableId, sellerAgentAddress, @@ -611,10 +611,10 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) var action = new Buy { buyerAvatarAddress = _buyerAvatarAddress, - purchaseInfos = new[] { purchaseInfo }, + purchaseInfos = new[] { purchaseInfo, }, }; - IWorld nextState = action.Execute(new ActionContext() + var nextState = action.Execute(new ActionContext() { BlockIndex = blockIndex, PreviousState = _initialState, @@ -630,10 +630,10 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) var buyProductAction = new BuyProduct { AvatarAddress = _buyerAvatarAddress, - ProductInfos = new[] { productInfo }, + ProductInfos = new[] { productInfo, }, }; - Type exc = errorCodeMember.ErrorCode switch + var exc = errorCodeMember.ErrorCode switch { Buy.ErrorCodeFailedLoadingState => typeof(FailedLoadStateException), Buy.ErrorCodeShopItemExpired => typeof(ShopItemExpiredException), @@ -656,7 +656,7 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) Signer = _buyerAgentAddress, })); - foreach (var address in new[] { agentAddress, sellerAgentAddress, GoldCurrencyState.Address }) + foreach (var address in new[] { agentAddress, sellerAgentAddress, GoldCurrencyState.Address, }) { Assert.Equal( _initialState.GetBalance(address, _goldCurrencyState.Currency), @@ -699,7 +699,7 @@ public void Execute_ReconfigureFungibleItem(params OrderData[] orderDataList) buyerAvatarState.Update(mail); } - Address shardedShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); + var shardedShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, orderId); var shopState = _initialState.GetLegacyState(shardedShopAddress) is null ? new ShardedShopStateV2(shardedShopAddress) : new ShardedShopStateV2((Dictionary)_initialState.GetLegacyState(shardedShopAddress)); @@ -718,7 +718,7 @@ public void Execute_ReconfigureFungibleItem(params OrderData[] orderDataList) var sellItem = order.Sell3(sellerAvatarState); var orderDigest = order.Digest(sellerAvatarState, _tableSheets.CostumeStatSheet); - Address digestListAddress = OrderDigestListState.DeriveAddress(firstData.SellerAvatarAddress); + var digestListAddress = OrderDigestListState.DeriveAddress(firstData.SellerAvatarAddress); var digestListState = new OrderDigestListState(OrderDigestListState.DeriveAddress(firstData.SellerAvatarAddress)); if (_initialState.TryGetLegacyState(digestListAddress, out Dictionary rawDigestList)) { @@ -775,34 +775,34 @@ public void Execute_ReconfigureFungibleItem(params OrderData[] orderDataList) Signer = _buyerAgentAddress, }); - AvatarState nextBuyerAvatarState = nextState.GetAvatarState(_buyerAvatarAddress); + var nextBuyerAvatarState = nextState.GetAvatarState(_buyerAvatarAddress); Assert.Empty(buyAction.errors); foreach (var purchaseInfo in purchaseInfos) { - Address shardedShopAddress = + var shardedShopAddress = ShardedShopStateV2.DeriveAddress(purchaseInfo.ItemSubType, purchaseInfo.OrderId); var nextShopState = new ShardedShopStateV2((Dictionary)nextState.GetLegacyState(shardedShopAddress)); Assert.DoesNotContain(nextShopState.OrderDigestList, o => o.OrderId.Equals(purchaseInfo.OrderId)); - Order order = + var order = OrderFactory.Deserialize( (Dictionary)nextState.GetLegacyState(Order.DeriveAddress(purchaseInfo.OrderId))); - FungibleAssetValue tax = order.GetTax(); + var tax = order.GetTax(); - int itemCount = order is FungibleOrder fungibleOrder ? fungibleOrder.ItemCount : 1; + var itemCount = order is FungibleOrder fungibleOrder ? fungibleOrder.ItemCount : 1; Assert.True( nextBuyerAvatarState.inventory.TryGetTradableItems( purchaseInfo.TradableId, 100, itemCount, - out List inventoryItems) + out var inventoryItems) ); Assert.Single(inventoryItems); - Inventory.Item inventoryItem = inventoryItems.First(); - ITradableItem tradableItem = (ITradableItem)inventoryItem.item; + var inventoryItem = inventoryItems.First(); + var tradableItem = (ITradableItem)inventoryItem.item; Assert.Equal(100, tradableItem.RequiredBlockIndex); - int expectedCount = tradableItem is TradableMaterial + var expectedCount = tradableItem is TradableMaterial ? orderDataList.Sum(i => i.ItemCount) : itemCount; Assert.Equal(expectedCount, inventoryItem.count); @@ -898,7 +898,7 @@ public void Execute_With_Testbed() Assert.DoesNotContain(nextShopState.OrderDigestList, o => o.OrderId.Equals(purchaseInfo.OrderId)); var order = OrderFactory.Deserialize( - (Dictionary)nextState.GetLegacyState(Order.DeriveAddress(purchaseInfo.OrderId))); + (Dictionary)nextState.GetLegacyState(Order.DeriveAddress(purchaseInfo.OrderId))); var tradableId = purchaseInfo.TradableId; var itemCount = order is FungibleOrder fungibleOrder ? fungibleOrder.ItemCount : 1; var nextSellerAvatarState = @@ -1033,130 +1033,133 @@ public class ErrorCodeMember } #pragma warning disable SA1201 - public static IEnumerable ErrorCodeMemberData() => new List + public static IEnumerable ErrorCodeMemberData() { - new object[] + return new List { - new ErrorCodeMember() + new object[] { - EqualSigner = true, - ErrorCode = Buy.ErrorCodeInvalidAddress, + new ErrorCodeMember() + { + EqualSigner = true, + ErrorCode = Buy.ErrorCodeInvalidAddress, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ErrorCode = Buy.ErrorCodeFailedLoadingState, + new ErrorCodeMember() + { + BuyerExist = true, + ErrorCode = Buy.ErrorCodeFailedLoadingState, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - ErrorCode = Buy.ErrorCodeInvalidOrderId, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + ErrorCode = Buy.ErrorCodeInvalidOrderId, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - ErrorCode = Buy.ErrorCodeInvalidOrderId, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + ErrorCode = Buy.ErrorCodeInvalidOrderId, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - ErrorCode = Buy.ErrorCodeFailedLoadingState, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + ErrorCode = Buy.ErrorCodeFailedLoadingState, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - EqualSellerAgent = true, - EqualSellerAvatar = true, - ErrorCode = Buy.ErrorCodeInvalidTradableId, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + EqualSellerAgent = true, + EqualSellerAvatar = true, + ErrorCode = Buy.ErrorCodeInvalidTradableId, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - EqualSellerAgent = true, - EqualSellerAvatar = true, - EqualTradableId = true, - ErrorCode = Buy.ErrorCodeInvalidPrice, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + EqualSellerAgent = true, + EqualSellerAvatar = true, + EqualTradableId = true, + ErrorCode = Buy.ErrorCodeInvalidPrice, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - EqualSellerAgent = true, - EqualSellerAvatar = true, - EqualTradableId = true, - EqualPrice = true, - Expire = true, - ErrorCode = Buy.ErrorCodeShopItemExpired, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + EqualSellerAgent = true, + EqualSellerAvatar = true, + EqualTradableId = true, + EqualPrice = true, + Expire = true, + ErrorCode = Buy.ErrorCodeShopItemExpired, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - EqualSellerAgent = true, - EqualSellerAvatar = true, - EqualTradableId = true, - EqualPrice = true, - NotEnoughBalance = true, - ErrorCode = Buy.ErrorCodeInsufficientBalance, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + EqualSellerAgent = true, + EqualSellerAvatar = true, + EqualTradableId = true, + EqualPrice = true, + NotEnoughBalance = true, + ErrorCode = Buy.ErrorCodeInsufficientBalance, + }, }, - }, - new object[] - { - new ErrorCodeMember() + new object[] { - BuyerExist = true, - ShopStateExist = true, - OrderExist = true, - DigestExist = true, - EqualSellerAgent = true, - EqualSellerAvatar = true, - EqualTradableId = true, - EqualPrice = true, - Duplicate = true, - ErrorCode = Buy.ErrorCodeDuplicateSell, + new ErrorCodeMember() + { + BuyerExist = true, + ShopStateExist = true, + OrderExist = true, + DigestExist = true, + EqualSellerAgent = true, + EqualSellerAvatar = true, + EqualTradableId = true, + EqualPrice = true, + Duplicate = true, + ErrorCode = Buy.ErrorCodeDuplicateSell, + }, }, - }, - }; + }; + } #pragma warning restore SA1201 } } diff --git a/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs b/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs index 69451e28c4..3bccfb3319 100644 --- a/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs +++ b/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs @@ -199,7 +199,7 @@ public void Execute_Throw_ProductNotFoundException() public void Execute_Throw_ArgumentOutOfRangeException() { var productInfos = new List(); - for (int i = 0; i < CancelProductRegistration.Capacity + 1; i++) + for (var i = 0; i < CancelProductRegistration.Capacity + 1; i++) { productInfos.Add(new ItemProductInfo()); } @@ -239,7 +239,7 @@ public void Mail_Serialize_BackwardCompatibility(ProductType productType) case ProductType.Fungible: case ProductType.NonFungible: { - ITradableItem tradableItem = productType == ProductType.Fungible + var tradableItem = productType == ProductType.Fungible ? ItemFactory.CreateTradableMaterial(_tableSheets.MaterialItemSheet.First) : (ITradableItem)ItemFactory.CreateItemUsable(_tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 0L); product = new ItemProduct diff --git a/.Lib9c.Tests/Action/ChargeActionPointTest.cs b/.Lib9c.Tests/Action/ChargeActionPointTest.cs index 82fcd1e7e1..3979247a9e 100644 --- a/.Lib9c.Tests/Action/ChargeActionPointTest.cs +++ b/.Lib9c.Tests/Action/ChargeActionPointTest.cs @@ -98,7 +98,7 @@ public void Execute(bool useTradable) } [Theory] - [InlineData(false, false, false, false, typeof(FailedLoadStateException))] + [InlineData(false, false, false, false, typeof(FailedLoadStateException))] [InlineData(true, false, false, false, typeof(NotEnoughMaterialException))] [InlineData(true, true, false, false, typeof(NotEnoughMaterialException))] [InlineData(true, false, true, true, typeof(ActionPointExceededException))] diff --git a/.Lib9c.Tests/Action/ClaimItemsTest.cs b/.Lib9c.Tests/Action/ClaimItemsTest.cs index b6d24032e5..9c7bf221f6 100644 --- a/.Lib9c.Tests/Action/ClaimItemsTest.cs +++ b/.Lib9c.Tests/Action/ClaimItemsTest.cs @@ -50,7 +50,7 @@ public ClaimItemsTest(ITestOutputHelper outputHelper) _itemIds = _tableSheets.CostumeItemSheet.Values.Take(3).Select(x => x.Id).ToList(); _itemCurrencies = _itemIds.Select(id => Currencies.GetItemCurrency(id, true)).ToList(); _wrappedFavCurrencies = new List(); - foreach (var currency in new[] { Currencies.Crystal, Currencies.StakeRune }) + foreach (var currency in new[] { Currencies.Crystal, Currencies.StakeRune, }) { var wrappedCurrency = Currencies.GetWrappedCurrency(currency); _wrappedFavCurrencies.Add(wrappedCurrency); @@ -78,18 +78,18 @@ public void Serialize(bool memoExist) { var states = GenerateAvatar(_initialState, out var avatarAddress1, out _); GenerateAvatar(states, out var avatarAddress2, out _); - string memo = memoExist ? "memo" : null; + var memo = memoExist ? "memo" : null; var action = new ClaimItems( new List<(Address, IReadOnlyList)> { - (avatarAddress1, new List { _itemCurrencies[0] * 1, _itemCurrencies[1] * 1 }), - (avatarAddress2, new List { _itemCurrencies[0] * 1 }), + (avatarAddress1, new List { _itemCurrencies[0] * 1, _itemCurrencies[1] * 1, }), + (avatarAddress2, new List { _itemCurrencies[0] * 1, }), }, memo ); Assert.Equal(!memoExist, string.IsNullOrEmpty(action.Memo)); - Dictionary serialized = (Dictionary)action.PlainValue; - Dictionary values = (Dictionary)serialized["values"]; + var serialized = (Dictionary)action.PlainValue; + var values = (Dictionary)serialized["values"]; Assert.Equal(memoExist, values.ContainsKey("m")); var deserialized = new ClaimItems(); deserialized.LoadPlainValue(action.PlainValue); @@ -112,7 +112,7 @@ public void Execute_Throws_ArgumentException_TickerInvalid() var currency = Currencies.Crystal; var action = new ClaimItems(new List<(Address, IReadOnlyList)> { - (recipientAvatarAddress, new List { currency * 1 }), + (recipientAvatarAddress, new List { currency * 1, }), }); Assert.Throws(() => action.Execute(new ActionContext @@ -132,7 +132,7 @@ public void Execute_Throws_WhenNotEnoughBalance() var currency = _itemCurrencies.First(); var action = new ClaimItems(new List<(Address, IReadOnlyList)> { - (recipientAvatarAddress, new List { currency * 6 }), + (recipientAvatarAddress, new List { currency * 6, }), }); Assert.Throws(() => action.Execute(new ActionContext @@ -210,7 +210,7 @@ public void Execute(string memo) Assert.Equal(1, mailItems.count); } - for (int i = 0; i < _wrappedFavCurrencies.Count; i++) + for (var i = 0; i < _wrappedFavCurrencies.Count; i++) { var wrappedCurrency = _wrappedFavCurrencies[i]; Assert.Equal(wrappedCurrency * 4, states.GetBalance(_signerAddress, wrappedCurrency)); @@ -219,7 +219,7 @@ public void Execute(string memo) currency, recipientAgentAddress, recipientAvatarAddress - ); + ); Assert.Equal(currency * 1, states.GetBalance(recipientAddress, currency)); var mailFav = mail.FungibleAssetValues.Single(f => f.Currency.Equals(currency)); Assert.Equal(currency * 1, mailFav); diff --git a/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs b/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs index 05c361f678..6a81399e64 100644 --- a/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs @@ -45,7 +45,7 @@ public ClaimRaidRewardTest() public void Execute(Type exc, int rank, int latestRank) { Address agentAddress = default; - Address avatarAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; var bossRow = _tableSheets.WorldBossListSheet.OrderedList.First(); var raiderAddress = Addresses.GetRaiderAddress(avatarAddress, bossRow.Id); var highScore = 0; @@ -115,8 +115,8 @@ public void Execute(Type exc, int rank, int latestRank) var rune = 0; var runeIds = _tableSheets.RuneWeightSheet.Values - .Where(r => r.BossId == bossRow.BossId) - .SelectMany(r => r.RuneInfos.Select(i => i.RuneId)).ToHashSet(); + .Where(r => r.BossId == bossRow.BossId) + .SelectMany(r => r.RuneInfos.Select(i => i.RuneId)).ToHashSet(); foreach (var runeId in runeIds) { var runeCurrency = RuneHelper.ToCurrency(_tableSheets.RuneSheet[runeId]); diff --git a/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs b/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs index 82ae98e4eb..dfe841117e 100644 --- a/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs @@ -24,7 +24,7 @@ public class ClaimStakeRewardTest { private const string AgentAddressHex = "0x0000000001000000000100000000010000000001"; private const int AvatarIndex = 0; - private static readonly Address AgentAddr = new Address(AgentAddressHex); + private static readonly Address AgentAddr = new (AgentAddressHex); private static readonly Address AvatarAddr = Addresses.GetAvatarAddress(AgentAddr, AvatarIndex); diff --git a/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs b/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs index c9be706d1c..d1fff158a5 100644 --- a/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs @@ -25,8 +25,8 @@ public void Execute(long blockIndex, Type exc) { var sheets = TableSheetsImporter.ImportSheets(); var tableSheets = new TableSheets(sheets); - Address agentAddress = new PrivateKey().Address; - Address avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; IWorld state = new World(MockUtil.MockModernWorldState); var runeWeightSheet = new RuneWeightSheet(); diff --git a/.Lib9c.Tests/Action/CombinationConsumableTest.cs b/.Lib9c.Tests/Action/CombinationConsumableTest.cs index 06cc4bf9d2..f9a85c961e 100644 --- a/.Lib9c.Tests/Action/CombinationConsumableTest.cs +++ b/.Lib9c.Tests/Action/CombinationConsumableTest.cs @@ -94,7 +94,7 @@ public void Execute() _tableSheets.WorldSheet, GameConfig.RequireClearedStageLevel.CombinationConsumableAction); - IWorld previousState = _initialState.SetAvatarState(_avatarAddress, avatarState); + var previousState = _initialState.SetAvatarState(_avatarAddress, avatarState); var action = new CombinationConsumable { diff --git a/.Lib9c.Tests/Action/CombinationEquipmentTest.cs b/.Lib9c.Tests/Action/CombinationEquipmentTest.cs index b46ec22dc8..7dab7b969e 100644 --- a/.Lib9c.Tests/Action/CombinationEquipmentTest.cs +++ b/.Lib9c.Tests/Action/CombinationEquipmentTest.cs @@ -137,13 +137,13 @@ bool previousCostStateExist ) { var context = new ActionContext(); - IWorld state = _initialState; + var state = _initialState; if (unlockIdsExist) { var unlockIds = List.Empty.Add(1.Serialize()); if (crystalUnlock) { - for (int i = 2; i < recipeId + 1; i++) + for (var i = 2; i < recipeId + 1; i++) { unlockIds = unlockIds.Add(i.Serialize()); } @@ -207,7 +207,7 @@ bool previousCostStateExist } } - int expectedCrystal = 0; + var expectedCrystal = 0; if (payByCrystal) { var crystalBalance = 0; @@ -353,9 +353,9 @@ public void ExecuteWithCheckingHammerPointState( int recipeId) { var context = new ActionContext(); - IWorld state = _initialState; + var state = _initialState; var unlockIds = List.Empty.Add(1.Serialize()); - for (int i = 2; i < recipeId + 1; i++) + for (var i = 2; i < recipeId + 1; i++) { unlockIds = unlockIds.Add(i.Serialize()); } @@ -404,7 +404,7 @@ public void ExecuteWithCheckingHammerPointState( if (exc is null) { var costCrystal = CrystalCalculator.CRYSTAL * - hammerPointSheet[recipeId].CRYSTAL; + hammerPointSheet[recipeId].CRYSTAL; state = state.MintAsset( context, _agentAddress, diff --git a/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs b/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs index 6a376939e7..ab96945f3d 100644 --- a/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs +++ b/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs @@ -7,32 +7,29 @@ namespace Lib9c.Tests.Action.Coupons public static class CouponsFixture { - public static Address AgentAddress1 { get; } = - new Address("0000000000000000000000000000000000000000"); + public static Address AgentAddress1 { get; } = new ("0000000000000000000000000000000000000000"); - public static Address AgentAddress2 { get; } = - new Address("0000000000000000000000000000000000000001"); + public static Address AgentAddress2 { get; } = new ("0000000000000000000000000000000000000001"); - public static Address AgentAddress3 { get; } = - new Address("0000000000000000000000000000000000000002"); + public static Address AgentAddress3 { get; } = new ("0000000000000000000000000000000000000002"); public static RewardSet RewardSet1 { get; } = - new RewardSet(ImmutableDictionary.Empty + new (ImmutableDictionary.Empty .Add(302001, 1)); public static RewardSet RewardSet2 { get; } = - new RewardSet(ImmutableDictionary.Empty + new (ImmutableDictionary.Empty .Add(302001, 1) .Add(302002, 2)); public static RewardSet RewardSet3 { get; } = - new RewardSet(ImmutableDictionary.Empty + new (ImmutableDictionary.Empty .Add(302002, 2)); - public static Guid Guid1 { get; } = new Guid("9CB96C65-3D47-4BAD-8BE6-18D97042B6C9"); + public static Guid Guid1 { get; } = new ("9CB96C65-3D47-4BAD-8BE6-18D97042B6C9"); - public static Guid Guid2 { get; } = new Guid("85BECFD9-7F5A-4C14-A2E7-C6EA83A23758"); + public static Guid Guid2 { get; } = new ("85BECFD9-7F5A-4C14-A2E7-C6EA83A23758"); - public static Guid Guid3 { get; } = new Guid("BC911842-11E3-48EB-BFFC-3719465718A5"); + public static Guid Guid3 { get; } = new ("BC911842-11E3-48EB-BFFC-3719465718A5"); } } diff --git a/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs b/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs index 77999b3573..971be47f51 100644 --- a/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs +++ b/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs @@ -20,7 +20,7 @@ public class IssueCouponsTest [Fact] public void Execute() { - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState( AdminState.Address, new AdminState(CouponsFixture.AgentAddress1, 1) @@ -56,8 +56,8 @@ public void Execute() Assert.Equal( ImmutableDictionary.Empty, new IssueCoupons( - ImmutableDictionary.Empty, - CouponsFixture.AgentAddress1) + ImmutableDictionary.Empty, + CouponsFixture.AgentAddress1) .Execute( new ActionContext { @@ -156,19 +156,19 @@ public void LoadPlainValue() Dictionary.Empty .Add("type_id", "issue_coupons") .Add("values", new Bencodex.Types.Dictionary( - ImmutableDictionary.Empty - .Add("recipient", new Binary(CouponsFixture.AgentAddress1.ByteArray)) - .Add( - "rewards", - Bencodex.Types.List.Empty - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) - .Add("quantity", 2)) - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) - .Add("quantity", 1))) - .Select(kv => new KeyValuePair((Text)kv.Key, kv.Value))) - .SetItem("id", new Guid("6E69DC55-A0D0-435A-A787-C62356CBE517").Serialize()))); + ImmutableDictionary.Empty + .Add("recipient", new Binary(CouponsFixture.AgentAddress1.ByteArray)) + .Add( + "rewards", + Bencodex.Types.List.Empty + .Add(Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) + .Add("quantity", 2)) + .Add(Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) + .Add("quantity", 1))) + .Select(kv => new KeyValuePair((Text)kv.Key, kv.Value))) + .SetItem("id", new Guid("6E69DC55-A0D0-435A-A787-C62356CBE517").Serialize()))); Assert.Equal(expected.Rewards, actual.Rewards); Assert.Equal(expected.Recipient, actual.Recipient); diff --git a/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs b/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs index 21261a98da..bb5d2fc6b4 100644 --- a/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs +++ b/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs @@ -22,7 +22,7 @@ public void Execute() { IRandom random = new TestRandom(); var sheets = TableSheetsImporter.ImportSheets(); - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState( Addresses.GameConfig, new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize() @@ -44,38 +44,38 @@ public void Execute() .Derive("avatar-states-0"); var agent1Avatar0State = CreateAvatar.CreateAvatarState( - "agent1avatar0", - agent1Avatar0Address, - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - BlockIndex = 0, - }, - state.GetSheet(), - default); + "agent1avatar0", + agent1Avatar0Address, + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + BlockIndex = 0, + }, + state.GetSheet(), + default); var agent1Avatar1State = CreateAvatar.CreateAvatarState( - "agent1avatar1", - agent1Avatar1Address, - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - BlockIndex = 0, - }, - state.GetSheet(), - default); + "agent1avatar1", + agent1Avatar1Address, + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + BlockIndex = 0, + }, + state.GetSheet(), + default); var agent2Avatar0State = CreateAvatar.CreateAvatarState( - "agent2avatar0", - agent2Avatar0Address, - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress2, - BlockIndex = 0, - }, - state.GetSheet(), - default); + "agent2avatar0", + agent2Avatar0Address, + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress2, + BlockIndex = 0, + }, + state.GetSheet(), + default); state = state .SetAvatarState(agent1Avatar0Address, agent1Avatar0State) @@ -86,15 +86,15 @@ public void Execute() Assert.Equal( state, new RedeemCoupon( - new Guid("AEB63B38-1850-4003-B549-19D37B37AC89"), - agent1Avatar0Address) + new Guid("AEB63B38-1850-4003-B549-19D37B37AC89"), + agent1Avatar0Address) .Execute( - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - RandomSeed = random.Seed, - })); + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + RandomSeed = random.Seed, + })); var agent1CouponWallet = state.GetCouponWallet(CouponsFixture.AgentAddress1); var agent2CouponWallet = state.GetCouponWallet(CouponsFixture.AgentAddress2); diff --git a/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs b/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs index 7986ce2f52..d851fa2f14 100644 --- a/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs +++ b/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs @@ -225,22 +225,22 @@ public void LoadPlainValue() actual.LoadPlainValue(Dictionary.Empty .Add("type_id", "transfer_coupons") .Add("values", new Bencodex.Types.Dictionary( - ImmutableDictionary.Empty - .Add( - "couponsPerRecipient", - Bencodex.Types.Dictionary.Empty - .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress1.ByteArray, - Bencodex.Types.List.Empty - .Add(CouponsFixture.Guid1.ToByteArray())) - .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress2.ByteArray, - Bencodex.Types.List.Empty - .Add(CouponsFixture.Guid2.ToByteArray()) - .Add(CouponsFixture.Guid3.ToByteArray())) - .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress3.ByteArray, - Bencodex.Types.List.Empty))) + ImmutableDictionary.Empty + .Add( + "couponsPerRecipient", + Bencodex.Types.Dictionary.Empty + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress1.ByteArray, + Bencodex.Types.List.Empty + .Add(CouponsFixture.Guid1.ToByteArray())) + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress2.ByteArray, + Bencodex.Types.List.Empty + .Add(CouponsFixture.Guid2.ToByteArray()) + .Add(CouponsFixture.Guid3.ToByteArray())) + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress3.ByteArray, + Bencodex.Types.List.Empty))) .SetItem("id", new Guid("AE3FA099-B97C-480F-9E3A-4E1FEF1EA783").Serialize()))); Assert.Equal(expected.CouponsPerRecipient, actual.CouponsPerRecipient); } diff --git a/.Lib9c.Tests/Action/CreatePendingActivationTest.cs b/.Lib9c.Tests/Action/CreatePendingActivationTest.cs index 9478aa2f28..4bb7cec032 100644 --- a/.Lib9c.Tests/Action/CreatePendingActivationTest.cs +++ b/.Lib9c.Tests/Action/CreatePendingActivationTest.cs @@ -14,7 +14,7 @@ public class CreatePendingActivationTest [Fact] public void Execute() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); @@ -41,7 +41,7 @@ public void Execute() [Fact] public void CheckPermission() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); diff --git a/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs b/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs index efd37f9663..373441032a 100644 --- a/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs +++ b/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs @@ -17,14 +17,15 @@ public void Execute() { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); + PendingActivationState CreatePendingActivation() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var pubKey = new PrivateKey().PublicKey; return new PendingActivationState(nonce, pubKey); } - PendingActivationState[] activations = + var activations = Enumerable.Range(0, 5000).Select(_ => CreatePendingActivation()).ToArray(); var action = new CreatePendingActivations(activations); var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); @@ -40,7 +41,7 @@ PendingActivationState CreatePendingActivation() var nextState = action.Execute(actionContext); - foreach (PendingActivationState pa in activations) + foreach (var pa in activations) { Assert.Equal( pa.Serialize(), @@ -52,9 +53,9 @@ PendingActivationState CreatePendingActivation() [Fact] public void PlainValue() { - byte[] nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; - PublicKey pubKey = new PrivateKey().PublicKey; - Address address = PendingActivationState.DeriveAddress(nonce, pubKey); + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; + var pubKey = new PrivateKey().PublicKey; + var address = PendingActivationState.DeriveAddress(nonce, pubKey); var plainValue = Dictionary.Empty .Add("type_id", "create_pending_activations") .Add("values", new List() diff --git a/.Lib9c.Tests/Action/CreatePledgeTest.cs b/.Lib9c.Tests/Action/CreatePledgeTest.cs index 9799227cf9..0b8ce7a119 100644 --- a/.Lib9c.Tests/Action/CreatePledgeTest.cs +++ b/.Lib9c.Tests/Action/CreatePledgeTest.cs @@ -36,7 +36,7 @@ public void Execute(bool admin, Type exc) var agentAddress = new PrivateKey().Address; var pledgeAddress = agentAddress.GetPledgeAddress(); var context = new ActionContext(); - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState(Addresses.Admin, adminState.Serialize()) .MintAsset(context, patronAddress, 4 * 500 * mead); @@ -44,7 +44,7 @@ public void Execute(bool admin, Type exc) { (agentAddress, pledgeAddress), }; - for (int i = 0; i < 499; i++) + for (var i = 0; i < 499; i++) { var address = new PrivateKey().Address; agentAddresses.Add((address, address.GetPledgeAddress())); @@ -57,7 +57,7 @@ public void Execute(bool admin, Type exc) AgentAddresses = agentAddresses, }; - Address singer = admin ? adminAddress : poolAddress; + var singer = admin ? adminAddress : poolAddress; var actionContext = new ActionContext { Signer = singer, diff --git a/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs b/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs index 8fd4946db1..8a9ad03710 100644 --- a/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs +++ b/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs @@ -364,7 +364,7 @@ public void Execute( state = state.SetRelationship(_avatarAddress, initialRelationship); var gameConfig = state.GetGameConfigState(); - var materialList = new List { ScrollItemId, CircleItemId }; + var materialList = new List { ScrollItemId, CircleItemId, }; if (enoughMaterials) { var relationshipSheet = _tableSheets.CustomEquipmentCraftRelationshipSheet; @@ -388,8 +388,8 @@ public void Execute( var circleRow = materialSheet[CircleItemId]; var circle = ItemFactory.CreateMaterial(circleRow); var circleAmount = (decimal)recipeRow.CircleAmount - * relationshipRow.CostMultiplier - / 10000m; + * relationshipRow.CostMultiplier + / 10000m; if (craftData.IconId != 0) { circleAmount *= @@ -520,7 +520,7 @@ public void Execute( Assert.Contains(craftData.IconId, iconIdList); } - var cp = equipment.StatsMap.GetAdditionalStats(ignoreZero: true).Sum( + var cp = equipment.StatsMap.GetAdditionalStats(true).Sum( stat => CPHelper.GetStatCP(stat.statType, stat.additionalValue) ); // CP > Stat convert can drop sub-1 values and vise versa. diff --git a/.Lib9c.Tests/Action/DailyRewardTest.cs b/.Lib9c.Tests/Action/DailyRewardTest.cs index 0028b438e7..1a580d9318 100644 --- a/.Lib9c.Tests/Action/DailyRewardTest.cs +++ b/.Lib9c.Tests/Action/DailyRewardTest.cs @@ -42,11 +42,11 @@ public DailyRewardTest(ITestOutputHelper outputHelper) [InlineData(false)] public void Execute(bool stateExist) { - IWorld previousStates = stateExist switch + var previousStates = stateExist switch { true => _initialState.SetDailyRewardReceivedBlockIndex(_agentAddress, 0L) .SetActionPoint(_avatarAddress, 0), - false => _initialState + false => _initialState, }; var nextState = ExecuteInternal(previousStates, _avatarAddress, DailyReward.DailyRewardInterval); diff --git a/.Lib9c.Tests/Action/EndPledgeTest.cs b/.Lib9c.Tests/Action/EndPledgeTest.cs index 296c29ba3b..578b08ea56 100644 --- a/.Lib9c.Tests/Action/EndPledgeTest.cs +++ b/.Lib9c.Tests/Action/EndPledgeTest.cs @@ -20,7 +20,7 @@ public void Execute(int balance) var patron = new PrivateKey().Address; var agent = new PrivateKey().Address; var context = new ActionContext(); - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState(agent.GetPledgeAddress(), List.Empty.Add(patron.Serialize()).Add(true.Serialize())); var mead = Currencies.Mead; if (balance > 0) @@ -50,10 +50,10 @@ public void Execute(int balance) [InlineData(false, true, typeof(FailedLoadStateException))] public void Execute_Throw_Exception(bool invalidSigner, bool invalidAgent, Type exc) { - Address patron = new PrivateKey().Address; - Address agent = new PrivateKey().Address; - List contract = List.Empty.Add(patron.Serialize()).Add(true.Serialize()); - IWorld states = new World(MockUtil.MockModernWorldState).SetLegacyState(agent.GetPledgeAddress(), contract); + var patron = new PrivateKey().Address; + var agent = new PrivateKey().Address; + var contract = List.Empty.Add(patron.Serialize()).Add(true.Serialize()); + var states = new World(MockUtil.MockModernWorldState).SetLegacyState(agent.GetPledgeAddress(), contract); var action = new EndPledge { diff --git a/.Lib9c.Tests/Action/EventDungeonBattleTest.cs b/.Lib9c.Tests/Action/EventDungeonBattleTest.cs index 2fec4ba2d6..098f3f08f2 100644 --- a/.Lib9c.Tests/Action/EventDungeonBattleTest.cs +++ b/.Lib9c.Tests/Action/EventDungeonBattleTest.cs @@ -168,8 +168,8 @@ public void Execute_Success_With_Ticket_Purchase( eventScheduleId, eventDungeonId, eventDungeonStageId, - buyTicketIfNeeded: true, - blockIndex: scheduleRow.StartBlockIndex); + true, + scheduleRow.StartBlockIndex); var nextEventDungeonInfoList = (Bencodex.Types.List)nextStates.GetLegacyState(eventDungeonInfoAddr)!; Assert.Equal( @@ -179,7 +179,7 @@ public void Execute_Success_With_Ticket_Purchase( nextStates.TryGetGoldBalance( _agentAddress, _ncgCurrency, - out FungibleAssetValue balance + out var balance ) ); Assert.Equal(0 * _ncgCurrency, balance); @@ -191,13 +191,15 @@ out FungibleAssetValue balance public void Execute_Throw_InvalidActionFieldException_By_EventScheduleId( int eventScheduleId, int eventDungeonId, - int eventDungeonStageId) => + int eventDungeonStageId) + { Assert.Throws(() => Execute( _initialStates, eventScheduleId, eventDungeonId, eventDungeonStageId)); + } [Theory] [InlineData(1001, 10010001, 10010001)] @@ -323,8 +325,8 @@ public void Execute_Throw_InsufficientBalanceException( eventScheduleId, eventDungeonId, eventDungeonStageId, - buyTicketIfNeeded: true, - blockIndex: scheduleRow.StartBlockIndex)); + true, + scheduleRow.StartBlockIndex)); } [Theory] @@ -387,9 +389,9 @@ public void Execute_DuplicatedException(int slotIndex, int runeId, int slotIndex [Fact] public void Execute_V100301() { - int eventScheduleId = 1001; - int eventDungeonId = 10010001; - int eventDungeonStageId = 10010001; + var eventScheduleId = 1001; + var eventDungeonId = 10010001; + var eventDungeonStageId = 10010001; var csv = $@"id,_name,start_block_index,dungeon_end_block_index,dungeon_tickets_max,dungeon_tickets_reset_interval_block_range,dungeon_ticket_price,dungeon_ticket_additional_price,dungeon_exp_seed_value,recipe_end_block_index 1001,2022 Summer Event,{ActionObsoleteConfig.V100301ExecutedBlockIndex},{ActionObsoleteConfig.V100301ExecutedBlockIndex + 100},5,7200,5,2,1,5018000"; _initialStates = @@ -520,8 +522,8 @@ private IWorld Execute( Foods = new List(), RuneInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, BuyTicketIfNeeded = buyTicketIfNeeded, }; diff --git a/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs b/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs index e4e3be9aa1..c559d7844f 100644 --- a/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs +++ b/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs @@ -34,7 +34,7 @@ public static IEnumerable GetAllClaimStakeRewardV1() var ver = string.IsNullOrEmpty(verStr) ? 1 : int.Parse(verStr); - yield return new object[] { str, ver }; + yield return new object[] { str, ver, }; } } diff --git a/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs b/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs index 53e5a03183..07cd4221ff 100644 --- a/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs @@ -76,7 +76,7 @@ public void Serialize( var actions = new[] { new BulkUnloadFromGarages(), - new BulkUnloadFromGarages(new[] { unloadData }), + new BulkUnloadFromGarages(new[] { unloadData, }), }; foreach (var action in actions) @@ -114,7 +114,7 @@ public void Execute_Success() { const long blockIndex = 0L; var (states, unloadDataEnumerable) = RegisterPlainValue(_previousStates); - var action = new BulkUnloadFromGarages(new[] { unloadDataEnumerable }); + var action = new BulkUnloadFromGarages(new[] { unloadDataEnumerable, }); states = action.Execute(new ActionContext { Signer = AgentAddress, @@ -146,7 +146,7 @@ public void Execute_Success() { var garageAddress = Addresses.GetGarageAddress(AgentAddress, fungibleId); Assert.Equal(0, new FungibleItemGarage(states.GetLegacyState(garageAddress)).Count); - Assert.True(inventory.HasFungibleItem(fungibleId, blockIndex: 0, count)); + Assert.True(inventory.HasFungibleItem(fungibleId, 0, count)); } } @@ -159,9 +159,9 @@ public void Execute_Success() Assert.Equal(blockIndex, mail.blockIndex); Assert.Equal(blockIndex, mail.requiredBlockIndex); Assert.True(action.UnloadData[0].fungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? - mail.FungibleAssetValues is null); + mail.FungibleAssetValues is null); Assert.True(action.UnloadData[0].fungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? - mail.FungibleIdAndCounts is null); + mail.FungibleIdAndCounts is null); Assert.Equal(action.UnloadData[0].memo, mail.Memo); } @@ -209,7 +209,7 @@ private static (Address balanceAddr, FungibleAssetValue value)[] .Select(tuple => (fungibleId: tuple.FungibleItem.FungibleId, tuple.count)) .ToArray(); - var actionContext = new ActionContext { Signer = Addresses.Admin }; + var actionContext = new ActionContext { Signer = Addresses.Admin, }; var garageBalanceAddress = Addresses.GetGarageBalanceAddress(AgentAddress); foreach (var (_, value) in fungibleAssetValues) { diff --git a/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs b/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs index 051e9ae9af..6fcd064689 100644 --- a/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs @@ -102,9 +102,9 @@ public void Serialize( des.LoadPlainValue(ser); Assert.Equal(action.RecipientAgentAddr, des.RecipientAgentAddr); Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? - des.FungibleAssetValues is null); + des.FungibleAssetValues is null); Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? - des.FungibleIdAndCounts is null); + des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); Assert.Equal(ser, des.PlainValue); @@ -133,7 +133,7 @@ public void Execute_Success() _fungibleAssetValues, _fungibleIdAndCounts, "memo"); - if (action.FungibleAssetValues is { }) + if (action.FungibleAssetValues is not null) { var senderGarageBalanceAddr = Addresses.GetGarageBalanceAddress(SenderAgentAddr); @@ -216,7 +216,7 @@ public void Execute_Throws_Exception() { // Sender's FungibleAssetValue Garage does not have enough balance. var previousStatesWithEmptyBalances = _previousStates; - var actionContext = new ActionContext { Signer = SenderAgentAddr }; + var actionContext = new ActionContext { Signer = SenderAgentAddr, }; var senderFungibleAssetValueGarageAddr = Addresses.GetGarageBalanceAddress(SenderAgentAddr); foreach (var vaf in _fungibleAssetValues) @@ -357,7 +357,7 @@ private static FungibleAssetValue[] GetFungibleAssetValues() GetSuccessfulPreviousStatesWithPlainValue() { var previousStates = _initialStatesWithAvatarStateV2; - var actionContext = new ActionContext { Signer = Addresses.Admin }; + var actionContext = new ActionContext { Signer = Addresses.Admin, }; var senderFavGarageBalanceAddr = Addresses.GetGarageBalanceAddress(SenderAgentAddr); var fungibleAssetValues = GetFungibleAssetValues(); @@ -380,16 +380,16 @@ private static FungibleAssetValue[] GetFungibleAssetValues() } var fungibleIdAndCounts = new List<(IFungibleItem fungibleItem, int count)>(); - var tradableIds = new[] { 400000, 500000 }; - var nonTradableIds = new[] { 600201, 800201, 800202 }; - for (int i = 0; i < tradableIds.Count(); i++) + var tradableIds = new[] { 400000, 500000, }; + var nonTradableIds = new[] { 600201, 800201, 800202, }; + for (var i = 0; i < tradableIds.Count(); i++) { var id = tradableIds[i]; var row = _tableSheets.MaterialItemSheet[id]; fungibleIdAndCounts.Add((ItemFactory.CreateTradableMaterial(row), i + 1)); } - for (int i = 0; i < nonTradableIds.Count(); i++) + for (var i = 0; i < nonTradableIds.Count(); i++) { var id = nonTradableIds[i]; var row = _tableSheets.MaterialItemSheet[id]; @@ -402,7 +402,7 @@ private static FungibleAssetValue[] GetFungibleAssetValues() SenderAgentAddr, fungibleItem.FungibleId); var garageState = previousStates.GetLegacyState(senderGarageAddr); - Material material = fungibleItem is TradableMaterial tradableMaterial + var material = fungibleItem is TradableMaterial tradableMaterial ? new Material(tradableMaterial) : (Material)fungibleItem; var garage = garageState is null diff --git a/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs b/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs index bf937fc18c..6b74266889 100644 --- a/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs @@ -36,6 +36,7 @@ public class LoadIntoMyGaragesTest private readonly FungibleAssetValue _cost; private readonly IWorld _previousStates; private readonly IFungibleItem[] _fungibleItems; + private readonly int[] _nonTradableIds = new[] { 600201, @@ -111,10 +112,10 @@ public void Serialize( var des = new LoadIntoMyGarages(); des.LoadPlainValue(ser); Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? - des.FungibleAssetValues is null); + des.FungibleAssetValues is null); Assert.Equal(action.AvatarAddr, des.AvatarAddr); Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? - des.FungibleIdAndCounts is null); + des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); Assert.Equal(ser, des.PlainValue); @@ -151,7 +152,7 @@ public void Execute_Success() nextStates.GetBalance(Addresses.GarageWallet, Currencies.Garage)); var garageBalanceAddr = Addresses.GetGarageBalanceAddress(AgentAddr); - if (action.FungibleAssetValues is { }) + if (action.FungibleAssetValues is not null) { foreach (var (balanceAddr, value) in action.FungibleAssetValues) { @@ -176,7 +177,7 @@ public void Execute_Success() { Assert.False(inventory.HasFungibleItem( fungibleId, - blockIndex: 0, + 0, 1)); var garageAddr = Addresses.GetGarageAddress( AgentAddr, @@ -266,7 +267,7 @@ public void Execute_Throws_Exception() // Balance does not enough to pay cost. var balance = _previousStates.GetBalance(AgentAddr, Currencies.Garage); var previousStatesWithNotEnoughCost = _previousStates.BurnAsset( - new ActionContext { Signer = AgentAddr }, + new ActionContext { Signer = AgentAddr, }, AgentAddr, balance); Assert.Throws(() => Execute( @@ -283,7 +284,7 @@ public void Execute_Throws_Exception() foreach (var (balanceAddr, value) in _fungibleAssetValues) { previousStatesWithEmptyBalances = previousStatesWithEmptyBalances.BurnAsset( - new ActionContext { Signer = AgentAddr }, + new ActionContext { Signer = AgentAddr, }, balanceAddr, value); } @@ -319,8 +320,8 @@ public void Execute_Throws_Exception() { avatarState.inventory.RemoveTradableFungibleItem( fungibleId, - requiredBlockIndex: null, - blockIndex: 0, + null, + 0, count - 1); } @@ -408,7 +409,7 @@ private static (Address balanceAddr, FungibleAssetValue value)[] .Select(objects => (FungibleAssetValue)objects[0]) .Where(fav => (tableSheets?.LoadIntoMyGaragesCostSheet.HasCost(fav.Currency.Ticker) ?? - true) && + true) && fav.Sign > 0) .Select(fav => { @@ -433,7 +434,7 @@ private static (Address balanceAddr, FungibleAssetValue value)[] AgentAddr, _avatarAddress, _tableSheets); - var actionContext = new ActionContext { Signer = Addresses.Admin }; + var actionContext = new ActionContext { Signer = Addresses.Admin, }; foreach (var (balanceAddr, value) in fungibleAssetValues) { if (value.Currency.Equals(_ncg)) @@ -471,7 +472,7 @@ private static (Address balanceAddr, FungibleAssetValue value)[] fungibleItemAndCounts .Select(tuple => (tuple.fungibleItem.FungibleId, tuple.count))); previousStates = previousStates.MintAsset( - new ActionContext { Signer = AgentAddr }, + new ActionContext { Signer = AgentAddr, }, AgentAddr, garageCost); return ( diff --git a/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs b/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs index 4f31eafa59..dae68f4ba7 100644 --- a/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs @@ -108,9 +108,9 @@ public void Serialize( des.LoadPlainValue(ser); Assert.Equal(action.RecipientAvatarAddr, des.RecipientAvatarAddr); Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? - des.FungibleAssetValues is null); + des.FungibleAssetValues is null); Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? - des.FungibleIdAndCounts is null); + des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); Assert.Equal(ser, des.PlainValue); @@ -144,7 +144,7 @@ public void Execute_Success() memo); var garageBalanceAddr = Addresses.GetGarageBalanceAddress(AgentAddr); - if (action.FungibleAssetValues is { }) + if (action.FungibleAssetValues is not null) { foreach (var (balanceAddr, value) in action.FungibleAssetValues) { @@ -158,7 +158,7 @@ public void Execute_Success() } var avatarState = nextStates.GetAvatarState(_recipientAvatarAddr); - if (action.FungibleIdAndCounts is { }) + if (action.FungibleIdAndCounts is not null) { foreach (var (fungibleId, count) in action.FungibleIdAndCounts) { @@ -168,7 +168,7 @@ public void Execute_Success() Assert.Equal(0, new FungibleItemGarage(nextStates.GetLegacyState(garageAddr)).Count); Assert.True(avatarState.inventory.HasFungibleItem( fungibleId, - blockIndex: 0, + 0, count)); } } @@ -179,9 +179,9 @@ public void Execute_Success() Assert.Equal(blockIndex, mail.blockIndex); Assert.Equal(blockIndex, mail.requiredBlockIndex); Assert.True(action.FungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? - mail.FungibleAssetValues is null); + mail.FungibleAssetValues is null); Assert.True(action.FungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? - mail.FungibleIdAndCounts is null); + mail.FungibleIdAndCounts is null); Assert.Equal(action.Memo, mail.Memo); } @@ -229,7 +229,7 @@ public void Execute_Throws_Exception() { // Agent's FungibleAssetValue garages does not have enough balance. var previousStatesWithEmptyBalances = _previousStates; - var actionContext = new ActionContext { Signer = AgentAddr }; + var actionContext = new ActionContext { Signer = AgentAddr, }; var garageBalanceAddress = Addresses.GetGarageBalanceAddress(AgentAddr); foreach (var (_, value) in _fungibleAssetValues) { @@ -340,7 +340,7 @@ private static (Address balanceAddr, FungibleAssetValue value)[] GetSuccessfulPreviousStatesWithPlainValue() { var previousStates = _initialStatesWithAvatarStateV2; - var actionContext = new ActionContext { Signer = Addresses.Admin }; + var actionContext = new ActionContext { Signer = Addresses.Admin, }; var garageBalanceAddress = Addresses.GetGarageBalanceAddress(AgentAddr); var fungibleAssetValues = GetFungibleAssetValues( AgentAddr, diff --git a/.Lib9c.Tests/Action/GoldDistributionTest.cs b/.Lib9c.Tests/Action/GoldDistributionTest.cs index 0a3879e746..012cc71521 100644 --- a/.Lib9c.Tests/Action/GoldDistributionTest.cs +++ b/.Lib9c.Tests/Action/GoldDistributionTest.cs @@ -9,28 +9,28 @@ public class GoldDistributionTest { public static readonly GoldDistribution[] Fixture = { - new GoldDistribution + new() { Address = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), AmountPerBlock = 100, StartBlock = 1, EndBlock = 100000, }, - new GoldDistribution + new() { Address = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"), AmountPerBlock = 3000, StartBlock = 3600, EndBlock = 13600, }, - new GoldDistribution + new() { Address = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"), AmountPerBlock = 100000000000, StartBlock = 2, EndBlock = 2, }, - new GoldDistribution + new() { Address = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), AmountPerBlock = 1000000, @@ -41,8 +41,8 @@ public class GoldDistributionTest public static string CreateFixtureCsvFile() { - string csvPath = Path.GetTempFileName(); - using (StreamWriter writer = File.CreateText(csvPath)) + var csvPath = Path.GetTempFileName(); + using (var writer = File.CreateText(csvPath)) { writer.Write(@"Address,AmountPerBlock,StartBlock,EndBlock F9A15F870701268Bd7bBeA6502eB15F4997f32f9,1000000,0,0 @@ -58,8 +58,8 @@ public static string CreateFixtureCsvFile() [Fact] public void LoadInDescendingEndBlockOrder() { - string fixturePath = CreateFixtureCsvFile(); - GoldDistribution[] records = GoldDistribution.LoadInDescendingEndBlockOrder(fixturePath); + var fixturePath = CreateFixtureCsvFile(); + var records = GoldDistribution.LoadInDescendingEndBlockOrder(fixturePath); Assert.Equal(Fixture, records); } } diff --git a/.Lib9c.Tests/Action/GrindingTest.cs b/.Lib9c.Tests/Action/GrindingTest.cs index 11a941d080..ad9fa8c231 100644 --- a/.Lib9c.Tests/Action/GrindingTest.cs +++ b/.Lib9c.Tests/Action/GrindingTest.cs @@ -93,7 +93,7 @@ public void Execute_Success(int itemLevel, int equipmentCount, bool equipped, in var testRandom = new TestRandom(); var itemRow = _tableSheets.EquipmentItemSheet.Values.First(r => r.Grade == 1); - for (int i = 0; i < equipmentCount; i++) + for (var i = 0; i < equipmentCount; i++) { var equipment = (Equipment)ItemFactory.CreateItemUsable(itemRow, testRandom.GenerateRandomGuid(), 1, itemLevel); equipment.equipped = equipped; @@ -352,7 +352,7 @@ private static IWorld Execute( { var testRandom = new TestRandom(); var equipmentIds = new List(); - for (int i = 0; i < equipmentCount; i++) + for (var i = 0; i < equipmentCount; i++) { equipmentIds.Add(testRandom.GenerateRandomGuid()); } @@ -376,7 +376,7 @@ private static IWorld Execute( var crystalCurrency = Currencies.Crystal; // CrystalCurrencyState.Address; var nextAvatarState = nextState.GetAvatarState(avatarAddress); - FungibleAssetValue asset = totalAsset * crystalCurrency; + var asset = totalAsset * crystalCurrency; Assert.Equal(asset, nextState.GetBalance(agentAddress, crystalCurrency)); Assert.False(nextAvatarState.inventory.HasNonFungibleItem(default)); @@ -396,11 +396,11 @@ private static IWorld Execute( private class CalculateMaterialRewardData : IEnumerable { - private readonly List _data = new List + private readonly List _data = new() { new object[] { - new[] { 10110000, 10120000, 10140000 }, + new[] { 10110000, 10120000, 10140000, }, new Dictionary { { 306040, 2 }, @@ -410,7 +410,7 @@ private class CalculateMaterialRewardData : IEnumerable }, new object[] { - new[] { 10110000, 10111000, 10112000, 10113000 }, + new[] { 10110000, 10111000, 10112000, 10113000, }, new Dictionary { { 306040, 8 }, @@ -418,24 +418,30 @@ private class CalculateMaterialRewardData : IEnumerable }, new object[] { - new[] { 10750008, 10760000, 20160000, 20160003 }, + new[] { 10750008, 10760000, 20160000, 20160003, }, new Dictionary { - { 306085, 15 }, // 5 + 10 + 0 + 0 - { 600401, 12 }, // 0 + 0 + 2 + 10 - { 600402, 23 }, // 0 + 0 + 3 + 20 + { 306085, 15 }, // 5 + 10 + 0 + 0 + { 600401, 12 }, // 0 + 0 + 2 + 10 + { 600402, 23 }, // 0 + 0 + 3 + 20 }, }, new object[] { - new[] { 10100000 }, + new[] { 10100000, }, new Dictionary(), }, }; - public IEnumerator GetEnumerator() => _data.GetEnumerator(); + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => _data.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return _data.GetEnumerator(); + } } } } diff --git a/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs index 8b6215d070..f88b49fb43 100644 --- a/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs @@ -30,7 +30,7 @@ public void Execute() var guildMasterAddress = AddressUtil.CreateAgentAddress(); var guildAddress = AddressUtil.CreateGuildAddress(); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .ApplyGuild(appliedMemberAddress, guildAddress); diff --git a/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs b/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs index e978cf4a68..6e56f5989a 100644 --- a/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs @@ -31,10 +31,10 @@ public void Execute() var guildAddress = AddressUtil.CreateGuildAddress(); var action = new ApplyGuild(guildAddress); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress); - IWorld bannedWorld = world.Ban(guildAddress, guildMasterAddress, agentAddress); + var bannedWorld = world.Ban(guildAddress, guildMasterAddress, agentAddress); // This case should fail because the agent is banned by the guild. Assert.Throws(() => action.Execute(new ActionContext diff --git a/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs b/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs index 114d7ff350..db636f327c 100644 --- a/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs +++ b/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs @@ -191,7 +191,7 @@ public void RejectGuildApplication() var guildMasterAddress = AddressUtil.CreateAgentAddress(); var agentAddress = AddressUtil.CreateAgentAddress(); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .ApplyGuild(agentAddress, guildAddress); Assert.True(world.TryGetGuildApplication(agentAddress, out _)); diff --git a/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs index d6ea8ee7b5..06ff38d9b5 100644 --- a/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs @@ -31,7 +31,7 @@ public void Execute() var guildAddress = AddressUtil.CreateGuildAddress(); var action = new CancelGuildApplication(); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress); Assert.Throws( () => action.Execute(new ActionContext diff --git a/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs b/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs index 78c089f567..df8db3f1f7 100644 --- a/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs @@ -13,20 +13,21 @@ namespace Lib9c.Tests.Action.Guild public class MakeGuildTest { - public static IEnumerable TestCases => new[] - { - new object[] - { - AddressUtil.CreateAgentAddress(), - // TODO: Update to false when Guild features are enabled. - true, - }, - new object[] + public static IEnumerable TestCases => + new[] { - GuildConfig.PlanetariumGuildOwner, - false, - }, - }; + new object[] + { + AddressUtil.CreateAgentAddress(), + // TODO: Update to false when Guild features are enabled. + true, + }, + new object[] + { + GuildConfig.PlanetariumGuildOwner, + false, + }, + }; [Fact] public void Serialization() diff --git a/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs b/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs index 46c937548d..a4f840bd6a 100644 --- a/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs +++ b/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs @@ -30,7 +30,7 @@ public void MigratePlanetariumPledgeToGuild_When_WithUnapprovedPledgeContract() .JoinGuild(guildAddress, guildMasterAddress) .SetLegacyState(pledgeAddress, new List( MeadConfig.PatronAddress.Serialize(), - false.Serialize(), // Unapproved + false.Serialize(), // Unapproved RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); diff --git a/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs b/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs index 70c8850a2d..c63beb306a 100644 --- a/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs @@ -54,7 +54,7 @@ public void Execute_When_WithPledgeContract() var action = new MigratePledgeToGuild(target); // Migrate by other. - IWorld newWorld = action.Execute(new ActionContext + var newWorld = action.Execute(new ActionContext { PreviousState = world, Signer = caller, diff --git a/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs b/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs index 4de4975872..9564e916e9 100644 --- a/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs @@ -28,7 +28,7 @@ public void Execute() var guildMasterAddress = AddressUtil.CreateAgentAddress(); var action = new QuitGuild(); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress); // This case should fail because guild master cannot quit the guild. diff --git a/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs index 217096d9ed..d063ca2db0 100644 --- a/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs @@ -31,7 +31,7 @@ public void Execute() var guildMasterAddress = AddressUtil.CreateAgentAddress(); var guildAddress = AddressUtil.CreateGuildAddress(); - IWorld world = new World(MockUtil.MockModernWorldState) + var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .ApplyGuild(appliedMemberAddress, guildAddress); diff --git a/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs b/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs index d3d4a9d957..24a7ecd0d1 100644 --- a/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs +++ b/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs @@ -208,8 +208,8 @@ public void Execute_InvalidStageException(int clearedWorldId, int clearedStageId var state = _initialState .SetLegacyState( - _avatarAddress.Derive("world_ids"), - List.Empty.Add(worldId.Serialize()) + _avatarAddress.Derive("world_ids"), + List.Empty.Add(worldId.Serialize()) ) .SetAvatarState(_avatarAddress, _avatarState); @@ -238,7 +238,7 @@ public void Execute_InvalidWorldException(int worldId, int stageId, bool unlocke avatarState.worldInformation = new WorldInformation(0, _initialState.GetSheet(), 10000001); - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState); + var state = _initialState.SetAvatarState(_avatarAddress, avatarState); if (unlockedIdsExist) { @@ -278,7 +278,7 @@ public void Execute_UsageLimitExceedException() avatarState.worldInformation = new WorldInformation(0, _initialState.GetSheet(), 25); - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState); + var state = _initialState.SetAvatarState(_avatarAddress, avatarState); var action = new HackAndSlashSweep { @@ -318,7 +318,7 @@ public void Execute_NotEnoughMaterialException(int useApStoneCount, int holdingA var apStone = ItemFactory.CreateTradableMaterial(row); avatarState.inventory.AddItem(apStone, holdingApStoneCount); - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState); + var state = _initialState.SetAvatarState(_avatarAddress, avatarState); var actionPoint = _initialState.GetActionPoint(_avatarAddress); var stageSheet = _initialState.GetSheet(); @@ -371,7 +371,7 @@ public void Execute_NotEnoughActionPointException() new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 400; - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState) + var state = _initialState.SetAvatarState(_avatarAddress, avatarState) .SetActionPoint(_avatarAddress, 0); var actionPoint = _initialState.GetActionPoint(_avatarAddress); @@ -425,7 +425,7 @@ public void Execute_PlayCountIsZeroException() new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 400; - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState) + var state = _initialState.SetAvatarState(_avatarAddress, avatarState) .SetActionPoint(_avatarAddress, 0); var actionPoint = state.GetActionPoint(_avatarAddress); @@ -479,13 +479,13 @@ public void Execute_NotEnoughCombatPointException() new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 1; - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState) + var state = _initialState.SetAvatarState(_avatarAddress, avatarState) .SetActionPoint(_avatarAddress, 0); var actionPoint = state.GetActionPoint(_avatarAddress); var stageSheet = _initialState.GetSheet(); var (expectedLevel, expectedExp) = (0, 0L); - int stageId = 24; + var stageId = 24; if (stageSheet.TryGetValue(stageId, out var stageRow)) { var itemPlayCount = @@ -742,8 +742,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 equipments = new List(), runeInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, avatarAddress = _avatarAddress, actionPoint = (int)actionPoint, @@ -782,7 +782,7 @@ public void Execute_ArgumentOutOfRangeException(int ap, int apPotion) new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 400; - IWorld state = _initialState.SetAvatarState(_avatarAddress, avatarState) + var state = _initialState.SetAvatarState(_avatarAddress, avatarState) .SetActionPoint(_avatarAddress, 0); var actionPoint = _initialState.GetActionPoint(_avatarAddress); diff --git a/.Lib9c.Tests/Action/HackAndSlashTest.cs b/.Lib9c.Tests/Action/HackAndSlashTest.cs index 9d61aab639..0db89f7609 100644 --- a/.Lib9c.Tests/Action/HackAndSlashTest.cs +++ b/.Lib9c.Tests/Action/HackAndSlashTest.cs @@ -130,10 +130,10 @@ public void Execute(int avatarLevel, int worldId, int stageId, bool isWeaponLock if (avatarLevel >= GameConfig.RequireCharacterLevel.CharacterFullCostumeSlot) { var costumeId = _tableSheets - .CostumeItemSheet - .Values - .First(r => r.ItemSubType == ItemSubType.FullCostume) - .Id; + .CostumeItemSheet + .Values + .First(r => r.ItemSubType == ItemSubType.FullCostume) + .Id; var costume = (Costume)ItemFactory.CreateItem( _tableSheets.ItemSheet[costumeId], random); @@ -167,7 +167,7 @@ public void Execute(int avatarLevel, int worldId, int stageId, bool isWeaponLock previousAvatarState.Update(mail); } - IWorld state = _initialState + var state = _initialState .SetAvatarState(_avatarAddress, previousAvatarState) .SetLegacyState( _avatarAddress.Derive("world_ids"), @@ -301,7 +301,7 @@ public void MaxLevelTest() var worldRow = _tableSheets.WorldSheet .FirstOrDefault(row => stageId >= row.Value.StageBegin && - stageId <= row.Value.StageEnd); + stageId <= row.Value.StageEnd); var worldId = worldRow.Value.Id; previousAvatarState.worldInformation = new WorldInformation( @@ -360,8 +360,8 @@ public void MultipleEquipmentTest(ItemSubType type, int maxCount) foreach (var row in weaponRows) { var equipment = ItemFactory.CreateItem( - _tableSheets.EquipmentItemSheet[row.Id], - new TestRandom()) + _tableSheets.EquipmentItemSheet[row.Id], + new TestRandom()) as Equipment; equipments.Add(equipment.ItemId); @@ -407,7 +407,7 @@ public void Execute_Throw_FailedLoadStateException(bool empty) AvatarAddress = _avatarAddress, }; - IWorld state = empty + var state = empty ? new World(MockUtil.MockModernWorldState) : _initialState .SetAvatarState(_avatarAddress, _avatarState) @@ -530,7 +530,7 @@ public void Execute_Throw_InvalidWorldException(int worldId, int stageId, bool u AvatarAddress = _avatarAddress, }; - IWorld state = _initialState; + var state = _initialState; if (unlockedIdsExist) { state = state.SetLegacyState( @@ -765,7 +765,7 @@ public void ExecuteWithoutPlayCount() previousAvatarState.Update(mail); } - IWorld state = _initialState.SetAvatarState(_avatarAddress, previousAvatarState); + var state = _initialState.SetAvatarState(_avatarAddress, previousAvatarState); var action = new HackAndSlash { @@ -807,7 +807,7 @@ public void Execute_Throw_NotEnoughAvatarLevelException(int avatarLevel) }; var state = _initialState; - var itemIds = new[] { GameConfig.DefaultAvatarWeaponId, 40100000 }; + var itemIds = new[] { GameConfig.DefaultAvatarWeaponId, 40100000, }; foreach (var itemId in itemIds) { foreach (var requirementRow in _tableSheets.ItemRequirementSheet.OrderedList @@ -1036,7 +1036,7 @@ public void CheckRewardItems(int worldId, int stageId) previousAvatarState.Update(mail); } - IWorld state = _initialState + var state = _initialState .SetAvatarState(_avatarAddress, previousAvatarState) .SetLegacyState( _avatarAddress.Derive("world_ids"), @@ -1068,8 +1068,8 @@ public void CheckRewardItems(int worldId, int stageId) var rewardItem = nextAvatarState.inventory.Items.Where( x => x.item.ItemSubType != ItemSubType.FoodMaterial && - x.item is IFungibleItem ownedFungibleItem && - x.item.Id != 400000 && x.item.Id != 500000); + x.item is IFungibleItem ownedFungibleItem && + x.item.Id != 400000 && x.item.Id != 500000); var worldQuestSheet = state.GetSheet(); var questRow = worldQuestSheet.OrderedList.FirstOrDefault(e => e.Goal == stageId); @@ -1319,8 +1319,8 @@ public void CheckUsedApByStaking(int level, int playCount) .MintAsset(context, stakeStateAddress, requiredGold * _initialState.GetGoldCurrency()); var expectedAp = state.GetActionPoint(_avatarAddress) - - _tableSheets.StakeActionPointCoefficientSheet.GetActionPointByStaking( - _tableSheets.StageSheet[stageId].CostAP, playCount, level); + _tableSheets.StakeActionPointCoefficientSheet.GetActionPointByStaking( + _tableSheets.StageSheet[stageId].CostAP, playCount, level); var action = new HackAndSlash { Costumes = new List(), @@ -1479,10 +1479,10 @@ public void ExecuteTwoRepetitions() if (avatarLevel >= GameConfig.RequireCharacterLevel.CharacterFullCostumeSlot) { var costumeId = _tableSheets - .CostumeItemSheet - .Values - .First(r => r.ItemSubType == ItemSubType.FullCostume) - .Id; + .CostumeItemSheet + .Values + .First(r => r.ItemSubType == ItemSubType.FullCostume) + .Id; var costume = (Costume)ItemFactory.CreateItem( _tableSheets.ItemSheet[costumeId], random); @@ -1526,8 +1526,8 @@ public void ExecuteTwoRepetitions() Foods = new List(), RuneInfos = new List() { - new RuneSlotInfo(0, 30001), - new RuneSlotInfo(1, 10002), + new (0, 30001), + new (1, 10002), }, WorldId = worldId, StageId = stageId, @@ -1549,8 +1549,8 @@ public void ExecuteTwoRepetitions() Foods = new List(), RuneInfos = new List() { - new RuneSlotInfo(0, 10002), - new RuneSlotInfo(1, 30001), + new (0, 10002), + new (1, 30001), }, WorldId = worldId, StageId = stageId, @@ -1593,10 +1593,10 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 if (avatarLevel >= GameConfig.RequireCharacterLevel.CharacterFullCostumeSlot) { var costumeId = _tableSheets - .CostumeItemSheet - .Values - .First(r => r.ItemSubType == ItemSubType.FullCostume) - .Id; + .CostumeItemSheet + .Values + .First(r => r.ItemSubType == ItemSubType.FullCostume) + .Id; var costume = (Costume)ItemFactory.CreateItem( _tableSheets.ItemSheet[costumeId], random); @@ -1659,8 +1659,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 Foods = new List(), RuneInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, WorldId = worldId, StageId = stageId, diff --git a/.Lib9c.Tests/Action/HitHelperTest.cs b/.Lib9c.Tests/Action/HitHelperTest.cs index ab8ba20723..5e3e00727b 100644 --- a/.Lib9c.Tests/Action/HitHelperTest.cs +++ b/.Lib9c.Tests/Action/HitHelperTest.cs @@ -20,9 +20,9 @@ long GetHitStep2Legacy(int attackerHit, int defenderHit) HitHelper.GetHitStep2AdditionalCorrectionMax); } - for (int i = 0; i < 9; i++) + for (var i = 0; i < 9; i++) { - for (int j = 0; j < 9; j++) + for (var j = 0; j < 9; j++) { var legacy = GetHitStep2Legacy(i, j); var current = HitHelper.GetHitStep2(i, j); diff --git a/.Lib9c.Tests/Action/InitializeStatesTest.cs b/.Lib9c.Tests/Action/InitializeStatesTest.cs index 7af13e7d5f..01d0d679f7 100644 --- a/.Lib9c.Tests/Action/InitializeStatesTest.cs +++ b/.Lib9c.Tests/Action/InitializeStatesTest.cs @@ -39,17 +39,17 @@ public void Execute() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (ActivationKey activationKey, PendingActivationState pendingActivation) = + (var activationKey, var pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: new AdminState( new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), 1500000 @@ -57,7 +57,7 @@ public void Execute() activatedAccountsState: new ActivatedAccountsState(), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, - pendingActivationStates: new[] { pendingActivation } + pendingActivationStates: new[] { pendingActivation, } ); var genesisState = action.Execute(new ActionContext() @@ -101,17 +101,17 @@ public void ExecuteWithAuthorizedMinersState() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (ActivationKey activationKey, PendingActivationState pendingActivation) = + (var activationKey, var pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: new AdminState( new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), 1500000 @@ -119,11 +119,11 @@ public void ExecuteWithAuthorizedMinersState() activatedAccountsState: new ActivatedAccountsState(), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, - pendingActivationStates: new[] { pendingActivation }, + pendingActivationStates: new[] { pendingActivation, }, authorizedMinersState: new AuthorizedMinersState( interval: 50, validUntil: 1000, - miners: new[] { default(Address) } + miners: new[] { default(Address), } ) ); @@ -141,7 +141,7 @@ public void ExecuteWithAuthorizedMinersState() Assert.Equal(50, fetchedState.Interval); Assert.Equal(1000, fetchedState.ValidUntil); - Assert.Equal(new[] { default(Address) }, fetchedState.Miners); + Assert.Equal(new[] { default(Address), }, fetchedState.Miners); } [Fact] @@ -157,23 +157,23 @@ public void ExecuteWithActivateAdminKey() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (ActivationKey activationKey, PendingActivationState pendingActivation) = + (var activationKey, var pendingActivation) = ActivationKey.Create(privateKey, nonce); var adminAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: new AdminState(adminAddress, 1500000), activatedAccountsState: new ActivatedAccountsState(ImmutableHashSet
.Empty.Add(adminAddress)), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, - pendingActivationStates: new[] { pendingActivation } + pendingActivationStates: new[] { pendingActivation, } ); var genesisState = action.Execute(new ActionContext() @@ -203,7 +203,7 @@ public void ExecuteWithCredits() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var adminAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); var creditState = new CreditsState( new[] @@ -215,11 +215,11 @@ public void ExecuteWithCredits() ); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: new AdminState(adminAddress, 1500000), activatedAccountsState: new ActivatedAccountsState(ImmutableHashSet
.Empty.Add(adminAddress)), goldCurrencyState: new GoldCurrencyState(ncg), @@ -256,22 +256,22 @@ public void ExecuteWithoutAdminState() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (ActivationKey activationKey, PendingActivationState pendingActivation) = + (var activationKey, var pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: null, activatedAccountsState: new ActivatedAccountsState(ImmutableHashSet
.Empty), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, - pendingActivationStates: new[] { pendingActivation } + pendingActivationStates: new[] { pendingActivation, } ); var genesisState = action.Execute(new ActionContext() @@ -301,15 +301,15 @@ public void ExecuteWithoutInitialSupply() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: null, activatedAccountsState: new ActivatedAccountsState(ImmutableHashSet
.Empty), goldCurrencyState: new GoldCurrencyState(ncg, 0), @@ -341,21 +341,21 @@ public void ExecuteWithAssetMinters() // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var ncg = Currency.Legacy("NCG", 2, minterKey.Address); #pragma warning restore CS0618 - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var adminAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); var action = new InitializeStates( - rankingState: new RankingState0(), - shopState: new ShopState(), - tableSheets: _sheets, - gameConfigState: gameConfigState, - redeemCodeState: new RedeemCodeState(redeemCodeListSheet), + new RankingState0(), + new ShopState(), + _sheets, + gameConfigState, + new RedeemCodeState(redeemCodeListSheet), adminAddressState: new AdminState(adminAddress, 1500000), activatedAccountsState: new ActivatedAccountsState(ImmutableHashSet
.Empty.Add(adminAddress)), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, pendingActivationStates: Array.Empty(), - assetMinters: new[] { default(Address) }.ToHashSet() + assetMinters: new[] { default(Address), }.ToHashSet() ); var genesisState = action.Execute(new ActionContext() diff --git a/.Lib9c.Tests/Action/InvalidSignatureExceptionTest.cs b/.Lib9c.Tests/Action/InvalidSignatureExceptionTest.cs index 13fe51545a..ebd1e50133 100644 --- a/.Lib9c.Tests/Action/InvalidSignatureExceptionTest.cs +++ b/.Lib9c.Tests/Action/InvalidSignatureExceptionTest.cs @@ -15,12 +15,12 @@ public void Serialize() var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); var pending = new PendingActivationState( - new byte[] { 0x00 }, + new byte[] { 0x00, }, new PrivateKey().PublicKey ); var exc = new InvalidSignatureException( pending, - new byte[] { 0x01 } + new byte[] { 0x01, } ); formatter.Serialize(ms, exc); diff --git a/.Lib9c.Tests/Action/IssueTokenTest.cs b/.Lib9c.Tests/Action/IssueTokenTest.cs index a6aafb8214..ea69a8c5eb 100644 --- a/.Lib9c.Tests/Action/IssueTokenTest.cs +++ b/.Lib9c.Tests/Action/IssueTokenTest.cs @@ -44,7 +44,7 @@ public IssueTokenTest() .Select(r => r.ItemId); var inventory = new Inventory(); foreach (var row in tableSheets.MaterialItemSheet.OrderedList! - .Where(r => materialIds.Contains(r.Id))) + .Where(r => materialIds.Contains(r.Id))) { var material = ItemFactory.CreateMaterial(row); var tradableMaterial = ItemFactory.CreateTradableMaterial(row); @@ -109,7 +109,7 @@ public void Execute_With_FungibleAssetValues() }; var prevState = _prevState.MintAsset(new ActionContext(), _signer, FungibleAssetValue.Parse(Currencies.Garage, "4.2000042")); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, @@ -165,8 +165,8 @@ public void Execute_With_FungibleItemValue() ); Assert.Equal(0 * Currencies.Garage, nextState.GetBalance(_signer, Currencies.Garage)); - Currency nonTradableItemCurrency = Currency.Legacy("Item_NT_500000", 0, null); - Currency tradableItemCurrency = Currency.Legacy("Item_T_500000", 0, null); + var nonTradableItemCurrency = Currency.Legacy("Item_NT_500000", 0, null); + var tradableItemCurrency = Currency.Legacy("Item_T_500000", 0, null); Assert.Equal(nonTradableItemCurrency * 42, nextState.GetBalance(_signer, nonTradableItemCurrency)); Assert.Equal(tradableItemCurrency * 42, nextState.GetBalance(_signer, tradableItemCurrency)); var inventory = nextState.GetInventoryV2(_avatarAddress); diff --git a/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs b/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs index ef79bed692..136f49794c 100644 --- a/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs +++ b/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs @@ -40,10 +40,10 @@ public IssueTokensFromGarageTest() MockWorldState.CreateModern() .SetBalance(garageBalanceAddr, Currencies.Crystal * 1000)); - IEnumerable materials = _tableSheets.MaterialItemSheet.OrderedList! + var materials = _tableSheets.MaterialItemSheet.OrderedList! .Take(3) .Select(ItemFactory.CreateMaterial); - foreach (Material material in materials) + foreach (var material in materials) { var garageAddr = Addresses.GetGarageAddress(_signer, material.FungibleId); var garage = new FungibleItemGarage(material, 1000); @@ -66,7 +66,7 @@ public void PlainValue() }; var action = new IssueTokensFromGarage(specs); - Dictionary expected = Dictionary.Empty + var expected = Dictionary.Empty .Add("type_id", "issue_tokens_from_garage") .Add("values", List.Empty .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) @@ -80,7 +80,7 @@ public void PlainValue() [Fact] public void LoadPlainValue() { - Dictionary encoded = Dictionary.Empty + var encoded = Dictionary.Empty .Add("type_id", "issue_tokens_from_garage") .Add("values", List.Empty .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) @@ -104,7 +104,7 @@ public void Execute_With_FungibleAssetValue() IssueTokensFromGarage.Spec.FromFungibleAssetValue(Currencies.Crystal * 42), }); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = _prevState, @@ -142,7 +142,7 @@ public void Execute_With_FungibleItemValue() } ); - Currency itemCurrency = Currency.Legacy("Item_NT_100000", 0, null); + var itemCurrency = Currency.Legacy("Item_NT_100000", 0, null); var garageAddr = Addresses.GetGarageAddress(_signer, SampleFungibleId); Assert.Equal(itemCurrency * 42, nextState.GetBalance(_signer, itemCurrency)); Assert.Equal(1000 - 42, new FungibleItemGarage(nextState.GetLegacyState(garageAddr)).Count); diff --git a/.Lib9c.Tests/Action/ItemEnhancementTest.cs b/.Lib9c.Tests/Action/ItemEnhancementTest.cs index b5fa83694e..5eb1504b8e 100644 --- a/.Lib9c.Tests/Action/ItemEnhancementTest.cs +++ b/.Lib9c.Tests/Action/ItemEnhancementTest.cs @@ -188,7 +188,7 @@ public void Execute( bool oldMaterial, int materialCount, bool duplicated = false - ) + ) { var row = _tableSheets.EquipmentItemSheet.Values.First(r => r.Id == 10110000); var equipment = (Equipment)ItemFactory.CreateItemUsable(row, default, 0, startLevel); @@ -209,7 +209,7 @@ public void Execute( equipment.Exp = 0L; } - _avatarState.inventory.AddItem(equipment, count: 1); + _avatarState.inventory.AddItem(equipment, 1); var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault(r => r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && @@ -244,7 +244,7 @@ public void Execute( material.Exp = 0L; } - _avatarState.inventory.AddItem(material, count: 1); + _avatarState.inventory.AddItem(material, 1); } var result = new CombinationConsumable5.ResultModel() @@ -300,7 +300,7 @@ public void Execute( var nextAvatarState = nextState.GetAvatarState(_avatarAddress); var expectedTargetRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault( r => r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && - r.Level == level); + r.Level == level); var expectedCost = (expectedTargetRow?.Cost ?? 0) - (startRow?.Cost ?? 0); var expectedBlockIndex = (expectedTargetRow?.RequiredBlockIndex ?? 0) - (startRow?.RequiredBlockIndex ?? 0); @@ -392,8 +392,8 @@ public void LoadPlainValue() public void Execute_With_Hammer(bool oldStart) { var row = _tableSheets.EquipmentItemSheet.Values.First(r => r.Id == 10110000); - int startLevel = 0; - int materialCount = 1; + var startLevel = 0; + var materialCount = 1; var equipment = (Equipment)ItemFactory.CreateItemUsable(row, default, 0, startLevel); equipment.Exp = (long)row.Exp!; var hammerId = ItemEnhancement.HammerIds.First(); @@ -404,7 +404,7 @@ public void Execute_With_Hammer(bool oldStart) equipment.Exp = 0L; } - _avatarState.inventory.AddItem(equipment, count: 1); + _avatarState.inventory.AddItem(equipment, 1); var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault(r => r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && @@ -419,7 +419,7 @@ public void Execute_With_Hammer(bool oldStart) (Equipment)ItemFactory.CreateItemUsable(row, materialId, 0, 0); material.Exp = (long)row.Exp!; expectedExpIncrement += material.Exp; - _avatarState.inventory.AddItem(material, count: 1); + _avatarState.inventory.AddItem(material, 1); } _avatarState.inventory.AddItem( @@ -484,7 +484,7 @@ public void Execute_With_Hammer(bool oldStart) var nextAvatarState = nextState.GetAvatarState(_avatarAddress); var expectedTargetRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault( r => r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && - r.Level == level); + r.Level == level); var expectedCost = (expectedTargetRow?.Cost ?? 0) - (startRow?.Cost ?? 0); var expectedBlockIndex = (expectedTargetRow?.RequiredBlockIndex ?? 0) - (startRow?.RequiredBlockIndex ?? 0); diff --git a/.Lib9c.Tests/Action/JoinArena1Test.cs b/.Lib9c.Tests/Action/JoinArena1Test.cs index 0e5ad7690b..71d03e2ed5 100644 --- a/.Lib9c.Tests/Action/JoinArena1Test.cs +++ b/.Lib9c.Tests/Action/JoinArena1Test.cs @@ -102,7 +102,7 @@ public JoinArena1Test(ITestOutputHelper outputHelper) .SetAvatarState(_avatar2Address, avatar2State) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((string key, string value) in sheets) + foreach ((var key, var value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -188,7 +188,7 @@ public void Execute(long blockIndex, int championshipId, int round, string balan avatarState = AddMedal(avatarState, row, 80); var context = new ActionContext(); - var state = (balance == "0") + var state = balance == "0" ? _state : _state.MintAsset(context, _signer, FungibleAssetValue.Parse(_currency, balance)); diff --git a/.Lib9c.Tests/Action/JoinArena3Test.cs b/.Lib9c.Tests/Action/JoinArena3Test.cs index d10ed47324..413d123387 100644 --- a/.Lib9c.Tests/Action/JoinArena3Test.cs +++ b/.Lib9c.Tests/Action/JoinArena3Test.cs @@ -105,7 +105,7 @@ public JoinArena3Test(ITestOutputHelper outputHelper) .SetLegacyState(gameConfigState.address, gameConfigState.Serialize()) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((string key, string value) in sheets) + foreach ((var key, var value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -190,7 +190,7 @@ public void Execute(long blockIndex, int championshipId, int round, string balan avatarState = AddMedal(avatarState, row, 80); var context = new ActionContext(); - var state = (balance == "0") + var state = balance == "0" ? _state : _state.MintAsset(context, _signer, FungibleAssetValue.Parse(_currency, balance)); @@ -499,8 +499,8 @@ public void Execute_NotEnoughClearedStageLevelException() [InlineData(1, 10002, 1, 30001, typeof(DuplicatedRuneSlotIndexException))] public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2, int runeId2, Type exception) { - int championshipId = 1; - int round = 1; + var championshipId = 1; + var round = 1; var arenaSheet = _state.GetSheet(); if (!arenaSheet.TryGetValue(championshipId, out var row)) { @@ -538,8 +538,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 equipments = equipments, runeInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, avatarAddress = _avatarAddress, }; diff --git a/.Lib9c.Tests/Action/JoinArenaTest.cs b/.Lib9c.Tests/Action/JoinArenaTest.cs index 19e66cfd6e..1c2b5dabcd 100644 --- a/.Lib9c.Tests/Action/JoinArenaTest.cs +++ b/.Lib9c.Tests/Action/JoinArenaTest.cs @@ -1,343 +1,344 @@ -namespace Lib9c.Tests.Action; - -using System; -using System.Collections.Generic; -using System.Linq; -using Bencodex.Types; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Libplanet.Types.Assets; -using Lib9c.Tests.Util; -using Nekoyume.Action; -using Nekoyume.Arena; -using Nekoyume.Model.Arena; -using Nekoyume.Model.EnumType; -using Nekoyume.Model.Item; -using Nekoyume.Model.State; -using Nekoyume.Module; -using Nekoyume.TableData; -using Serilog; -using Xunit; -using Xunit.Abstractions; - -public class JoinArenaTest +namespace Lib9c.Tests.Action { - private readonly IWorld _world; - private readonly TableSheets _tableSheets; - private readonly AgentState _myAgentState; - private readonly AvatarState _myAvatarState; + using System; + using System.Collections.Generic; + using System.Linq; + using Bencodex.Types; + using Libplanet.Action.State; + using Libplanet.Crypto; + using Libplanet.Types.Assets; + using Lib9c.Tests.Util; + using Nekoyume.Action; + using Nekoyume.Arena; + using Nekoyume.Model.Arena; + using Nekoyume.Model.EnumType; + using Nekoyume.Model.Item; + using Nekoyume.Model.State; + using Nekoyume.Module; + using Nekoyume.TableData; + using Serilog; + using Xunit; + using Xunit.Abstractions; - public JoinArenaTest(ITestOutputHelper outputHelper) + public class JoinArenaTest { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Verbose() - .WriteTo.TestOutput(outputHelper) - .CreateLogger(); - (_world, _tableSheets) = InitializeUtil.Initialize(); - (_world, _myAgentState) = InitializeUtil.AddAgent(_world); - (_world, _myAvatarState, _) = InitializeUtil.AddAvatar( - _world, - _tableSheets.GetAvatarSheets(), - _myAgentState.address); - } + private readonly IWorld _world; + private readonly TableSheets _tableSheets; + private readonly AgentState _myAgentState; + private readonly AvatarState _myAvatarState; - [Fact] - public void Execute_OffSeason_Success() - { - Execute( - _world, - _myAgentState.address, - blockIndex: 0, - randomSeed: 0, - _myAvatarState.address, - championshipId: 1, - round: 1, - costumes: new List(), - equipments: new List(), - runeInfos: new List()); - } + public JoinArenaTest(ITestOutputHelper outputHelper) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.TestOutput(outputHelper) + .CreateLogger(); + (_world, _tableSheets) = InitializeUtil.Initialize(); + (_world, _myAgentState) = InitializeUtil.AddAgent(_world); + (_world, _myAvatarState, _) = InitializeUtil.AddAvatar( + _world, + _tableSheets.GetAvatarSheets(), + _myAgentState.address); + } - [Fact] - public void Execute_Season_Success() - { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Season && - e2.EntranceFee > 0)); - var roundData = row.Round.First(e => - e.ArenaType == ArenaType.Season && - e.EntranceFee > 0); - var blockIndex = roundData.StartBlockIndex; - var fee = ArenaHelper.GetEntranceFee( - roundData, - blockIndex, - _myAvatarState.level); - var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); - Execute( - world, - _myAgentState.address, - blockIndex: blockIndex, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List()); - } + [Fact] + public void Execute_OffSeason_Success() + { + Execute( + _world, + _myAgentState.address, + 0, + 0, + _myAvatarState.address, + 1, + 1, + new List(), + new List(), + new List()); + } - [Fact] - public void Execute_Championship_Success() - { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Championship && - e2.RequiredMedalCount > 0)); - Assert.True(row.TryGetChampionshipRound(out var roundData)); - var blockIndex = roundData.StartBlockIndex; - var fee = ArenaHelper.GetEntranceFee( - roundData, - blockIndex, - _myAvatarState.level); - var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); - var seasonRound = row.Round.First(e => e.ArenaType == ArenaType.Season); - var itemSheetId = seasonRound.MedalId; - Assert.True(_tableSheets.ItemSheet.TryGetValue(itemSheetId, out var itemRow)); - var item = ItemFactory.CreateItem(itemRow, new TestRandom()); - var inventory = _world.GetInventoryV2(_myAvatarState.address); - inventory.AddItem(item, roundData.RequiredMedalCount); - world = world.SetInventory(_myAvatarState.address, inventory); + [Fact] + public void Execute_Season_Success() + { + var row = _tableSheets.ArenaSheet.OrderedList!.First(e => + e.Round.Any(e2 => + e2.ArenaType == ArenaType.Season && + e2.EntranceFee > 0)); + var roundData = row.Round.First(e => + e.ArenaType == ArenaType.Season && + e.EntranceFee > 0); + var blockIndex = roundData.StartBlockIndex; + var fee = ArenaHelper.GetEntranceFee( + roundData, + blockIndex, + _myAvatarState.level); + var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); + Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List()); + } - Execute( - world, - _myAgentState.address, - blockIndex: blockIndex, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List()); - } + [Fact] + public void Execute_Championship_Success() + { + var row = _tableSheets.ArenaSheet.OrderedList!.First(e => + e.Round.Any(e2 => + e2.ArenaType == ArenaType.Championship && + e2.RequiredMedalCount > 0)); + Assert.True(row.TryGetChampionshipRound(out var roundData)); + var blockIndex = roundData.StartBlockIndex; + var fee = ArenaHelper.GetEntranceFee( + roundData, + blockIndex, + _myAvatarState.level); + var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); + var seasonRound = row.Round.First(e => e.ArenaType == ArenaType.Season); + var itemSheetId = seasonRound.MedalId; + Assert.True(_tableSheets.ItemSheet.TryGetValue(itemSheetId, out var itemRow)); + var item = ItemFactory.CreateItem(itemRow, new TestRandom()); + var inventory = _world.GetInventoryV2(_myAvatarState.address); + inventory.AddItem(item, roundData.RequiredMedalCount); + world = world.SetInventory(_myAvatarState.address, inventory); - [Theory] - [InlineData(int.MaxValue)] - public void Execute_SheetRowNotFoundException(int championshipId) - { - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - blockIndex: 0, - randomSeed: 0, - _myAvatarState.address, - championshipId: championshipId, - round: 1, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); - } + Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List()); + } - [Theory] - [InlineData(10)] - public void Execute_RoundNotFoundByIdsException(int round) - { - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - blockIndex: 0, - randomSeed: 0, - _myAvatarState.address, - championshipId: 1, - round: round, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); - } + [Theory] + [InlineData(int.MaxValue)] + public void Execute_SheetRowNotFoundException(int championshipId) + { + Assert.Throws(() => Execute( + _world, + _myAgentState.address, + 0, + 0, + _myAvatarState.address, + championshipId, + 1, + new List(), + new List(), + new List())); + } - [Fact] - public void Execute_NotEnoughFungibleAssetValueException() - { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Season && - e2.EntranceFee > 0)); - var roundData = row.Round.First(e => - e.ArenaType == ArenaType.Season && - e.EntranceFee > 0); - var blockIndex = roundData.StartBlockIndex; + [Theory] + [InlineData(10)] + public void Execute_RoundNotFoundByIdsException(int round) + { + Assert.Throws(() => Execute( + _world, + _myAgentState.address, + 0, + 0, + _myAvatarState.address, + 1, + round, + new List(), + new List(), + new List())); + } - // with 0 assets. - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - blockIndex: blockIndex, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); + [Fact] + public void Execute_NotEnoughFungibleAssetValueException() + { + var row = _tableSheets.ArenaSheet.OrderedList!.First(e => + e.Round.Any(e2 => + e2.ArenaType == ArenaType.Season && + e2.EntranceFee > 0)); + var roundData = row.Round.First(e => + e.ArenaType == ArenaType.Season && + e.EntranceFee > 0); + var blockIndex = roundData.StartBlockIndex; - // get discounted fee. - var fee = ArenaHelper.GetEntranceFee( - roundData, - blockIndex - 1, - _myAvatarState.level); - var world = _world - .MintAsset(new ActionContext(), _myAgentState.address, fee) - .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); - // with not enough assets in discount period. - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex: blockIndex - 1, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); + // with 0 assets. + Assert.Throws(() => Execute( + _world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); - // get original fee. - fee = ArenaHelper.GetEntranceFee( - roundData, - blockIndex, - _myAvatarState.level); - world = _world - .MintAsset(new ActionContext(), _myAgentState.address, fee) - .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); - // with not enough assets in discount period. - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex: blockIndex, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); - } + // get discounted fee. + var fee = ArenaHelper.GetEntranceFee( + roundData, + blockIndex - 1, + _myAvatarState.level); + var world = _world + .MintAsset(new ActionContext(), _myAgentState.address, fee) + .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); + // with not enough assets in discount period. + Assert.Throws(() => Execute( + world, + _myAgentState.address, + blockIndex - 1, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); - [Fact] - public void Execute_NotEnoughMedalException() - { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Championship && - e2.RequiredMedalCount > 0)); - Assert.True(row.TryGetChampionshipRound(out var roundData)); - var blockIndex = roundData.StartBlockIndex; - var fee = ArenaHelper.GetEntranceFee( - roundData, - blockIndex, - _myAvatarState.level); - var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex: blockIndex, - randomSeed: 0, - _myAvatarState.address, - championshipId: row.ChampionshipId, - round: roundData.Round, - costumes: new List(), - equipments: new List(), - runeInfos: new List())); - } + // get original fee. + fee = ArenaHelper.GetEntranceFee( + roundData, + blockIndex, + _myAvatarState.level); + world = _world + .MintAsset(new ActionContext(), _myAgentState.address, fee) + .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); + // with not enough assets in discount period. + Assert.Throws(() => Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); + } - private IWorld Execute( - IWorld world, - Address signer, - long blockIndex, - int randomSeed, - Address avatarAddr, - int championshipId, - int round, - List costumes, - List equipments, - List runeInfos) - { - var action = new JoinArena + [Fact] + public void Execute_NotEnoughMedalException() { - avatarAddress = avatarAddr, - championshipId = championshipId, - round = round, - costumes = costumes, - equipments = equipments, - runeInfos = runeInfos, - }; - world = action.Execute(new ActionContext + var row = _tableSheets.ArenaSheet.OrderedList!.First(e => + e.Round.Any(e2 => + e2.ArenaType == ArenaType.Championship && + e2.RequiredMedalCount > 0)); + Assert.True(row.TryGetChampionshipRound(out var roundData)); + var blockIndex = roundData.StartBlockIndex; + var fee = ArenaHelper.GetEntranceFee( + roundData, + blockIndex, + _myAvatarState.level); + var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); + Assert.Throws(() => Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); + } + + private IWorld Execute( + IWorld world, + Address signer, + long blockIndex, + int randomSeed, + Address avatarAddr, + int championshipId, + int round, + List costumes, + List equipments, + List runeInfos) { - PreviousState = world, - Signer = signer, - BlockIndex = blockIndex, - RandomSeed = randomSeed, - }); + var action = new JoinArena + { + avatarAddress = avatarAddr, + championshipId = championshipId, + round = round, + costumes = costumes, + equipments = equipments, + runeInfos = runeInfos, + }; + world = action.Execute(new ActionContext + { + PreviousState = world, + Signer = signer, + BlockIndex = blockIndex, + RandomSeed = randomSeed, + }); - // check ItemSlotState - var itemSlotState = new ItemSlotState(BattleType.Arena); - itemSlotState.UpdateCostumes(costumes); - itemSlotState.UpdateEquipment(equipments); - var itemSlotStateAddr = ItemSlotState.DeriveAddress(avatarAddr, BattleType.Arena); - Assert.Equal(itemSlotState.Serialize(), world.GetLegacyState(itemSlotStateAddr)); + // check ItemSlotState + var itemSlotState = new ItemSlotState(BattleType.Arena); + itemSlotState.UpdateCostumes(costumes); + itemSlotState.UpdateEquipment(equipments); + var itemSlotStateAddr = ItemSlotState.DeriveAddress(avatarAddr, BattleType.Arena); + Assert.Equal(itemSlotState.Serialize(), world.GetLegacyState(itemSlotStateAddr)); - // check RuneSlotState - var runeSlotState = new RuneSlotState(BattleType.Arena); - runeSlotState.UpdateSlot(runeInfos, _tableSheets.RuneListSheet); - var runeSlotStateAddr = RuneSlotState.DeriveAddress(avatarAddr, BattleType.Arena); - Assert.Equal(runeSlotState.Serialize(), world.GetLegacyState(runeSlotStateAddr)); + // check RuneSlotState + var runeSlotState = new RuneSlotState(BattleType.Arena); + runeSlotState.UpdateSlot(runeInfos, _tableSheets.RuneListSheet); + var runeSlotStateAddr = RuneSlotState.DeriveAddress(avatarAddr, BattleType.Arena); + Assert.Equal(runeSlotState.Serialize(), world.GetLegacyState(runeSlotStateAddr)); - // check ArenaParticipant - var avatarState = world.GetAvatarState(avatarAddr); - var arenaParticipant = world.GetArenaParticipant(championshipId, round, avatarAddr); - Assert.NotNull(arenaParticipant); - Assert.Equal(avatarAddr, arenaParticipant.AvatarAddr); - Assert.Equal(avatarState.name, arenaParticipant.Name); - Assert.Equal(avatarState.GetPortraitId(), arenaParticipant.PortraitId); - Assert.Equal(avatarState.level, arenaParticipant.Level); - // Assert.Equal(cp, arenaParticipant.Cp); - Assert.Equal(ArenaParticipant.DefaultScore, arenaParticipant.Score); - Assert.Equal(ArenaParticipant.MaxTicketCount, arenaParticipant.Ticket); - Assert.Equal(0, arenaParticipant.TicketResetCount); - Assert.Equal(0, arenaParticipant.PurchasedTicketCount); - Assert.Equal(0, arenaParticipant.Win); - Assert.Equal(0, arenaParticipant.Lose); - Assert.Equal(0, arenaParticipant.LastBattleBlockIndex); + // check ArenaParticipant + var avatarState = world.GetAvatarState(avatarAddr); + var arenaParticipant = world.GetArenaParticipant(championshipId, round, avatarAddr); + Assert.NotNull(arenaParticipant); + Assert.Equal(avatarAddr, arenaParticipant.AvatarAddr); + Assert.Equal(avatarState.name, arenaParticipant.Name); + Assert.Equal(avatarState.GetPortraitId(), arenaParticipant.PortraitId); + Assert.Equal(avatarState.level, arenaParticipant.Level); + // Assert.Equal(cp, arenaParticipant.Cp); + Assert.Equal(ArenaParticipant.DefaultScore, arenaParticipant.Score); + Assert.Equal(ArenaParticipant.MaxTicketCount, arenaParticipant.Ticket); + Assert.Equal(0, arenaParticipant.TicketResetCount); + Assert.Equal(0, arenaParticipant.PurchasedTicketCount); + Assert.Equal(0, arenaParticipant.Win); + Assert.Equal(0, arenaParticipant.Lose); + Assert.Equal(0, arenaParticipant.LastBattleBlockIndex); - // check ArenaParticipants - var arenaParticipantsAdr = ArenaParticipants.DeriveAddress(championshipId, round); - var arenaParticipants = world.GetArenaParticipants(arenaParticipantsAdr, championshipId, round); - Assert.Equal(arenaParticipantsAdr, arenaParticipants.Address); - Assert.Contains(avatarAddr, arenaParticipants.AvatarAddresses); + // check ArenaParticipants + var arenaParticipantsAdr = ArenaParticipants.DeriveAddress(championshipId, round); + var arenaParticipants = world.GetArenaParticipants(arenaParticipantsAdr, championshipId, round); + Assert.Equal(arenaParticipantsAdr, arenaParticipants.Address); + Assert.Contains(avatarAddr, arenaParticipants.AvatarAddresses); - // check ArenaScore - var arenaScoreAdr = ArenaScore.DeriveAddress(avatarAddr, championshipId, round); - Assert.True(world.TryGetArenaScore(arenaScoreAdr, out var arenaScore)); - Assert.Equal(ArenaScore.ArenaScoreDefault, arenaScore.Score); + // check ArenaScore + var arenaScoreAdr = ArenaScore.DeriveAddress(avatarAddr, championshipId, round); + Assert.True(world.TryGetArenaScore(arenaScoreAdr, out var arenaScore)); + Assert.Equal(ArenaScore.ArenaScoreDefault, arenaScore.Score); - // check ArenaInformation - var arenaInformationAdr = ArenaInformation.DeriveAddress(avatarAddr, championshipId, round); - Assert.True(world.TryGetArenaInformation(arenaInformationAdr, out var arenaInformation)); - Assert.Equal(arenaInformationAdr, arenaInformation.Address); - Assert.Equal(0, arenaInformation.Win); - Assert.Equal(0, arenaInformation.Lose); - Assert.Equal(ArenaInformation.MaxTicketCount, arenaInformation.Ticket); - Assert.Equal(0, arenaInformation.TicketResetCount); - Assert.Equal(0, arenaInformation.PurchasedTicketCount); + // check ArenaInformation + var arenaInformationAdr = ArenaInformation.DeriveAddress(avatarAddr, championshipId, round); + Assert.True(world.TryGetArenaInformation(arenaInformationAdr, out var arenaInformation)); + Assert.Equal(arenaInformationAdr, arenaInformation.Address); + Assert.Equal(0, arenaInformation.Win); + Assert.Equal(0, arenaInformation.Lose); + Assert.Equal(ArenaInformation.MaxTicketCount, arenaInformation.Ticket); + Assert.Equal(0, arenaInformation.TicketResetCount); + Assert.Equal(0, arenaInformation.PurchasedTicketCount); - // check ArenaAvatarState - var arenaAvatarStateAddr = ArenaAvatarState.DeriveAddress(avatarAddr); - var arenaAvatarState = new ArenaAvatarState(avatarState); - arenaAvatarState.UpdateCostumes(costumes); - arenaAvatarState.UpdateEquipment(equipments); - Assert.True(world.TryGetLegacyState(arenaAvatarStateAddr, out IValue arenaAvatarStateInWorld)); - Assert.Equal(arenaAvatarState.Serialize(), arenaAvatarStateInWorld); + // check ArenaAvatarState + var arenaAvatarStateAddr = ArenaAvatarState.DeriveAddress(avatarAddr); + var arenaAvatarState = new ArenaAvatarState(avatarState); + arenaAvatarState.UpdateCostumes(costumes); + arenaAvatarState.UpdateEquipment(equipments); + Assert.True(world.TryGetLegacyState(arenaAvatarStateAddr, out IValue arenaAvatarStateInWorld)); + Assert.Equal(arenaAvatarState.Serialize(), arenaAvatarStateInWorld); - return world; + return world; + } } } diff --git a/.Lib9c.Tests/Action/MarketValidationTest.cs b/.Lib9c.Tests/Action/MarketValidationTest.cs index 2c367db871..08cad89b21 100644 --- a/.Lib9c.Tests/Action/MarketValidationTest.cs +++ b/.Lib9c.Tests/Action/MarketValidationTest.cs @@ -16,9 +16,9 @@ namespace Lib9c.Tests.Action public class MarketValidationTest { - private static readonly Address AgentAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); - private static readonly Address AvatarAddress = new Address("47d082a115c63e7b58b1532d20e631538eafadde"); - private static readonly Currency Gold = Currency.Legacy("NCG", 2, minters: null); + private static readonly Address AgentAddress = new ("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); + private static readonly Address AvatarAddress = new ("47d082a115c63e7b58b1532d20e631538eafadde"); + private static readonly Currency Gold = Currency.Legacy("NCG", 2, null); private readonly IWorld _initialState; @@ -207,7 +207,7 @@ public void Validate_RegisterInfo(params RegisterInfosMember[] validateMembers) var registerProduct = new RegisterProduct { AvatarAddress = AvatarAddress, - RegisterInfos = new[] { registerInfo }, + RegisterInfos = new[] { registerInfo, }, }; Assert.Throws(validateMember.Exc, () => registerProduct.Execute(actionContext)); @@ -241,7 +241,7 @@ public void Validate_ProductInfo(params ProductInfosMember[] validateMembers) var buyProduct = new BuyProduct { AvatarAddress = AvatarAddress, - ProductInfos = new[] { productInfo }, + ProductInfos = new[] { productInfo, }, }; Assert.Throws(validateMember.Exc, () => buyProduct.Execute(actionContext)); @@ -249,7 +249,7 @@ public void Validate_ProductInfo(params ProductInfosMember[] validateMembers) var cancelRegister = new CancelProductRegistration { AvatarAddress = AvatarAddress, - ProductInfos = new List() { productInfo }, + ProductInfos = new List() { productInfo, }, }; Assert.Throws(validateMember.Exc, () => cancelRegister.Execute(actionContext)); diff --git a/.Lib9c.Tests/Action/MigrateFeeTest.cs b/.Lib9c.Tests/Action/MigrateFeeTest.cs index 68607b0159..56f4f946b4 100644 --- a/.Lib9c.Tests/Action/MigrateFeeTest.cs +++ b/.Lib9c.Tests/Action/MigrateFeeTest.cs @@ -1,137 +1,138 @@ -namespace Lib9c.Tests.Action; - -using System.Collections.Generic; -using System.Globalization; -using System.Numerics; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Libplanet.Mocks; -using Libplanet.Types.Assets; -using Nekoyume.Action; -using Nekoyume.Model.State; -using Nekoyume.Module; -using Xunit; - -public class MigrateFeeTest +namespace Lib9c.Tests.Action { - private readonly Currency _ncgCurrency; - - public MigrateFeeTest() + using System.Collections.Generic; + using System.Globalization; + using System.Numerics; + using Libplanet.Action.State; + using Libplanet.Crypto; + using Libplanet.Mocks; + using Libplanet.Types.Assets; + using Nekoyume.Action; + using Nekoyume.Model.State; + using Nekoyume.Module; + using Xunit; + + public class MigrateFeeTest { -#pragma warning disable CS0618 - _ncgCurrency = Currency.Legacy("NCG", 2, null); -#pragma warning restore CS0618 - } + private readonly Currency _ncgCurrency; - [Fact] - public void Execute() - { - var admin = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); - var context = new ActionContext(); - var state = new World(MockUtil.MockModernWorldState) - .SetLegacyState(AdminState.Address, new AdminState(admin, 100).Serialize()) - .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(_ncgCurrency).Serialize()); - var recipient = new PrivateKey().Address; - var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); - var amount = FungibleAssetValue.Parse(_ncgCurrency, 0.1m.ToString(CultureInfo.InvariantCulture)); - for (int i = 1; i < 10; i++) + public MigrateFeeTest() { - var address = new PrivateKey().Address; - var balance = 0.1m * i; - var fav = FungibleAssetValue.Parse(_ncgCurrency, balance.ToString(CultureInfo.InvariantCulture)); - state = state.MintAsset(context, address, fav); - transferData.Add((address, recipient, amount.RawValue)); - } - - var action = new MigrateFee - { - TransferData = transferData, - Memo = "memo", - }; - - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = state, - RandomSeed = 0, - Signer = admin, - }); - - foreach (var (sender, _, _) in transferData) - { - var prevBalance = state.GetBalance(sender, _ncgCurrency); - Assert.Equal(prevBalance - amount, nextState.GetBalance(sender, _ncgCurrency)); +#pragma warning disable CS0618 + _ncgCurrency = Currency.Legacy("NCG", 2, null); +#pragma warning restore CS0618 } - Assert.Equal(FungibleAssetValue.Parse(_ncgCurrency, "0.9"), nextState.GetBalance(recipient, _ncgCurrency)); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PlainValue(bool memo) - { - var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); - // 0.9 - // 1.0 - // 1.1 - for (int i = 9; i < 12; i++) + [Fact] + public void Execute() { - var sender = new PrivateKey().Address; + var admin = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); + var context = new ActionContext(); + var state = new World(MockUtil.MockModernWorldState) + .SetLegacyState(AdminState.Address, new AdminState(admin, 100).Serialize()) + .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(_ncgCurrency).Serialize()); var recipient = new PrivateKey().Address; - var amount = FungibleAssetValue.Parse(_ncgCurrency, (0.1m * i).ToString(CultureInfo.InvariantCulture)); - transferData.Add((sender, recipient, amount.RawValue)); + var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); + var amount = FungibleAssetValue.Parse(_ncgCurrency, 0.1m.ToString(CultureInfo.InvariantCulture)); + for (var i = 1; i < 10; i++) + { + var address = new PrivateKey().Address; + var balance = 0.1m * i; + var fav = FungibleAssetValue.Parse(_ncgCurrency, balance.ToString(CultureInfo.InvariantCulture)); + state = state.MintAsset(context, address, fav); + transferData.Add((address, recipient, amount.RawValue)); + } + + var action = new MigrateFee + { + TransferData = transferData, + Memo = "memo", + }; + + var nextState = action.Execute(new ActionContext + { + BlockIndex = 1L, + PreviousState = state, + RandomSeed = 0, + Signer = admin, + }); + + foreach (var (sender, _, _) in transferData) + { + var prevBalance = state.GetBalance(sender, _ncgCurrency); + Assert.Equal(prevBalance - amount, nextState.GetBalance(sender, _ncgCurrency)); + } + + Assert.Equal(FungibleAssetValue.Parse(_ncgCurrency, "0.9"), nextState.GetBalance(recipient, _ncgCurrency)); } - var action = new MigrateFee + [Theory] + [InlineData(true)] + [InlineData(false)] + public void PlainValue(bool memo) { - TransferData = transferData, - Memo = memo ? "memo" : null, - }; - - var des = new MigrateFee(); - des.LoadPlainValue(action.PlainValue); - - for (int i = 0; i < action.TransferData.Count; i++) - { - var data = action.TransferData[i]; - Assert.Equal(des.TransferData[i].sender, data.sender); - Assert.Equal(des.TransferData[i].recipient, data.recipient); - Assert.Equal(des.TransferData[i].amount, data.amount); + var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); + // 0.9 + // 1.0 + // 1.1 + for (var i = 9; i < 12; i++) + { + var sender = new PrivateKey().Address; + var recipient = new PrivateKey().Address; + var amount = FungibleAssetValue.Parse(_ncgCurrency, (0.1m * i).ToString(CultureInfo.InvariantCulture)); + transferData.Add((sender, recipient, amount.RawValue)); + } + + var action = new MigrateFee + { + TransferData = transferData, + Memo = memo ? "memo" : null, + }; + + var des = new MigrateFee(); + des.LoadPlainValue(action.PlainValue); + + for (var i = 0; i < action.TransferData.Count; i++) + { + var data = action.TransferData[i]; + Assert.Equal(des.TransferData[i].sender, data.sender); + Assert.Equal(des.TransferData[i].recipient, data.recipient); + Assert.Equal(des.TransferData[i].amount, data.amount); + } + + Assert.Equal(memo, !string.IsNullOrEmpty(des.Memo)); } - Assert.Equal(memo, !string.IsNullOrEmpty(des.Memo)); - } - - [Fact] - public void Execute_Throw_InsufficientBalanceException() - { - var admin = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); - var context = new ActionContext(); - var state = new World(MockUtil.MockModernWorldState) - .SetLegacyState(AdminState.Address, new AdminState(admin, 100).Serialize()) - .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(_ncgCurrency).Serialize()); - var recipient = new PrivateKey().Address; - var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); - var amount = 1 * _ncgCurrency; - var address = new PrivateKey().Address; - var balance = 0.1m; - var fav = FungibleAssetValue.Parse(_ncgCurrency, balance.ToString(CultureInfo.InvariantCulture)); - state = state.MintAsset(context, address, fav); - transferData.Add((address, recipient, amount.RawValue)); - - var action = new MigrateFee + [Fact] + public void Execute_Throw_InsufficientBalanceException() { - TransferData = transferData, - Memo = "memo", - }; + var admin = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); + var context = new ActionContext(); + var state = new World(MockUtil.MockModernWorldState) + .SetLegacyState(AdminState.Address, new AdminState(admin, 100).Serialize()) + .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(_ncgCurrency).Serialize()); + var recipient = new PrivateKey().Address; + var transferData = new List<(Address sender, Address recipient, BigInteger amount)>(); + var amount = 1 * _ncgCurrency; + var address = new PrivateKey().Address; + var balance = 0.1m; + var fav = FungibleAssetValue.Parse(_ncgCurrency, balance.ToString(CultureInfo.InvariantCulture)); + state = state.MintAsset(context, address, fav); + transferData.Add((address, recipient, amount.RawValue)); - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = state, - RandomSeed = 0, - Signer = admin, - })); + var action = new MigrateFee + { + TransferData = transferData, + Memo = "memo", + }; + + Assert.Throws(() => action.Execute(new ActionContext + { + BlockIndex = 1L, + PreviousState = state, + RandomSeed = 0, + Signer = admin, + })); + } } } diff --git a/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs b/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs index 838f889080..ec24c0c5f2 100644 --- a/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs +++ b/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs @@ -33,7 +33,7 @@ public MigrateMonsterCollectionTest(ITestOutputHelper outputHelper) _signer = default; _avatarAddress = _signer.Derive("avatar"); _state = new World(MockUtil.MockModernWorldState); - Dictionary sheets = TableSheetsImporter.ImportSheets(); + var sheets = TableSheetsImporter.ImportSheets(); var tableSheets = new TableSheets(sheets); var rankingMapAddress = new PrivateKey().Address; var agentState = new AgentState(_signer); @@ -56,7 +56,7 @@ public MigrateMonsterCollectionTest(ITestOutputHelper outputHelper) .SetAvatarState(_avatarAddress, avatarState) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((string key, string value) in sheets) + foreach ((var key, var value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -66,14 +66,14 @@ public MigrateMonsterCollectionTest(ITestOutputHelper outputHelper) [Fact] public void Execute_ThrowsIfAlreadyStakeStateExists() { - Address monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); + var monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); var monsterCollectionState = new MonsterCollectionState( monsterCollectionAddress, 1, 0); - Address stakeStateAddress = StakeState.DeriveAddress(_signer); + var stakeStateAddress = StakeState.DeriveAddress(_signer); var states = _state.SetLegacyState( stakeStateAddress, new StakeState(stakeStateAddress, 0).SerializeV2()) .SetLegacyState(monsterCollectionAddress, monsterCollectionState.Serialize()); - MigrateMonsterCollection action = new MigrateMonsterCollection(_avatarAddress); + var action = new MigrateMonsterCollection(_avatarAddress); Assert.Throws(() => action.Execute(new ActionContext { PreviousState = states, @@ -86,7 +86,7 @@ public void Execute_ThrowsIfAlreadyStakeStateExists() [Fact] public void Execute_After_V100220ObsoleteIndex() { - Address monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); + var monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); var monsterCollectionState = new MonsterCollectionState( monsterCollectionAddress, 1, ActionObsoleteConfig.V100220ObsoleteIndex - MonsterCollectionState.RewardInterval); var currency = _state.GetGoldCurrency(); @@ -94,7 +94,7 @@ public void Execute_After_V100220ObsoleteIndex() var states = _state .SetLegacyState(monsterCollectionAddress, monsterCollectionState.Serialize()) .MintAsset(context, monsterCollectionAddress, currency * 100); - MigrateMonsterCollection action = new MigrateMonsterCollection(_avatarAddress); + var action = new MigrateMonsterCollection(_avatarAddress); states = action.Execute(new ActionContext { PreviousState = states, @@ -106,7 +106,7 @@ public void Execute_After_V100220ObsoleteIndex() Assert.True(states.TryGetAvatarState( _signer, _avatarAddress, - out AvatarState avatarState)); + out var avatarState)); Assert.Equal(80, avatarState.inventory.Items.First(item => item.item.Id == 400000).count); Assert.Equal(1, avatarState.inventory.Items.First(item => item.item.Id == 500000).count); @@ -116,9 +116,9 @@ public void Execute_After_V100220ObsoleteIndex() [ClassData(typeof(ExecuteFixture))] public void Execute(int collectionLevel, long claimBlockIndex, long receivedBlockIndex, long stakedAmount, (int ItemId, int Quantity)[] expectedItems) { - Address collectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); + var collectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); var monsterCollectionState = new MonsterCollectionState(collectionAddress, collectionLevel, 0); - Currency currency = _state.GetGoldCurrency(); + var currency = _state.GetGoldCurrency(); var context = new ActionContext(); var states = _state @@ -129,7 +129,7 @@ public void Execute(int collectionLevel, long claimBlockIndex, long receivedBloc Assert.Equal(0 * currency, states.GetBalance(_signer, currency)); Assert.Equal(stakedAmount * currency, states.GetBalance(collectionAddress, currency)); - MigrateMonsterCollection action = new MigrateMonsterCollection(_avatarAddress); + var action = new MigrateMonsterCollection(_avatarAddress); states = action.Execute(new ActionContext { PreviousState = states, @@ -138,7 +138,7 @@ public void Execute(int collectionLevel, long claimBlockIndex, long receivedBloc RandomSeed = 0, }); - Assert.True(states.TryGetStakeState(_signer, out StakeState stakeState)); + Assert.True(states.TryGetStakeState(_signer, out var stakeState)); Assert.Equal( 0 * currency, states.GetBalance(monsterCollectionState.address, currency)); @@ -149,7 +149,7 @@ public void Execute(int collectionLevel, long claimBlockIndex, long receivedBloc states.TryGetAvatarState( _signer, _avatarAddress, - out AvatarState avatarState)); + out var avatarState)); foreach (var (itemId, quantity) in expectedItems) { Assert.True(avatarState.inventory.HasItem(itemId, quantity)); @@ -167,7 +167,7 @@ public void Serialization() private class ExecuteFixture : IEnumerable { - private readonly List _data = new List + private readonly List _data = new() { new object[] { @@ -257,7 +257,7 @@ private class ExecuteFixture : IEnumerable { 7, MonsterCollectionState.RewardInterval - 1, - 0, // Because it cannot claim rewards. + 0, // Because it cannot claim rewards. 2313500, new (int, int)[] { @@ -267,9 +267,15 @@ private class ExecuteFixture : IEnumerable }, }; - public IEnumerator GetEnumerator() => _data.GetEnumerator(); + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => _data.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return _data.GetEnumerator(); + } } } } diff --git a/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs b/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs index f131917863..3b908c059c 100644 --- a/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs +++ b/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs @@ -16,7 +16,7 @@ public class MigrationActivatedAccountsStateTest [Fact] public void Execute() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var admin = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(AdminState.Address, new AdminState(admin, 100).Serialize()) @@ -24,7 +24,7 @@ public void Execute() var action = new MigrationActivatedAccountsState(); - IWorld nextState = action.Execute(new ActionContext() + var nextState = action.Execute(new ActionContext() { PreviousState = state, Signer = admin, diff --git a/.Lib9c.Tests/Action/MintAssetsTest.cs b/.Lib9c.Tests/Action/MintAssetsTest.cs index d1f8b54d76..4912009be8 100644 --- a/.Lib9c.Tests/Action/MintAssetsTest.cs +++ b/.Lib9c.Tests/Action/MintAssetsTest.cs @@ -127,7 +127,7 @@ public void Execute_With_FungibleAssetValue() }, null ); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = _prevState, @@ -149,8 +149,8 @@ public void Execute_With_FungibleAssetValue() [Fact] public void Execute_With_FungibleItemValue() { - IWorld prevState = GenerateAvatar(_prevState, out Address avatarAddress); - HashDigest fungibleId = HashDigest.FromString( + var prevState = GenerateAvatar(_prevState, out var avatarAddress); + var fungibleId = HashDigest.FromString( "7f5d25371e58c0f3d5a33511450f73c2e0fa4fac32a92e1cbe64d3bf2fef6328" ); @@ -165,7 +165,7 @@ public void Execute_With_FungibleItemValue() }, "Execute_With_FungibleItemValue" ); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, @@ -180,15 +180,15 @@ public void Execute_With_FungibleItemValue() var avatarState = nextState.GetAvatarState(avatarAddress); Assert.Single(avatarState.mailBox); var mail = Assert.IsType(avatarState.mailBox.First()); - Assert.Equal(new[] { (fungibleId, 42) }, mail.FungibleIdAndCounts); + Assert.Equal(new[] { (fungibleId, 42), }, mail.FungibleIdAndCounts); Assert.Equal(action.Memo, mail.Memo); } [Fact] public void Execute_With_Mixed() { - IWorld prevState = GenerateAvatar(_prevState, out Address avatarAddress); - HashDigest fungibleId = HashDigest.FromString( + var prevState = GenerateAvatar(_prevState, out var avatarAddress); + var fungibleId = HashDigest.FromString( "7f5d25371e58c0f3d5a33511450f73c2e0fa4fac32a92e1cbe64d3bf2fef6328" ); @@ -209,7 +209,7 @@ public void Execute_With_Mixed() }, "Execute_With_FungibleItemValue" ); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, @@ -224,8 +224,8 @@ public void Execute_With_Mixed() var avatarState = nextState.GetAvatarState(avatarAddress); Assert.Single(avatarState.mailBox); var mail = Assert.IsType(avatarState.mailBox.First()); - Assert.Equal(new[] { (fungibleId, 42) }, mail.FungibleIdAndCounts); - Assert.Equal(new[] { (avatarAddress, Currencies.StakeRune * 123) }, mail.FungibleAssetValues); + Assert.Equal(new[] { (fungibleId, 42), }, mail.FungibleIdAndCounts); + Assert.Equal(new[] { (avatarAddress, Currencies.StakeRune * 123), }, mail.FungibleAssetValues); Assert.Equal(action.Memo, mail.Memo); } @@ -252,7 +252,7 @@ public void Execute_Throws_InvalidMinterException() ); // Allows minters - foreach (Address m in _minters) + foreach (var m in _minters) { _ = action.Execute( new ActionContext() @@ -285,8 +285,8 @@ public void Execute_Crystal() action.LoadPlainValue(a); var address = action.MintSpecs!.First().Recipient; var avatarAddress = action.MintSpecs.Last().Recipient; - IWorld prevState = GenerateAvatar(_prevState, address, avatarAddress); - IWorld nextState = action.Execute( + var prevState = GenerateAvatar(_prevState, address, avatarAddress); + var nextState = action.Execute( new ActionContext() { PreviousState = prevState, diff --git a/.Lib9c.Tests/Action/PatchTableSheetTest.cs b/.Lib9c.Tests/Action/PatchTableSheetTest.cs index 28f8a63912..748c0bc0d1 100644 --- a/.Lib9c.Tests/Action/PatchTableSheetTest.cs +++ b/.Lib9c.Tests/Action/PatchTableSheetTest.cs @@ -126,7 +126,7 @@ public void CheckPermission() TableCsv = "New Value", }; - PolicyExpiredException exc1 = Assert.Throws(() => + var exc1 = Assert.Throws(() => { action.Execute( new ActionContext() @@ -139,7 +139,7 @@ public void CheckPermission() }); Assert.Equal(101, exc1.BlockIndex); - PermissionDeniedException exc2 = Assert.Throws(() => + var exc2 = Assert.Throws(() => { action.Execute( new ActionContext() diff --git a/.Lib9c.Tests/Action/PetEnhancement0Test.cs b/.Lib9c.Tests/Action/PetEnhancement0Test.cs index f909ef1479..b8ca0881c8 100644 --- a/.Lib9c.Tests/Action/PetEnhancement0Test.cs +++ b/.Lib9c.Tests/Action/PetEnhancement0Test.cs @@ -183,7 +183,7 @@ public void Execute_Throw_NotEnoughFungibleAssetValueException( _targetPetId, currentPetLevel, targetPetLevel, - mintAssets: false)); + false)); } private static IWorld Execute( @@ -214,7 +214,7 @@ private static IWorld Execute( var ncgCurrency = prevStates.GetGoldCurrency(); var petSheet = prevStates.GetSheet(); Assert.True(petSheet.TryGetValue(petId, out var petRow)); - var soulStoneCurrency = Currency.Legacy(petRow.SoulStoneTicker, 0, minters: null); + var soulStoneCurrency = Currency.Legacy(petRow.SoulStoneTicker, 0, null); if (mintAssets && // NOTE: If the currentPetLevel does not less than targetPetLevel, // ArgumentOutOfRangeException will be thrown. diff --git a/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs b/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs index ce2b205f36..a1208b49b3 100644 --- a/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs +++ b/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs @@ -38,7 +38,7 @@ public void Execute(bool admin, bool includeNcg, Type exc) #pragma warning restore CS0618 } - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(Addresses.Admin, adminState.Serialize()); var action = new PrepareRewardAssets(poolAddress, assets); diff --git a/.Lib9c.Tests/Action/PurchaseInfoTest.cs b/.Lib9c.Tests/Action/PurchaseInfoTest.cs index 9f15a8dafd..d8bd49be24 100644 --- a/.Lib9c.Tests/Action/PurchaseInfoTest.cs +++ b/.Lib9c.Tests/Action/PurchaseInfoTest.cs @@ -30,7 +30,7 @@ public void Serialize() price ); - Dictionary serialized = (Dictionary)purchaseInfo.Serialize(); + var serialized = (Dictionary)purchaseInfo.Serialize(); Assert.Equal(purchaseInfo, new PurchaseInfo(serialized)); diff --git a/.Lib9c.Tests/Action/RaidTest.cs b/.Lib9c.Tests/Action/RaidTest.cs index 5526cb0cfe..51aab04f26 100644 --- a/.Lib9c.Tests/Action/RaidTest.cs +++ b/.Lib9c.Tests/Action/RaidTest.cs @@ -116,21 +116,21 @@ int runeId2 FoodIds = new List(), RuneInfos = new List() { - new RuneSlotInfo(slotIndex, runeId), - new RuneSlotInfo(slotIndex2, runeId2), + new (slotIndex, runeId), + new (slotIndex2, runeId2), }, PayNcg = payNcg, }; - Currency crystal = CrystalCalculator.CRYSTAL; - int raidId = _tableSheets.WorldBossListSheet.FindRaidIdByBlockIndex(blockIndex); - Address raiderAddress = Addresses.GetRaiderAddress(_avatarAddress, raidId); + var crystal = CrystalCalculator.CRYSTAL; + var raidId = _tableSheets.WorldBossListSheet.FindRaidIdByBlockIndex(blockIndex); + var raiderAddress = Addresses.GetRaiderAddress(_avatarAddress, raidId); var goldCurrencyState = new GoldCurrencyState(_goldCurrency); - WorldBossListSheet.Row worldBossRow = _tableSheets.WorldBossListSheet.FindRowByBlockIndex(blockIndex); + var worldBossRow = _tableSheets.WorldBossListSheet.FindRowByBlockIndex(blockIndex); var hpSheet = _tableSheets.WorldBossGlobalHpSheet; - Address bossAddress = Addresses.GetWorldBossAddress(raidId); - Address worldBossKillRewardRecordAddress = Addresses.GetWorldBossKillRewardRecordAddress(_avatarAddress, raidId); - Address raiderListAddress = Addresses.GetRaiderListAddress(raidId); - int level = 1; + var bossAddress = Addresses.GetWorldBossAddress(raidId); + var worldBossKillRewardRecordAddress = Addresses.GetWorldBossKillRewardRecordAddress(_avatarAddress, raidId); + var raiderListAddress = Addresses.GetRaiderListAddress(raidId); + var level = 1; if (kill & !levelUp) { level = hpSheet.OrderedList.Last().Level; @@ -139,7 +139,7 @@ int runeId2 var fee = _tableSheets.WorldBossListSheet[raidId].EntranceFee; var context = new ActionContext(); - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) .SetAgentState(_agentAddress, new AgentState(_agentAddress)); @@ -167,7 +167,7 @@ int runeId2 if (stageCleared) { - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -231,10 +231,10 @@ int runeId2 { var bossState = new WorldBossState(worldBossRow, _tableSheets.WorldBossGlobalHpSheet[level]) - { - CurrentHp = 0, - Level = level, - }; + { + CurrentHp = 0, + Level = level, + }; state = state.SetLegacyState(bossAddress, bossState.Serialize()); } @@ -266,7 +266,7 @@ int runeId2 new List(), _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet - ); + ); simulator.Simulate(); var score = simulator.DamageDealt; @@ -292,7 +292,7 @@ int runeId2 var bossRow = raidSimulatorSheets.WorldBossCharacterSheet[bossListRow.BossId]; Assert.True(state.TryGetLegacyState(bossAddress, out List prevRawBoss)); var prevBossState = new WorldBossState(prevRawBoss); - int rank = WorldBossHelper.CalculateRank(bossRow, raiderStateExist ? 1_000 : 0); + var rank = WorldBossHelper.CalculateRank(bossRow, raiderStateExist ? 1_000 : 0); var rewards = WorldBossHelper.CalculateReward( rank, prevBossState.Id, @@ -355,9 +355,9 @@ int runeId2 Assert.True(nextState.TryGetLegacyState(raiderAddress, out List rawRaider)); var raiderState = new RaiderState(rawRaider); - long expectedTotalScore = raiderStateExist ? 1_000 + score : score; - int expectedRemainChallenge = payNcg ? 0 : 2; - int expectedTotalChallenge = raiderStateExist ? 2 : 1; + var expectedTotalScore = raiderStateExist ? 1_000 + score : score; + var expectedRemainChallenge = payNcg ? 0 : 2; + var expectedTotalChallenge = raiderStateExist ? 2 : 1; Assert.Equal(score, raiderState.HighScore); Assert.Equal(expectedTotalScore, raiderState.TotalScore); @@ -369,7 +369,7 @@ int runeId2 Assert.True(nextState.TryGetLegacyState(bossAddress, out List rawBoss)); var bossState = new WorldBossState(rawBoss); - int expectedLevel = level; + var expectedLevel = level; if (kill & levelUp) { expectedLevel++; @@ -412,7 +412,7 @@ int runeId2 } Assert.True(nextState.TryGetLegacyState(raiderListAddress, out List rawRaiderList)); - List
raiderList = rawRaiderList.ToList(StateExtensions.ToAddress); + var raiderList = rawRaiderList.ToList(StateExtensions.ToAddress); Assert.Contains(raiderAddress, raiderList); } @@ -462,13 +462,13 @@ public void Execute_With_Reward() }; var worldBossRow = _tableSheets.WorldBossListSheet.First().Value; - int raidId = worldBossRow.Id; - Address raiderAddress = Addresses.GetRaiderAddress(_avatarAddress, raidId); + var raidId = worldBossRow.Id; + var raiderAddress = Addresses.GetRaiderAddress(_avatarAddress, raidId); var goldCurrencyState = new GoldCurrencyState(_goldCurrency); - Address bossAddress = Addresses.GetWorldBossAddress(raidId); - Address worldBossKillRewardRecordAddress = Addresses.GetWorldBossKillRewardRecordAddress(_avatarAddress, raidId); + var bossAddress = Addresses.GetWorldBossAddress(raidId); + var worldBossKillRewardRecordAddress = Addresses.GetWorldBossKillRewardRecordAddress(_avatarAddress, raidId); - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) .SetAgentState(_agentAddress, new AgentState(_agentAddress)); @@ -486,7 +486,7 @@ public void Execute_With_Reward() default ); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -516,10 +516,10 @@ public void Execute_With_Reward() var bossState = new WorldBossState(worldBossRow, _tableSheets.WorldBossGlobalHpSheet[2]) - { - CurrentHp = 0, - Level = 2, - }; + { + CurrentHp = 0, + Level = 2, + }; state = state.SetLegacyState(bossAddress, bossState.Serialize()); var randomSeed = 0; var random = new TestRandom(randomSeed); @@ -536,7 +536,7 @@ public void Execute_With_Reward() new List(), _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet - ); + ); simulator.Simulate(); var rewardMap = new Dictionary(); @@ -642,14 +642,14 @@ public void Execute_With_Free_Crystal_Fee() RuneInfos = new List(), PayNcg = false, }; - Currency crystal = CrystalCalculator.CRYSTAL; + var crystal = CrystalCalculator.CRYSTAL; _sheets[nameof(WorldBossListSheet)] = "id,boss_id,started_block_index,ended_block_index,fee,ticket_price,additional_ticket_price,max_purchase_count\r\n" + "1,900002,0,100,0,1,1,40"; var goldCurrencyState = new GoldCurrencyState(_goldCurrency); - IWorld state = new World(MockUtil.MockModernWorldState) + var state = new World(MockUtil.MockModernWorldState) .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) .SetAgentState(_agentAddress, new AgentState(_agentAddress)); @@ -667,7 +667,7 @@ public void Execute_With_Free_Crystal_Fee() default ); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } diff --git a/.Lib9c.Tests/Action/RapidCombinationTest.cs b/.Lib9c.Tests/Action/RapidCombinationTest.cs index b929f4ffc6..347c1bf82e 100644 --- a/.Lib9c.Tests/Action/RapidCombinationTest.cs +++ b/.Lib9c.Tests/Action/RapidCombinationTest.cs @@ -141,7 +141,7 @@ public void Execute() var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; var nextState = action.Execute(new ActionContext @@ -259,7 +259,7 @@ public void Execute_Throw_CombinationSlotResultNullException() var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; Assert.Throws(() => action.Execute(new ActionContext @@ -314,7 +314,7 @@ public void Execute_Throw_RequiredBlockIndexException(int itemRequiredBlockIndex var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; Assert.Throws(() => action.Execute(new ActionContext @@ -343,12 +343,12 @@ public void Execute_Throw_NotEnoughMaterialException(int materialCount, int trad slotStateUnlockStage); var row = _tableSheets.MaterialItemSheet.Values.First(r => r.ItemSubType == ItemSubType.Hourglass); - avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), count: materialCount); + avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), materialCount); if (tradableCount > 0) { var material = ItemFactory.CreateTradableMaterial(row); material.RequiredBlockIndex = blockIndex; - avatarState.inventory.AddItem(material, count: tradableCount); + avatarState.inventory.AddItem(material, tradableCount); } var firstEquipmentRow = _tableSheets.EquipmentItemSheet.First; @@ -389,7 +389,7 @@ public void Execute_Throw_NotEnoughMaterialException(int materialCount, int trad var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; Assert.Throws(() => action.Execute(new ActionContext @@ -477,7 +477,7 @@ public void Execute_Throw_RequiredAppraiseBlockException() var row = _tableSheets.MaterialItemSheet.Values.First(r => r.ItemSubType == ItemSubType.Hourglass); - avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), count: 22); + avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), 22); var firstEquipmentRow = _tableSheets.EquipmentItemSheet.First; Assert.NotNull(firstEquipmentRow); @@ -517,7 +517,7 @@ public void Execute_Throw_RequiredAppraiseBlockException() var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; Assert.Throws(() => action.Execute(new ActionContext @@ -580,7 +580,7 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( { id = mailId, itemUsable = equipment, - materialItemIdList = new[] { materialEquipment.NonFungibleId }, + materialItemIdList = new[] { materialEquipment.NonFungibleId, }, }; break; @@ -602,7 +602,7 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( id = mailId, preItemUsable = preItemUsable, itemUsable = equipment, - materialItemIdList = new[] { materialEquipment.NonFungibleId }, + materialItemIdList = new[] { materialEquipment.NonFungibleId, }, gold = 0, actionPoint = 0, enhancementResult = ItemEnhancement9.EnhancementResult.GreatSuccess, @@ -627,7 +627,7 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( id = mailId, preItemUsable = preItemUsable, itemUsable = equipment, - materialItemIdList = new[] { materialEquipment.NonFungibleId }, + materialItemIdList = new[] { materialEquipment.NonFungibleId, }, gold = 0, actionPoint = 0, enhancementResult = ItemEnhancement10.EnhancementResult.GreatSuccess, @@ -652,7 +652,7 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( id = mailId, preItemUsable = preItemUsable, itemUsable = equipment, - materialItemIdList = new[] { materialEquipment.NonFungibleId }, + materialItemIdList = new[] { materialEquipment.NonFungibleId, }, gold = 0, actionPoint = 0, enhancementResult = ItemEnhancement11.EnhancementResult.GreatSuccess, @@ -685,7 +685,7 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( var action = new RapidCombination { avatarAddress = _avatarAddress, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; action.Execute(new ActionContext diff --git a/.Lib9c.Tests/Action/ReRegisterProductTest.cs b/.Lib9c.Tests/Action/ReRegisterProductTest.cs index c29c1df0e5..91c49c27cb 100644 --- a/.Lib9c.Tests/Action/ReRegisterProductTest.cs +++ b/.Lib9c.Tests/Action/ReRegisterProductTest.cs @@ -164,7 +164,7 @@ bool fromPreviousAction if (inventoryCount > 1) { - for (int i = 0; i < inventoryCount; i++) + for (var i = 0; i < inventoryCount; i++) { // Different RequiredBlockIndex for divide inventory slot. if (tradableItem is ITradableFungibleItem tradableFungibleItem) @@ -225,7 +225,7 @@ bool fromPreviousAction var action = new UpdateSell { sellerAvatarAddress = _avatarAddress, - updateSellInfos = new[] { updateSellInfo }, + updateSellInfos = new[] { updateSellInfo, }, }; var expectedState = action.Execute(new ActionContext @@ -314,7 +314,7 @@ public void Execute_Throw_ListEmptyException() public void Execute_Throw_ArgumentOutOfRangeException() { var reRegisterInfos = new List<(IProductInfo, IRegisterInfo)>(); - for (int i = 0; i < ReRegisterProduct.Capacity + 1; i++) + for (var i = 0; i < ReRegisterProduct.Capacity + 1; i++) { reRegisterInfos.Add((new ItemProductInfo(), new RegisterInfo())); } diff --git a/.Lib9c.Tests/Action/RedeemCodeTest.cs b/.Lib9c.Tests/Action/RedeemCodeTest.cs index feb8ff49d4..56f92de295 100644 --- a/.Lib9c.Tests/Action/RedeemCodeTest.cs +++ b/.Lib9c.Tests/Action/RedeemCodeTest.cs @@ -18,7 +18,7 @@ namespace Lib9c.Tests.Action public class RedeemCodeTest { - private readonly Address _agentAddress = new Address(new byte[] + private readonly Address _agentAddress = new (new byte[] { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -26,7 +26,7 @@ public class RedeemCodeTest 0x00, 0x00, 0x00, 0x00, 0x02, }); - private readonly Address _avatarAddress = new Address(new byte[] + private readonly Address _avatarAddress = new (new byte[] { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -47,10 +47,10 @@ public RedeemCodeTest() public void Execute() { var privateKey = new PrivateKey(); - PublicKey publicKey = privateKey.PublicKey; + var publicKey = privateKey.PublicKey; var prevRedeemCodesState = new RedeemCodeState(new Dictionary() { - [publicKey] = new Reward(1), + [publicKey] = new (1), }); var gameConfigState = new GameConfigState(); var agentState = new AgentState(_agentAddress); @@ -89,7 +89,7 @@ public void Execute() _avatarAddress ); - IWorld nextState = redeemCode.Execute(new ActionContext() + var nextState = redeemCode.Execute(new ActionContext() { BlockIndex = 1, Miner = default, @@ -99,18 +99,15 @@ public void Execute() }); // Check target avatar & agent - AvatarState nextAvatarState = nextState.GetAvatarState(_avatarAddress); + var nextAvatarState = nextState.GetAvatarState(_avatarAddress); // See also Data/TableCSV/RedeemRewardSheet.csv - ItemSheet itemSheet = initialState.GetItemSheet(); - HashSet expectedItems = new[] { 302006, 302004, 302001, 302002 }.ToHashSet(); + var itemSheet = initialState.GetItemSheet(); + var expectedItems = new[] { 302006, 302004, 302001, 302002, }.ToHashSet(); Assert.Subset(nextAvatarState.inventory.Items.Select(i => i.item.Id).ToHashSet(), expectedItems); // Check the code redeemed properly - RedeemCodeState nextRedeemCodeState = nextState.GetRedeemCodeState(); - Assert.Throws(() => - { - nextRedeemCodeState.Redeem(redeemCode.Code, redeemCode.AvatarAddress); - }); + var nextRedeemCodeState = nextState.GetRedeemCodeState(); + Assert.Throws(() => { nextRedeemCodeState.Redeem(redeemCode.Code, redeemCode.AvatarAddress); }); } } } diff --git a/.Lib9c.Tests/Action/RegisterProduct0Test.cs b/.Lib9c.Tests/Action/RegisterProduct0Test.cs index 05d59e846c..b6b4e76f76 100644 --- a/.Lib9c.Tests/Action/RegisterProduct0Test.cs +++ b/.Lib9c.Tests/Action/RegisterProduct0Test.cs @@ -23,10 +23,9 @@ namespace Lib9c.Tests.Action public class RegisterProduct0Test { - private static readonly Address AvatarAddress = - new Address("47d082a115c63e7b58b1532d20e631538eafadde"); + private static readonly Address AvatarAddress = new ("47d082a115c63e7b58b1532d20e631538eafadde"); - private static readonly Currency Gold = Currency.Legacy("NCG", 2, minters: null); + private static readonly Currency Gold = Currency.Legacy("NCG", 2, null); private readonly Address _agentAddress; private readonly AvatarState _avatarState; @@ -258,7 +257,7 @@ public void Execute() var productsState = new ProductsState((List)nextState.GetLegacyState(ProductsState.DeriveAddress(AvatarAddress))); var random = new TestRandom(); - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { var guid = random.GenerateRandomGuid(); Assert.Contains(guid, productsState.ProductIds); @@ -292,7 +291,7 @@ public void Execute_Validate_RegisterInfos(params ValidateMember[] validateMembe var action = new RegisterProduct0 { AvatarAddress = AvatarAddress, - RegisterInfos = new[] { registerInfo }, + RegisterInfos = new[] { registerInfo, }, }; Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext { @@ -377,7 +376,7 @@ public void Execute_Throw_ItemDoesNotExistException(ProductType type, int itemCo public void Execute_Throw_ArgumentOutOfRangeException() { var registerInfos = new List(); - for (int i = 0; i < RegisterProduct0.Capacity + 1; i++) + for (var i = 0; i < RegisterProduct0.Capacity + 1; i++) { registerInfos.Add(new RegisterInfo()); } diff --git a/.Lib9c.Tests/Action/RegisterProductTest.cs b/.Lib9c.Tests/Action/RegisterProductTest.cs index cdebbed4ca..48d31d1bb4 100644 --- a/.Lib9c.Tests/Action/RegisterProductTest.cs +++ b/.Lib9c.Tests/Action/RegisterProductTest.cs @@ -23,10 +23,9 @@ namespace Lib9c.Tests.Action public class RegisterProductTest { - private static readonly Address AvatarAddress = - new Address("47d082a115c63e7b58b1532d20e631538eafadde"); + private static readonly Address AvatarAddress = new ("47d082a115c63e7b58b1532d20e631538eafadde"); - private static readonly Currency Gold = Currency.Legacy("NCG", 2, minters: null); + private static readonly Currency Gold = Currency.Legacy("NCG", 2, null); private readonly Address _agentAddress; private readonly AvatarState _avatarState; @@ -286,7 +285,7 @@ public void Execute() var productsState = new ProductsState((List)nextState.GetLegacyState(ProductsState.DeriveAddress(AvatarAddress))); var random = new TestRandom(); - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { var guid = random.GenerateRandomGuid(); Assert.Contains(guid, productsState.ProductIds); @@ -320,7 +319,7 @@ public void Execute_Validate_RegisterInfos(params ValidateMember[] validateMembe var action = new RegisterProduct { AvatarAddress = AvatarAddress, - RegisterInfos = new[] { registerInfo }, + RegisterInfos = new[] { registerInfo, }, }; Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext { @@ -406,7 +405,7 @@ public void Execute_Throw_ItemDoesNotExistException(ProductType type, int itemCo public void Execute_Throw_ArgumentOutOfRangeException() { var registerInfos = new List(); - for (int i = 0; i < RegisterProduct.Capacity + 1; i++) + for (var i = 0; i < RegisterProduct.Capacity + 1; i++) { registerInfos.Add(new RegisterInfo()); } diff --git a/.Lib9c.Tests/Action/RenewAdminStateTest.cs b/.Lib9c.Tests/Action/RenewAdminStateTest.cs index b41e36146f..77816069f3 100644 --- a/.Lib9c.Tests/Action/RenewAdminStateTest.cs +++ b/.Lib9c.Tests/Action/RenewAdminStateTest.cs @@ -98,7 +98,7 @@ public void CreatePendingActivationsAfterRenewAdminState() new PendingActivationState(nonce, privateKey.PublicKey), }); - long blockIndex = _validUntil + 1; + var blockIndex = _validUntil + 1; Assert.Throws(() => createPendingActivations.Execute(new ActionContext { BlockIndex = blockIndex, @@ -126,7 +126,7 @@ public void CreatePendingActivationsAfterRenewAdminState() Signer = _adminPrivateKey.Address, }); - Address expectedPendingActivationStateAddress = + var expectedPendingActivationStateAddress = PendingActivationState.DeriveAddress(nonce, privateKey.PublicKey); Assert.NotNull(stateDelta.GetLegacyState(expectedPendingActivationStateAddress)); } diff --git a/.Lib9c.Tests/Action/RequestPledgeTest.cs b/.Lib9c.Tests/Action/RequestPledgeTest.cs index 77b25fcdb6..d26eaa8e83 100644 --- a/.Lib9c.Tests/Action/RequestPledgeTest.cs +++ b/.Lib9c.Tests/Action/RequestPledgeTest.cs @@ -17,10 +17,10 @@ public class RequestPledgeTest [InlineData(100)] public void Execute(int contractedMead) { - Currency mead = Currencies.Mead; - Address patron = new PrivateKey().Address; + var mead = Currencies.Mead; + var patron = new PrivateKey().Address; var context = new ActionContext(); - IWorld states = new World(MockUtil.MockModernWorldState).MintAsset(context, patron, 2 * mead); + var states = new World(MockUtil.MockModernWorldState).MintAsset(context, patron, 2 * mead); var address = new PrivateKey().Address; var action = new RequestPledge { @@ -48,10 +48,10 @@ public void Execute(int contractedMead) [Fact] public void Execute_Throw_AlreadyContractedException() { - Address patron = new PrivateKey().Address; + var patron = new PrivateKey().Address; var address = new PrivateKey().Address; - Address contractAddress = address.GetPledgeAddress(); - IWorld states = new World(MockUtil.MockModernWorldState).SetLegacyState(contractAddress, List.Empty); + var contractAddress = address.GetPledgeAddress(); + var states = new World(MockUtil.MockModernWorldState).SetLegacyState(contractAddress, List.Empty); var action = new RequestPledge { AgentAddress = address, diff --git a/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs b/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs index 45a07e5d92..205f4f8fda 100644 --- a/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs +++ b/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs @@ -16,7 +16,7 @@ namespace Lib9c.Tests.Action public class RetrieveAvatarAssetsTest { - private static readonly Address _minter = new Address( + private static readonly Address _minter = new ( new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, @@ -106,9 +106,9 @@ public void Execute() var avatarAddress = agentState.avatarAddresses[0]; var prevState = _state.MintAsset( new ActionContext - { - Signer = _minter, - }, + { + Signer = _minter, + }, avatarAddress, 1 * _currency ); diff --git a/.Lib9c.Tests/Action/RewardGoldTest.cs b/.Lib9c.Tests/Action/RewardGoldTest.cs index 63df7d4cf9..8753b343e7 100644 --- a/.Lib9c.Tests/Action/RewardGoldTest.cs +++ b/.Lib9c.Tests/Action/RewardGoldTest.cs @@ -45,9 +45,9 @@ 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"); + 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.Address; @@ -192,8 +192,8 @@ public void PrepareNextArena(int prevWeeklyIndex, int targetWeeklyIndex, long bl var prevWeekly = new WeeklyArenaState(prevWeeklyIndex); var avatarAddress = _avatarState.address; var inactiveAvatarAddress = _avatarState2.address; - bool afterUpdate = prevWeeklyIndex >= 68; - bool filterInactive = blockIndex >= 3_976_000L; + var afterUpdate = prevWeeklyIndex >= 68; + var filterInactive = blockIndex >= 3_976_000L; if (!afterUpdate) { prevWeekly.Set(_avatarState, _tableSheets.CharacterSheet); @@ -293,7 +293,7 @@ out List rawList ) ); - List
addressList = rawList.ToList(StateExtensions.ToAddress); + var addressList = rawList.ToList(StateExtensions.ToAddress); Assert.Contains(avatarAddress, addressList); Assert.Equal(!filterInactive, addressList.Contains(inactiveAvatarAddress)); @@ -368,7 +368,7 @@ public void ResetChallengeCount() var updatedWeekly = nextState.GetWeeklyArenaState(migratedWeekly.address); var info = new ArenaInfo(rawInfo); - List
addressList = rawList.ToList(StateExtensions.ToAddress); + var addressList = rawList.ToList(StateExtensions.ToAddress); Assert.Empty(updatedWeekly.Map); Assert.Equal(blockIndex, updatedWeekly.ResetIndex); @@ -381,11 +381,11 @@ public void GoldDistributedEachAccount() { #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 - Currency currency = Currency.Legacy("NCG", 2, null); + var currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - Address fund = GoldCurrencyState.Address; - Address address1 = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); - Address address2 = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"); + var fund = GoldCurrencyState.Address; + var address1 = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); + var address2 = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"); var action = new RewardGold(); var ctx = new ActionContext() @@ -440,10 +440,7 @@ public void GoldDistributedEachAccount() // Fund 잔액을 초과해서 송금하는 경우 // EndBlock이 긴 순서대로 송금을 진행하기 때문에, 100이 송금 성공하고 10억이 송금 실패한다. ctx.BlockIndex = 2; - Assert.Throws(() => - { - delta = action.GenesisGoldDistribution(ctx, _baseState); - }); + Assert.Throws(() => { delta = action.GenesisGoldDistribution(ctx, _baseState); }); Assert.Equal(currency * 99999999900, delta.GetBalance(fund, currency)); Assert.Equal(currency * 100, delta.GetBalance(address1, currency)); Assert.Equal(currency * 0, delta.GetBalance(address2, currency)); @@ -452,8 +449,8 @@ public void GoldDistributedEachAccount() [Fact] public void MiningReward() { - Address miner = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); - Currency currency = _baseState.GetGoldCurrency(); + var miner = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); + var currency = _baseState.GetGoldCurrency(); var ctx = new ActionContext() { BlockIndex = 0, @@ -466,7 +463,7 @@ public void MiningReward() void AssertMinerReward(int blockIndex, string expected) { ctx.BlockIndex = blockIndex; - IWorld delta = action.MinerReward(ctx, _baseState); + var delta = action.MinerReward(ctx, _baseState); Assert.Equal(FungibleAssetValue.Parse(currency, expected), delta.GetBalance(miner, currency)); } @@ -511,12 +508,12 @@ public void TransferMead(int patronMead, int balance) null, DateTimeOffset.UtcNow, new TxActionList(new List()), - maxGasPrice: Currencies.Mead * 4, - gasLimit: 4), + Currencies.Mead * 4, + 4), new TxSigningMetadata(agentKey.PublicKey, 0)), agentKey)), }; - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .MintAsset(context, patronAddress, patronMead * Currencies.Mead) .TransferAsset(context, patronAddress, agentAddress, 1 * Currencies.Mead) .SetLegacyState(contractAddress, List.Empty.Add(patronAddress.Serialize()).Add(true.Serialize()).Add(balance.Serialize())) @@ -538,14 +535,14 @@ public void NoRewardWhenEmptySupply() gameConfigState.Set(_tableSheets.GameConfigSheet); var currency = Currency.Legacy("NCG", 2, null); - IWorld states = new World(MockUtil.MockModernWorldState) + var states = new World(MockUtil.MockModernWorldState) .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(currency, 0).Serialize()) .SetLegacyState(weekly.address, weekly.Serialize()) .SetLegacyState(Addresses.GoldDistribution, new List()) .SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); var action = new RewardGold(); - IWorld nextState = action.Execute( + var nextState = action.Execute( new ActionContext() { BlockIndex = 42, diff --git a/.Lib9c.Tests/Action/RuneEnhancementTest.cs b/.Lib9c.Tests/Action/RuneEnhancementTest.cs index 1d792cbfd9..174d26579d 100644 --- a/.Lib9c.Tests/Action/RuneEnhancementTest.cs +++ b/.Lib9c.Tests/Action/RuneEnhancementTest.cs @@ -96,8 +96,8 @@ int seed var ncgCurrency = state.GetGoldCurrency(); var crystalCurrency = CrystalCalculator.CRYSTAL; var runeTicker = tableSheets.RuneSheet.Values.First(r => r.Id == runeId).Ticker; - var runeCurrency = Currency.Legacy(runeTicker, 0, minters: null); - var r = new TestRandom(seed: 1); + var runeCurrency = Currency.Legacy(runeTicker, 0, null); + var r = new TestRandom(1); state = state.MintAsset(context, agentAddress, ncgCurrency * initialNcg); state = state.MintAsset(context, agentAddress, crystalCurrency * initialCrystal); @@ -214,8 +214,8 @@ int seed var ncgCurrency = state.GetGoldCurrency(); var crystalCurrency = CrystalCalculator.CRYSTAL; var runeTicker = tableSheets.RuneSheet.Values.First(r => r.Id == runeId).Ticker; - var runeCurrency = Currency.Legacy(runeTicker, 0, minters: null); - var r = new TestRandom(seed: 1); + var runeCurrency = Currency.Legacy(runeTicker, 0, null); + var r = new TestRandom(1); state = state.MintAsset(context, agentAddress, ncgCurrency * initialNcg); state = state.MintAsset(context, agentAddress, crystalCurrency * initialCrystal); @@ -446,7 +446,7 @@ public void Execute_NotEnoughFungibleAssetValueException(bool ncg, bool crystal, var ncgCurrency = state.GetGoldCurrency(); var crystalCurrency = CrystalCalculator.CRYSTAL; - var runeCurrency = Currency.Legacy(runeRow.Ticker, 0, minters: null); + var runeCurrency = Currency.Legacy(runeRow.Ticker, 0, null); if (ncg && cost.NcgQuantity > 0) { @@ -610,24 +610,24 @@ public void Execute_FailedLoadStateException() [Theory] // Rune upgrade - [InlineData(new[] { 1 }, 9, false, 30414)] - [InlineData(new[] { 9 }, 1, false, 30414)] - [InlineData(new[] { 7 }, 3, false, 30414)] - [InlineData(new[] { 4, 4 }, 2, false, 30598)] - [InlineData(new[] { 4, 5 }, 1, false, 30644)] + [InlineData(new[] { 1, }, 9, false, 30414)] + [InlineData(new[] { 9, }, 1, false, 30414)] + [InlineData(new[] { 7, }, 3, false, 30414)] + [InlineData(new[] { 4, 4, }, 2, false, 30598)] + [InlineData(new[] { 4, 5, }, 1, false, 30644)] // Crete new rune [InlineData(new int[] { }, 1, true, 30000)] [InlineData(new int[] { }, 10, true, 30414)] - [InlineData(new[] { 1 }, 9, true, 30414)] - [InlineData(new[] { 9 }, 1, true, 30414)] - [InlineData(new[] { 7 }, 3, true, 30414)] - [InlineData(new[] { 4, 4 }, 2, true, 30598)] - [InlineData(new[] { 4, 5 }, 1, true, 30644)] + [InlineData(new[] { 1, }, 9, true, 30414)] + [InlineData(new[] { 9, }, 1, true, 30414)] + [InlineData(new[] { 7, }, 3, true, 30414)] + [InlineData(new[] { 4, 4, }, 2, true, 30598)] + [InlineData(new[] { 4, 5, }, 1, true, 30644)] public void RuneBonus(int[] prevRuneLevels, int tryCount, bool createNewRune, int expectedRuneLevelBonus) { // Data const int testRuneId = 30001; - var prevRuneIds = new[] { 10001, 10002, 10003 }; + var prevRuneIds = new[] { 10001, 10002, 10003, }; const int initialNcg = 10_000; const int initialCrystal = 1_000_000; const int initialRune = 1_000; @@ -685,7 +685,7 @@ public void RuneBonus(int[] prevRuneLevels, int tryCount, bool createNewRune, in var ncgCurrency = state.GetGoldCurrency(); var crystalCurrency = CrystalCalculator.CRYSTAL; var runeTicker = tableSheets.RuneSheet.Values.First(r => r.Id == testRuneId).Ticker; - var runeCurrency = Currency.Legacy(runeTicker, 0, minters: null); + var runeCurrency = Currency.Legacy(runeTicker, 0, null); state = state.MintAsset(context, agentAddress, ncgCurrency * initialNcg); state = state.MintAsset(context, agentAddress, crystalCurrency * initialCrystal); state = state.MintAsset(context, avatarAddress, runeCurrency * initialRune); diff --git a/.Lib9c.Tests/Action/RuneHelperTest.cs b/.Lib9c.Tests/Action/RuneHelperTest.cs index 149f826685..1c2442c869 100644 --- a/.Lib9c.Tests/Action/RuneHelperTest.cs +++ b/.Lib9c.Tests/Action/RuneHelperTest.cs @@ -7,8 +7,7 @@ namespace Lib9c.Tests.Action public class RuneHelperTest { - private readonly TableSheets _tableSheets = - new TableSheets(TableSheetsImporter.ImportSheets()); + private readonly TableSheets _tableSheets = new (TableSheetsImporter.ImportSheets()); [Theory] [InlineData(50, 0)] diff --git a/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs index b3adc6eadf..641f64f607 100644 --- a/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs @@ -332,10 +332,10 @@ public IWorld BattleArena( private static string ShowLog(Address adr, ArenaSheet.RoundData data, ArenaScore score, ArenaInformation ai, int medalCount) { return $"[#{adr.ToHex().Substring(0, 6)}] arenaType({data.ArenaType}) / " + - $"score({score.Score}) / " + - $"Win({ai.Win}) / Lose({ai.Lose}) / " + - $"Ticket({ai.Ticket}) / TicketResetCount({ai.TicketResetCount}) / " + - $"MedalCount({medalCount})"; + $"score({score.Score}) / " + + $"Win({ai.Win}) / Lose({ai.Lose}) / " + + $"Ticket({ai.Ticket}) / TicketResetCount({ai.TicketResetCount}) / " + + $"MedalCount({medalCount})"; } private bool TryGetTarget( diff --git a/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs index 19a1a01890..93efe5a94b 100644 --- a/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs @@ -50,9 +50,9 @@ public AuraScenarioTest() var skillRow = _tableSheets.SkillSheet[210011]; var skill = SkillFactory.Get(skillRow, 0, 100, 0, StatType.NONE); _aura.Skills.Add(skill); - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; _initialState = new World(MockUtil.MockModernWorldState); - for (int i = 0; i < addresses.Length; i++) + for (var i = 0; i < addresses.Length; i++) { var avatarAddress = addresses[i]; agentState.avatarAddresses.Add(i, avatarAddress); @@ -68,7 +68,7 @@ public AuraScenarioTest() .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); } - _currency = Currency.Legacy("NCG", 2, minters: null); + _currency = Currency.Legacy("NCG", 2, null); _initialState = _initialState .SetAgentState(_agentAddress, agentState) .SetLegacyState( @@ -136,7 +136,7 @@ public void Raid() var itemSlotStateAddress = ItemSlotState.DeriveAddress(_avatarAddress, BattleType.Raid); Assert.Null(_initialState.GetLegacyState(itemSlotStateAddress)); var avatarState = _initialState.GetAvatarState(_avatarAddress); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -169,14 +169,14 @@ public void Raid() public void Arena() { var prevState = _initialState; - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; foreach (var avatarAddress in addresses) { var itemSlotStateAddress = ItemSlotState.DeriveAddress(avatarAddress, BattleType.Arena); Assert.Null(_initialState.GetLegacyState(itemSlotStateAddress)); var avatarState = prevState.GetAvatarState(avatarAddress); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -266,7 +266,7 @@ public void Arena() // Check player, enemy equip aura foreach (var spawn in log.OfType()) { - ArenaCharacter character = spawn.Character; + var character = spawn.Character; Assert.Equal(400, character.HIT); Assert.Equal(11, character.CRI); } @@ -311,7 +311,7 @@ public void Market() Assert.NotNull(aura); Assert.IsAssignableFrom(aura); Assert.Null(aura as ITradableItem); - for (int i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) + for (var i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -351,7 +351,7 @@ private void Assert_Player(AvatarState avatarState, IWorld state, Address avatar Assert_ItemSlot(state, itemSlotStateAddress); var player = new Player(avatarState, _tableSheets.GetSimulatorSheets()); var equippedPlayer = new Player(nextAvatarState, _tableSheets.GetSimulatorSheets()); - int diffLevel = equippedPlayer.Level - player.Level; + var diffLevel = equippedPlayer.Level - player.Level; var row = _tableSheets.CharacterSheet[player.CharacterId]; Assert.Null(player.aura); Assert.NotNull(equippedPlayer.aura); diff --git a/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs index 7f291f47b7..1def4bfec4 100644 --- a/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs @@ -35,9 +35,9 @@ public CollectionScenarioTest() _sheets = TableSheetsImporter.ImportSheets(); _tableSheets = new TableSheets(_sheets); var gameConfigState = new GameConfigState(_sheets[nameof(GameConfigSheet)]); - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; _initialState = new World(MockUtil.MockModernWorldState); - for (int i = 0; i < addresses.Length; i++) + for (var i = 0; i < addresses.Length; i++) { var avatarAddress = addresses[i]; agentState.avatarAddresses.Add(i, avatarAddress); @@ -49,11 +49,11 @@ public CollectionScenarioTest() rankingMapAddress ); _initialState = _initialState.SetAvatarState( - avatarAddress, avatarState, true, true, true, true) + avatarAddress, avatarState, true, true, true, true) .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); } - var currency = Currency.Legacy("NCG", 2, minters: null); + var currency = Currency.Legacy("NCG", 2, null); _initialState = _initialState .SetAgentState(_agentAddress, agentState) .SetLegacyState( @@ -169,14 +169,14 @@ public void BattleArena(bool collectionExist) prevStates = prevStates.SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); } - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; foreach (var avatarAddress in addresses) { var itemSlotStateAddress = ItemSlotState.DeriveAddress(avatarAddress, BattleType.Arena); Assert.Null(_initialState.GetLegacyState(itemSlotStateAddress)); var avatarState = prevStates.GetAvatarState(avatarAddress); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } diff --git a/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs index 2a8e7e3b2b..41f39cf5da 100644 --- a/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs @@ -50,9 +50,9 @@ public GrimoireScenarioTest() var skillRow = _tableSheets.SkillSheet[210011]; var skill = SkillFactory.Get(skillRow, 0, 100, 0, StatType.NONE); _grimoire.Skills.Add(skill); - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; _initialState = new World(MockUtil.MockModernWorldState); - for (int i = 0; i < addresses.Length; i++) + for (var i = 0; i < addresses.Length; i++) { var avatarAddress = addresses[i]; agentState.avatarAddresses.Add(i, avatarAddress); @@ -68,7 +68,7 @@ public GrimoireScenarioTest() .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); } - _currency = Currency.Legacy("NCG", 2, minters: null); + _currency = Currency.Legacy("NCG", 2, null); _initialState = _initialState .SetAgentState(_agentAddress, agentState) .SetLegacyState( @@ -136,7 +136,7 @@ public void Raid() var itemSlotStateAddress = ItemSlotState.DeriveAddress(_avatarAddress, BattleType.Raid); Assert.Null(_initialState.GetLegacyState(itemSlotStateAddress)); var avatarState = _initialState.GetAvatarState(_avatarAddress); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -169,14 +169,14 @@ public void Raid() public void Arena() { var prevState = _initialState; - var addresses = new[] { _avatarAddress, _enemyAvatarAddress }; + var addresses = new[] { _avatarAddress, _enemyAvatarAddress, }; foreach (var avatarAddress in addresses) { var itemSlotStateAddress = ItemSlotState.DeriveAddress(avatarAddress, BattleType.Arena); Assert.Null(_initialState.GetLegacyState(itemSlotStateAddress)); var avatarState = prevState.GetAvatarState(avatarAddress); - for (int i = 0; i < 50; i++) + for (var i = 0; i < 50; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -263,11 +263,11 @@ public void Arena() new List(), _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet - ); + ); // Check player, enemy equip charm foreach (var spawn in log.OfType()) { - ArenaCharacter character = spawn.Character; + var character = spawn.Character; Assert.Equal(30, character.ATK); Assert.Equal(11, character.CRI); } @@ -312,7 +312,7 @@ public void Market() Assert.NotNull(grimoire); Assert.IsAssignableFrom(grimoire); Assert.Null(grimoire as ITradableItem); - for (int i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) + for (var i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -352,7 +352,7 @@ private void Assert_Player(AvatarState avatarState, IWorld state, Address avatar Assert_ItemSlot(state, itemSlotStateAddress); var player = new Player(avatarState, _tableSheets.GetSimulatorSheets()); var equippedPlayer = new Player(nextAvatarState, _tableSheets.GetSimulatorSheets()); - int diffLevel = equippedPlayer.Level - player.Level; + var diffLevel = equippedPlayer.Level - player.Level; var row = _tableSheets.CharacterSheet[player.CharacterId]; Assert.Null(player.Grimoire); Assert.NotNull(equippedPlayer.Grimoire); diff --git a/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs b/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs index ece4a0e07d..9a412eec80 100644 --- a/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs +++ b/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs @@ -55,9 +55,9 @@ public ItemCraftTest() } [Theory] - [InlineData(1, new[] { 10110000 })] // 검 - [InlineData(1, new[] { 10110000, 10111000 })] // 검, 롱 소드(불) - [InlineData(1, new[] { 10110000, 10111000, 10114000 })] // 검, 롱 소드(불), 롱 소드(바람) + [InlineData(1, new[] { 10110000, })] // 검 + [InlineData(1, new[] { 10110000, 10111000, })] // 검, 롱 소드(불) + [InlineData(1, new[] { 10110000, 10111000, 10114000, })] // 검, 롱 소드(불), 롱 소드(바람) public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) { // Disable all quests to prevent contamination by quest reward @@ -73,7 +73,7 @@ public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) ).ToList(); Assert.Equal(targetItemIdList.Length, recipeList.Count); - List allMaterialList = + var allMaterialList = new List(); foreach (var recipe in recipeList) { @@ -89,7 +89,7 @@ public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) var maxUnlockStage = recipeList.Aggregate(0, (e, c) => Math.Max(e, c.UnlockStage)); var unlockRecipeIdsAddress = _avatarAddr.Derive("recipe_ids"); var recipeIds = List.Empty; - for (int i = 1; i < maxUnlockStage + 1; i++) + for (var i = 1; i < maxUnlockStage + 1; i++) { recipeIds = recipeIds.Add(i.Serialize()); } @@ -157,9 +157,9 @@ public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) } [Theory] - [InlineData(1, new[] { 201000 })] // 참치캔 - [InlineData(1, new[] { 201000, 201002 })] // 참치캔, 계란후라이 - [InlineData(1, new[] { 201011, 201012, 201013 })] // 스테이크, 모둠스테이크, 전설의 스테이크 + [InlineData(1, new[] { 201000, })] // 참치캔 + [InlineData(1, new[] { 201000, 201002, })] // 참치캔, 계란후라이 + [InlineData(1, new[] { 201011, 201012, 201013, })] // 스테이크, 모둠스테이크, 전설의 스테이크 public void CraftConsumableTest(int randomSeed, int[] targetItemIdList) { // Disable all quests to prevent contamination by quest reward @@ -242,7 +242,7 @@ public void CraftConsumableTest(int randomSeed, int[] targetItemIdList) } [Theory] - [InlineData(1, 1001, new[] { 900101 })] // 2022 Summer Event, 몬스터펀치 + [InlineData(1, 1001, new[] { 900101, })] // 2022 Summer Event, 몬스터펀치 public void EventConsumableItemCraftTest( int randomSeed, int eventScheduleId, @@ -322,7 +322,7 @@ int[] targetItemIdList } [Theory] - [InlineData(1, 1002, new[] { 10020001 })] // Grand Finale, AP Stone + [InlineData(1, 1002, new[] { 10020001, })] // Grand Finale, AP Stone public void EventMaterialItemCraftsTest( int randomSeed, int eventScheduleId, diff --git a/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs index dd6c3f0b77..aad1695d8e 100644 --- a/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs @@ -103,7 +103,7 @@ public MarketScenarioTest(ITestOutputHelper outputHelper) agentState3.avatarAddresses[0] = _buyerAvatarAddress; - _currency = Currency.Legacy("NCG", 2, minters: null); + _currency = Currency.Legacy("NCG", 2, null); _initialState = new World(MockUtil.MockModernWorldState) .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(_currency).Serialize()) .SetLegacyState(Addresses.GameConfig, _gameConfigState.Serialize()) @@ -364,8 +364,8 @@ public void Register_And_Cancel() _sellerAvatarState.inventory.AddItem(equipment); Assert.Equal(2, _sellerAvatarState.inventory.Items.Count); _initialState = _initialState - .SetAvatarState(_sellerAvatarAddress, _sellerAvatarState) - .MintAsset(context, _sellerAvatarAddress, 1 * RuneHelper.StakeRune); + .SetAvatarState(_sellerAvatarAddress, _sellerAvatarState) + .MintAsset(context, _sellerAvatarAddress, 1 * RuneHelper.StakeRune); var action = new RegisterProduct { AvatarAddress = _sellerAvatarAddress, @@ -417,7 +417,7 @@ public void Register_And_Cancel() Guid fungibleProductId = default; Guid nonFungibleProductId = default; Guid assetProductId = default; - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { var guid = random.GenerateRandomGuid(); @@ -448,7 +448,7 @@ public void Register_And_Cancel() } } - Assert.All(new[] { nonFungibleProductId, fungibleProductId, assetProductId }, productId => Assert.NotEqual(default, productId)); + Assert.All(new[] { nonFungibleProductId, fungibleProductId, assetProductId, }, productId => Assert.NotEqual(default, productId)); var action2 = new CancelProductRegistration { AvatarAddress = _sellerAvatarAddress, @@ -591,7 +591,7 @@ public void Register_And_ReRegister() Guid fungibleProductId = default; Guid nonFungibleProductId = default; Guid assetProductId = default; - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { var guid = random.GenerateRandomGuid(); switch (i) @@ -911,9 +911,9 @@ public void HardFork() var productsStateAddress = ProductsState.DeriveAddress(_sellerAvatarAddress); var productsState = new ProductsState((List)nextState.GetLegacyState(productsStateAddress)); foreach (var product in productsState.ProductIds.Select(Product.DeriveAddress) - .Select(productAddress => - ProductFactory.DeserializeProduct( - (List)nextState.GetLegacyState(productAddress)))) + .Select(productAddress => + ProductFactory.DeserializeProduct( + (List)nextState.GetLegacyState(productAddress)))) { switch (product) { @@ -1242,7 +1242,7 @@ private static IWorld Execute_Register_Custom_Equipment( MaterialItemSheet materialItemSheet) { var avatarState = state.GetAvatarState(avatarAddress); - var price = 1 * Currency.Legacy("NCG", 2, minters: null); + var price = 1 * Currency.Legacy("NCG", 2, null); var registerInfos = expectedReward.Select(expected => { materialItemSheet.TryGetValue(expected.id, out var materialRow); @@ -1264,7 +1264,7 @@ private static IWorld Execute_Register_Custom_Equipment( }; }); - for (int i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) + for (var i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) { avatarState.worldInformation.ClearStage(1, i + 1, 0, worldSheet, worldUnlockSheet); } @@ -1294,7 +1294,7 @@ private class ExecuteWithCustomEquipmentData : IEnumerable { new object[] { - new[] { 20160000, 20160001, 20160002 }, + new[] { 20160000, 20160001, 20160002, }, new[] { (600401, 14), @@ -1303,7 +1303,7 @@ private class ExecuteWithCustomEquipmentData : IEnumerable }, new object[] { - new[] { 20160000, 20260000, 20360000, 20460000, 20560000 }, + new[] { 20160000, 20260000, 20360000, 20460000, 20560000, }, new[] { (600401, 10), @@ -1312,7 +1312,7 @@ private class ExecuteWithCustomEquipmentData : IEnumerable }, new object[] { - new[] { 20160003, 20260000, 20360001, 20360001, 20460001 }, + new[] { 20160003, 20260000, 20360001, 20360001, 20460001, }, new[] { (600401, 24), // 10 + 2 + 4 + 4 + 4 = 24 @@ -1321,7 +1321,7 @@ private class ExecuteWithCustomEquipmentData : IEnumerable }, new object[] { - new[] { 20560003, 20560003, 20560003 }, + new[] { 20560003, 20560003, 20560003, }, new[] { (600401, 30), // 10 + 10 + 10 = 30 @@ -1330,9 +1330,15 @@ private class ExecuteWithCustomEquipmentData : IEnumerable }, }; - public IEnumerator GetEnumerator() => _data.GetEnumerator(); + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => _data.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return _data.GetEnumerator(); + } } } } diff --git a/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs index 0bf467e478..0c67b4451a 100644 --- a/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs @@ -22,7 +22,7 @@ public class MeadScenarioTest [Fact] public void Contract() { - Currency mead = Currencies.Mead; + var mead = Currencies.Mead; var patron = new PrivateKey().Address; var agentKey = new PrivateKey(); var agentAddress = agentKey.Address; @@ -36,12 +36,12 @@ public void Contract() null, DateTimeOffset.UtcNow, new TxActionList(new List()), - maxGasPrice: Currencies.Mead * 4, - gasLimit: 4), + Currencies.Mead * 4, + 4), new TxSigningMetadata(agentKey.PublicKey, 0)), agentKey)), }; - IWorld states = new World(MockUtil.MockModernWorldState).MintAsset(context, patron, 10 * mead); + var states = new World(MockUtil.MockModernWorldState).MintAsset(context, patron, 10 * mead); var requestPledge = new RequestPledge { @@ -82,13 +82,13 @@ public void Contract() [Fact] public void UseGas() { - Type baseType = typeof(Nekoyume.Action.ActionBase); + var baseType = typeof(Nekoyume.Action.ActionBase); bool IsTarget(Type type) { return baseType.IsAssignableFrom(type) && type != typeof(InitializeStates) && - type.GetCustomAttribute() is { } && + type.GetCustomAttribute() is not null && ( !(type.GetCustomAttribute()?.ObsoleteIndex is { } obsoleteIndex) || obsoleteIndex > ActionObsoleteConfig.V200030ObsoleteIndex @@ -98,8 +98,8 @@ bool IsTarget(Type type) var assembly = baseType.Assembly; var typeIds = assembly.GetTypes() .Where(IsTarget); - long expectedTransferActionGasLimit = 4L; - long expectedActionGasLimit = 1L; + var expectedTransferActionGasLimit = 4L; + var expectedActionGasLimit = 1L; foreach (var typeId in typeIds) { var action = (IAction)Activator.CreateInstance(typeId)!; @@ -116,10 +116,10 @@ bool IsTarget(Type type) // ignored } - long expectedGasLimit = action is ITransferAsset || action is ITransferAssets + var expectedGasLimit = action is ITransferAsset || action is ITransferAssets ? expectedTransferActionGasLimit : expectedActionGasLimit; - long gasUsed = actionContext.GasUsed(); + var gasUsed = actionContext.GasUsed(); Assert.True(expectedGasLimit == gasUsed, $"{action} invalid used gas. {gasUsed}"); } } diff --git a/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs index 5564a6e9a2..6b5c1c546e 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs @@ -56,7 +56,7 @@ int petLevel Assert.NotNull(recipe); // Get Materials and stages - List materialList = + var materialList = recipe.GetAllMaterials( _tableSheets.EquipmentItemSubRecipeSheetV2, CraftType.Premium ).ToList(); diff --git a/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs index 1505761a1a..328d1e8549 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs @@ -47,7 +47,7 @@ public void PetCannotBeUsedToTwoSlotsAtTheSameTime() var recipe = _tableSheets.EquipmentItemRecipeSheet.Values.First( recipe => recipe.ResultEquipmentId == itemId ); - List materialList = + var materialList = recipe.GetAllMaterials(_tableSheets.EquipmentItemSubRecipeSheetV2).ToList(); var stageList = List.Empty; for (var i = 0; i < recipe.UnlockStage; i++) diff --git a/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs index ae8b5048b9..6ee53b69b1 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs @@ -59,7 +59,7 @@ public void CraftEquipmentTest( Assert.NotNull(recipe); // Get materials and stages - List materialList = + var materialList = recipe.GetAllMaterials(_tableSheets.EquipmentItemSubRecipeSheetV2).ToList(); var stageList = List.Empty; for (var i = 1; i < recipe.UnlockStage + 1; i++) diff --git a/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs index 613d5b4a87..023bf69cbb 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs @@ -67,7 +67,7 @@ public void RapidCombinationTest_Equipment( var recipe = _tableSheets.EquipmentItemRecipeSheet.Values.First( recipe => recipe.RequiredBlockIndex >= requiredBlock - ); + ); Assert.NotNull(recipe); // Get Materials and stages @@ -103,7 +103,7 @@ public void RapidCombinationTest_Equipment( recipe.RequiredBlockIndex / (stateV2.GetGameConfigState().HourglassPerBlock - + petRow.LevelOptionMap[(int)petLevel].OptionValue) + + petRow.LevelOptionMap[(int)petLevel].OptionValue) ); } @@ -114,7 +114,7 @@ public void RapidCombinationTest_Equipment( _avatarAddr, new List { - new EquipmentItemSubRecipeSheet.MaterialInfo( + new ( _hourglassItemId, expectedHourglass ), @@ -160,7 +160,7 @@ public void RapidCombinationTest_Equipment( var rapidAction = new RapidCombination { avatarAddress = _avatarAddr, - slotIndexList = new List { 0 }, + slotIndexList = new List { 0, }, }; stateV2 = rapidAction.Execute(new ActionContext { diff --git a/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs index 5a946bbc60..daa02f862b 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs @@ -42,7 +42,7 @@ public ReduceRequiredBlockTest() [InlineData(30)] // Lv.30 reduces 20% public void CombinationEquipmentTest(int? petLevel) { - int targetItemId = 10114000; + var targetItemId = 10114000; var random = new TestRandom(); // Get Recipe @@ -52,7 +52,7 @@ public void CombinationEquipmentTest(int? petLevel) var expectedBlock = recipe.RequiredBlockIndex; // Get Materials and stages - List materialList = + var materialList = recipe.GetAllMaterials(_tableSheets.EquipmentItemSubRecipeSheetV2).ToList(); var stageList = List.Empty; for (var i = 1; i < recipe.UnlockStage + 1; i++) diff --git a/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs index 280cf3f728..b02c12bef6 100644 --- a/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs @@ -40,12 +40,12 @@ public void Craft_And_Unlock_And_Equip() ); var context = new ActionContext(); - IWorld initialState = new World(MockUtil.MockModernWorldState) + var initialState = new World(MockUtil.MockModernWorldState) .SetAgentState(agentAddress, agentState) .SetAvatarState(avatarAddress, avatarState) .SetLegacyState( Addresses.GoldCurrency, - new GoldCurrencyState(Currency.Legacy("NCG", 2, minters: null)).Serialize()) + new GoldCurrencyState(Currency.Legacy("NCG", 2, null)).Serialize()) .SetLegacyState(gameConfigState.address, gameConfigState.Serialize()) .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); foreach (var (key, value) in sheets) @@ -121,7 +121,7 @@ public void Craft_And_Unlock_And_Equip() WorldId = 1, RuneInfos = new List { - new RuneSlotInfo(6, runeId), + new (6, runeId), }, }; @@ -163,12 +163,12 @@ public void MigrateToRuneStateModule() ); var context = new ActionContext(); - IWorld initialState = new World(MockUtil.MockModernWorldState) + var initialState = new World(MockUtil.MockModernWorldState) .SetAgentState(agentAddress, agentState) .SetAvatarState(avatarAddress, avatarState) .SetLegacyState( Addresses.GoldCurrency, - new GoldCurrencyState(Currency.Legacy("NCG", 2, minters: null)).Serialize()) + new GoldCurrencyState(Currency.Legacy("NCG", 2, null)).Serialize()) .SetLegacyState(gameConfigState.address, gameConfigState.Serialize()) .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); foreach (var (key, value) in sheets) diff --git a/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs b/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs index d82f44723b..bdbc8cec1f 100644 --- a/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs +++ b/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs @@ -161,7 +161,7 @@ public void Execute_With_TradableMaterial() } private Sell GetSell(ITradableItem tradableItem, int count, Guid orderId) => - new Sell + new() { sellerAvatarAddress = _avatarAddress, tradableId = tradableItem.TradableId, @@ -177,13 +177,15 @@ private Sell GetSell(ITradableItem tradableItem, int count, Guid orderId) => orderId = orderId, }; - private SellCancellation GetSellCancellation(Guid orderId, ITradableItem tradableItem) => - new SellCancellation + private SellCancellation GetSellCancellation(Guid orderId, ITradableItem tradableItem) + { + return new SellCancellation() { orderId = orderId, tradableId = tradableItem.TradableId, sellerAvatarAddress = _avatarAddress, itemSubType = tradableItem.ItemSubType, }; + } } } diff --git a/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs index 61b8157f1c..3e64d19c5f 100644 --- a/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs @@ -109,7 +109,7 @@ public void UnlockWorldByHackAndSlashAfterPatchTableWithAddRow( StageId = stageIdToClear, AvatarAddress = _avatarAddress, Costumes = new List(), - Equipments = new List { doomfist.NonFungibleId }, + Equipments = new List { doomfist.NonFungibleId, }, Foods = new List(), RuneInfos = new List(), }; diff --git a/.Lib9c.Tests/Action/SecureMiningRewardTest.cs b/.Lib9c.Tests/Action/SecureMiningRewardTest.cs index 4ba4db9052..70bd835309 100644 --- a/.Lib9c.Tests/Action/SecureMiningRewardTest.cs +++ b/.Lib9c.Tests/Action/SecureMiningRewardTest.cs @@ -15,17 +15,13 @@ public class SecureMiningRewardTest private static readonly Currency NCG = SecureMiningReward.NCG; // Just for sake of checking, chosen arbitrary addresses statically. - private static readonly Address _admin = - new Address("0x765781BB7B4FA2598Cb09383EBb9bEe8b1aE10bF"); + private static readonly Address _admin = new ("0x765781BB7B4FA2598Cb09383EBb9bEe8b1aE10bF"); - private static readonly Address _recipient = - new Address("0xC63c1dDCeB5054015bC01dE352b42234d4a25be5"); + private static readonly Address _recipient = new ("0xC63c1dDCeB5054015bC01dE352b42234d4a25be5"); - private static readonly Address _treasury = - new Address("0xB3bCa3b3c6069EF5Bdd6384bAD98F11378Dc360E"); + private static readonly Address _treasury = new ("0xB3bCa3b3c6069EF5Bdd6384bAD98F11378Dc360E"); - private static readonly Address _nil = - new Address("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF"); + private static readonly Address _nil = new ("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF"); private static readonly ImmutableList
_authMiners = new[] { @@ -36,19 +32,19 @@ public class SecureMiningRewardTest }.ToImmutableList(); private static readonly IWorld _previousState = new World( - MockWorldState.CreateModern() - .SetBalance(_authMiners[0], NCG * 1000) - .SetBalance(_authMiners[1], NCG * 2000) - .SetBalance(_authMiners[2], NCG * 3000) - .SetBalance(_authMiners[3], NCG * 4000)) + MockWorldState.CreateModern() + .SetBalance(_authMiners[0], NCG * 1000) + .SetBalance(_authMiners[1], NCG * 2000) + .SetBalance(_authMiners[2], NCG * 3000) + .SetBalance(_authMiners[3], NCG * 4000)) .SetLegacyState(AdminState.Address, new AdminState(_admin, 100).Serialize()) .SetLegacyState(GoldCurrencyState.Address, new GoldCurrencyState(NCG).Serialize()); [Fact] public void Execute() { - var action = new SecureMiningReward(recipient: _recipient); - IWorld nextState = action.Execute( + var action = new SecureMiningReward(_recipient); + var nextState = action.Execute( new ActionContext { PreviousState = _previousState, @@ -76,7 +72,7 @@ public void Execute() public void Execute_InvalidSigner() { var invalidSigner = new Address("0x94cde435616875310f0739FAf2c8671c58987bf0"); - var action = new SecureMiningReward(recipient: _recipient); + var action = new SecureMiningReward(_recipient); Assert.Throws(() => action.Execute( new ActionContext { diff --git a/.Lib9c.Tests/Action/Snapshot/ActionUtils.cs b/.Lib9c.Tests/Action/Snapshot/ActionUtils.cs index ee11c2ad6a..121e059751 100644 --- a/.Lib9c.Tests/Action/Snapshot/ActionUtils.cs +++ b/.Lib9c.Tests/Action/Snapshot/ActionUtils.cs @@ -10,8 +10,8 @@ public static class ActionUtils public static IValue GetActionTypeId() where T : IAction { - Type attrType = typeof(ActionTypeAttribute); - Type actionType = typeof(T); + var attrType = typeof(ActionTypeAttribute); + var actionType = typeof(T); return actionType.GetCustomAttribute() is { } attr ? attr.TypeIdentifier : throw new ArgumentException( diff --git a/.Lib9c.Tests/Action/Stake2Test.cs b/.Lib9c.Tests/Action/Stake2Test.cs index c1e7958343..dc45b9feb7 100644 --- a/.Lib9c.Tests/Action/Stake2Test.cs +++ b/.Lib9c.Tests/Action/Stake2Test.cs @@ -70,7 +70,7 @@ public void Execute_Throws_WhenNotEnoughBalance() [Fact] public void Execute_Throws_WhenThereIsMonsterCollection() { - Address monsterCollectionAddress = + var monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signerAddress, 0); var agentState = new AgentState(_signerAddress) { @@ -94,7 +94,7 @@ public void Execute_Throws_WhenThereIsMonsterCollection() [Fact] public void Execute_Throws_WhenClaimableExisting() { - Address stakeStateAddress = StakeState.DeriveAddress(_signerAddress); + var stakeStateAddress = StakeState.DeriveAddress(_signerAddress); var context = new ActionContext(); var states = _initialState .SetLegacyState(stakeStateAddress, new StakeState(stakeStateAddress, 0).Serialize()) @@ -139,7 +139,7 @@ public void Execute_Throws_WhenCancelOrUpdateWhileLockup() })); // Same (since 4611070) - if (states.TryGetStakeState(_signerAddress, out StakeState stakeState)) + if (states.TryGetStakeState(_signerAddress, out var stakeState)) { states = states.SetLegacyState( stakeState.address, @@ -180,7 +180,7 @@ public void Execute() _currency * 100, states.GetBalance(StakeState.DeriveAddress(_signerAddress), _currency)); - states.TryGetStakeState(_signerAddress, out StakeState stakeState); + states.TryGetStakeState(_signerAddress, out var stakeState); Assert.Equal(0, stakeState.StartedBlockIndex); Assert.Equal(0 + StakeState.LockupInterval, stakeState.CancellableBlockIndex); Assert.Equal(0, stakeState.ReceivedBlockIndex); @@ -192,7 +192,7 @@ public void Execute() Assert.False(achievements.Check(0, 1)); Assert.False(achievements.Check(1, 0)); - StakeState producedStakeState = new StakeState( + var producedStakeState = new StakeState( stakeState.address, stakeState.StartedBlockIndex, // Produce a situation that it already received rewards. @@ -224,7 +224,7 @@ public void Update() BlockIndex = 0, }); - states.TryGetStakeState(_signerAddress, out StakeState stakeState); + states.TryGetStakeState(_signerAddress, out var stakeState); Assert.Equal(0, stakeState.StartedBlockIndex); Assert.Equal(0 + StakeState.LockupInterval, stakeState.CancellableBlockIndex); Assert.Equal(0, stakeState.ReceivedBlockIndex); diff --git a/.Lib9c.Tests/Action/StakeTest.cs b/.Lib9c.Tests/Action/StakeTest.cs index fc42f3e94a..a433c31608 100644 --- a/.Lib9c.Tests/Action/StakeTest.cs +++ b/.Lib9c.Tests/Action/StakeTest.cs @@ -194,7 +194,7 @@ public void Execute_Throws_NotEnoughFungibleAssetValueException( if (balance > 0) { previousState = _initialState.MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, _agentAddr, _ncg * balance); } @@ -234,12 +234,12 @@ public void Execute_Throw_StakeExistingClaimableException_With_StakeState( { var stakeStateAddr = StakeState.DeriveAddress(_agentAddr); var stakeState = new StakeState( - address: stakeStateAddr, - startedBlockIndex: previousStartedBlockIndex); + stakeStateAddr, + previousStartedBlockIndex); Assert.True(stakeState.IsClaimable(blockIndex)); var previousState = _initialState .MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeState.Serialize()); @@ -267,11 +267,11 @@ public void Execute_Throw_StakeExistingClaimableException_With_StakeStateV2( { var stakeStateAddr = StakeStateV2.DeriveAddress(_agentAddr); var stakeStateV2 = new StakeStateV2( - contract: new Contract(_stakePolicySheet), - startedBlockIndex: previousStartedBlockIndex); + new Contract(_stakePolicySheet), + previousStartedBlockIndex); var previousState = _initialState .MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeStateV2.Serialize()); @@ -302,14 +302,14 @@ public void { var stakeStateAddr = StakeState.DeriveAddress(_agentAddr); var stakeState = new StakeState( - address: stakeStateAddr, - startedBlockIndex: previousStartedBlockIndex); + stakeStateAddr, + previousStartedBlockIndex); Assert.False(stakeState.IsCancellable(blockIndex)); stakeState.Claim(blockIndex); Assert.False(stakeState.IsClaimable(blockIndex)); var previousState = _initialState .MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeState.Serialize()); @@ -340,12 +340,12 @@ public void { var stakeStateAddr = StakeStateV2.DeriveAddress(_agentAddr); var stakeStateV2 = new StakeStateV2( - contract: new Contract(_stakePolicySheet), - startedBlockIndex: previousStartedBlockIndex, - receivedBlockIndex: blockIndex); + new Contract(_stakePolicySheet), + previousStartedBlockIndex, + blockIndex); var previousState = _initialState .MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeStateV2.Serialize()); @@ -365,7 +365,7 @@ public void public void Execute_Success_When_Staking_State_Null(long amount) { var previousState = _initialState.MintAsset( - new ActionContext { Signer = Addresses.Admin }, + new ActionContext { Signer = Addresses.Admin, }, _agentAddr, _ncg * amount); Execute( @@ -402,8 +402,8 @@ public void Execute_Success_When_Exist_StakeState( { var stakeStateAddr = StakeState.DeriveAddress(_agentAddr); var stakeState = new StakeState( - address: stakeStateAddr, - startedBlockIndex: previousStartedBlockIndex); + stakeStateAddr, + previousStartedBlockIndex); stakeState.Claim(blockIndex); var previousState = _initialState .MintAsset( @@ -451,9 +451,9 @@ public void Execute_Success_When_Exist_StakeStateV2( { var stakeStateAddr = StakeStateV2.DeriveAddress(_agentAddr); var stakeStateV2 = new StakeStateV2( - contract: new Contract(_stakePolicySheet), - startedBlockIndex: previousStartedBlockIndex, - receivedBlockIndex: blockIndex); + new Contract(_stakePolicySheet), + previousStartedBlockIndex, + blockIndex); var previousState = _initialState .MintAsset( new ActionContext(), diff --git a/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs b/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs index c357865884..4a935c6764 100644 --- a/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs +++ b/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs @@ -122,11 +122,11 @@ public void CumulativeRatio(string version, int groupId) [Theory] // success first group - [InlineData("V1", 10001, 1, 800201, 1, 1, new[] { 10610000 }, null)] - [InlineData("V1", 10001, 2, 800201, 2, 54, new[] { 10620000, 10630000 }, null)] + [InlineData("V1", 10001, 1, 800201, 1, 1, new[] { 10610000, }, null)] + [InlineData("V1", 10001, 2, 800201, 2, 54, new[] { 10620000, 10630000, }, null)] // success second group - [InlineData("V1", 10002, 1, 600201, 1, 1, new[] { 10620001 }, null)] - [InlineData("V1", 10002, 2, 600201, 2, 4, new[] { 10620001, 10630001 }, null)] + [InlineData("V1", 10002, 1, 600201, 1, 1, new[] { 10620001, }, null)] + [InlineData("V1", 10002, 2, 600201, 2, 4, new[] { 10620001, 10630001, }, null)] // Nine plus zero [InlineData( "V1", @@ -135,7 +135,7 @@ public void CumulativeRatio(string version, int groupId) 800201, 9, 0, - new[] { 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10620000, 10620000, 10620000 }, + new[] { 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10620000, 10620000, 10620000, }, null )] [InlineData( @@ -145,7 +145,7 @@ public void CumulativeRatio(string version, int groupId) 600201, 9, 0, - new[] { 10620001, 10620001, 10620001, 10620001, 10620001, 10630001, 10630001, 10630001, 10630001 }, + new[] { 10620001, 10620001, 10620001, 10620001, 10620001, 10630001, 10630001, 10630001, 10630001, }, null )] // Ten plus one @@ -156,7 +156,7 @@ public void CumulativeRatio(string version, int groupId) 800201, 10, 0, - new[] { 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10620000, 10620000, 10620000 }, + new[] { 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10610000, 10620000, 10620000, 10620000, }, null )] [InlineData( @@ -166,7 +166,7 @@ public void CumulativeRatio(string version, int groupId) 600201, 10, 0, - new[] { 10620001, 10620001, 10620001, 10620001, 10620001, 10620001, 10630001, 10620001, 10630001, 10630001, 10630001 }, + new[] { 10620001, 10620001, 10620001, 10620001, 10620001, 10620001, 10630001, 10620001, 10630001, 10630001, 10630001, }, null )] // fail by invalid group @@ -177,7 +177,7 @@ public void CumulativeRatio(string version, int groupId) // Fail by exceeding summon limit [InlineData("V1", 10001, 11, 800201, 22, 1, new int[] { }, typeof(InvalidSummonCountException))] // 15 recipes - [InlineData("V2", 10002, 1, 600201, 1, 5341, new[] { 10650006 }, null)] + [InlineData("V2", 10002, 1, 600201, 1, 5341, new[] { 10650006, }, null)] // 15 recipes [InlineData("V3", 20001, 1, 600201, 1, 5341, new int[] { }, typeof(SheetRowNotFoundException))] public void Execute( @@ -198,7 +198,7 @@ Type expectedExc "V1" => SummonSheetFixtures.V1.Serialize(), "V2" => SummonSheetFixtures.V2.Serialize(), "V3" => SummonSheetFixtures.V3.Serialize(), - _ => throw new ArgumentOutOfRangeException(nameof(version), version, null) + _ => throw new ArgumentOutOfRangeException(nameof(version), version, null), }; state = state.SetLegacyState(Addresses.TableSheet.Derive(nameof(SummonSheet)), sheet); diff --git a/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs b/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs index 8e98da0d60..0a451b81e3 100644 --- a/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs +++ b/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs @@ -196,7 +196,7 @@ private class ExecuteMemeber : IEnumerable }, new object[] { - 20001, 2, 600201, 2, 54, null, + 20001, 2, 600201, 2, 54, null, }, // Nine plus zero new object[] @@ -221,17 +221,17 @@ private class ExecuteMemeber : IEnumerable // fail by invalid group new object[] { - 100003, 1, null, 0, 0, typeof(RowNotInTableException), + 100003, 1, null, 0, 0, typeof(RowNotInTableException), }, // fail by not enough material new object[] { - 20001, 1, 600201, 0, 0, typeof(NotEnoughMaterialException), + 20001, 1, 600201, 0, 0, typeof(NotEnoughMaterialException), }, // Fail by exceeding summon limit new object[] { - 20001, 11, 600201, 22, 1, typeof(InvalidSummonCountException), + 20001, 11, 600201, 22, 1, typeof(InvalidSummonCountException), }, new object[] { @@ -239,9 +239,15 @@ private class ExecuteMemeber : IEnumerable }, }; - public IEnumerator GetEnumerator() => _data.GetEnumerator(); + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => _data.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return _data.GetEnumerator(); + } } } } diff --git a/.Lib9c.Tests/Action/TransferAssetTest.cs b/.Lib9c.Tests/Action/TransferAssetTest.cs index 4ec020e08e..46ba0131d4 100644 --- a/.Lib9c.Tests/Action/TransferAssetTest.cs +++ b/.Lib9c.Tests/Action/TransferAssetTest.cs @@ -22,23 +22,23 @@ namespace Lib9c.Tests.Action public class TransferAssetTest { - private static readonly Address _sender = new Address( + private static readonly Address _sender = new ( new byte[] { - 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, } ); - private static readonly Address _recipient = new Address(new byte[] + private static readonly Address _recipient = new (new byte[] { - 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, } ); #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 private static readonly Currency _currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 @@ -59,11 +59,11 @@ public void Execute() .SetBalance(_sender, _currency * 1000) .SetBalance(_recipient, _currency * 10)); var action = new TransferAsset( - sender: _sender, - recipient: _recipient, - amount: _currency * 100 + _sender, + _recipient, + _currency * 100 ); - IWorld nextState = action.Execute(new ActionContext() + var nextState = action.Execute(new ActionContext() { PreviousState = prevState, Signer = _sender, @@ -83,9 +83,9 @@ public void Execute_Throw_InvalidTransferSignerException() .SetBalance(_recipient, _currency * 10) .SetBalance(_sender, Currencies.Mead * 1)); var action = new TransferAsset( - sender: _sender, - recipient: _recipient, - amount: _currency * 100 + _sender, + _recipient, + _currency * 100 ); var exc = Assert.Throws(() => @@ -113,9 +113,9 @@ public void Execute_Throw_InvalidTransferRecipientException() .SetBalance(_sender, Currencies.Mead * 1)); // Should not allow TransferAsset with same sender and recipient. var action = new TransferAsset( - sender: _sender, - recipient: _sender, - amount: _currency * 100 + _sender, + _sender, + _currency * 100 ); var exc = Assert.Throws(() => @@ -141,12 +141,12 @@ public void Execute_Throw_InsufficientBalanceException() .SetBalance(_recipient, _currency * 10)); prevState = prevState.SetAgentState(_recipient, new AgentState(_recipient)); var action = new TransferAsset( - sender: _sender, - recipient: _recipient, - amount: _currency * 100000 + _sender, + _recipient, + _currency * 100000 ); - InsufficientBalanceException exc = Assert.Throws(() => + var exc = Assert.Throws(() => { action.Execute(new ActionContext() { @@ -165,21 +165,21 @@ public void Execute_Throw_InsufficientBalanceException() [InlineData(false)] public void Execute_Throw_InvalidTransferMinterException(bool minterAsSender) { - Address minter = minterAsSender ? _sender : _recipient; + var minter = minterAsSender ? _sender : _recipient; #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var currencyBySender = Currency.Legacy("NCG", 2, minter); #pragma warning restore CS0618 var prevState = new World( - MockWorldState.CreateModern() - .SetBalance(_sender, currencyBySender * 1000) - .SetBalance(_recipient, currencyBySender * 10) - .SetBalance(_sender, Currencies.Mead * 1)) + MockWorldState.CreateModern() + .SetBalance(_sender, currencyBySender * 1000) + .SetBalance(_recipient, currencyBySender * 10) + .SetBalance(_sender, Currencies.Mead * 1)) .SetAgentState(_recipient, new AgentState(_recipient)); var action = new TransferAsset( - sender: _sender, - recipient: _recipient, - amount: currencyBySender * 100 + _sender, + _recipient, + currencyBySender * 100 ); var ex = Assert.Throws(() => { @@ -191,7 +191,7 @@ public void Execute_Throw_InvalidTransferMinterException(bool minterAsSender) }); }); - Assert.Equal(new[] { minter }, ex.Minters); + Assert.Equal(new[] { minter, }, ex.Minters); Assert.Equal(_sender, ex.Sender); Assert.Equal(_recipient, ex.Recipient); } @@ -202,8 +202,8 @@ public void Execute_Throw_InvalidTransferMinterException(bool minterAsSender) public void PlainValue(string memo) { var action = new TransferAsset(_sender, _recipient, _currency * 100, memo); - Dictionary plainValue = (Dictionary)action.PlainValue; - Dictionary values = (Dictionary)plainValue["values"]; + var plainValue = (Dictionary)action.PlainValue; + var values = (Dictionary)plainValue["values"]; Assert.Equal((Text)"transfer_asset5", plainValue["type_id"]); Assert.Equal(_sender, values["sender"].ToAddress()); @@ -248,14 +248,14 @@ public void Execute_Throw_InvalidTransferCurrencyException() { var crystal = CrystalCalculator.CRYSTAL; var prevState = new World( - MockWorldState.CreateModern() - .SetBalance(_sender, crystal * 1000) - .SetBalance(_sender, Currencies.Mead * 1)) + MockWorldState.CreateModern() + .SetBalance(_sender, crystal * 1000) + .SetBalance(_sender, Currencies.Mead * 1)) .SetLegacyState(_recipient.Derive(ActivationKey.DeriveKey), true.Serialize()); var action = new TransferAsset( - sender: _sender, - recipient: _recipient, - amount: 1000 * crystal + _sender, + _recipient, + 1000 * crystal ); Assert.Throws(() => action.Execute(new ActionContext() { @@ -289,9 +289,9 @@ public void Execute_Throw_ArgumentException() MockWorldState.CreateModern() .SetBalance(_sender, _currency * 1000)); var action = new TransferAsset( - sender: _sender, - recipient: StakeState.DeriveAddress(_recipient), - amount: _currency * 100 + _sender, + StakeState.DeriveAddress(_recipient), + _currency * 100 ); // 스테이킹 주소에 송금하려고 하면 실패합니다. Assert.Throws("recipient", () => action.Execute(new ActionContext() diff --git a/.Lib9c.Tests/Action/TransferAssetsTest.cs b/.Lib9c.Tests/Action/TransferAssetsTest.cs index 70a3169f44..b5f1ade24c 100644 --- a/.Lib9c.Tests/Action/TransferAssetsTest.cs +++ b/.Lib9c.Tests/Action/TransferAssetsTest.cs @@ -22,22 +22,22 @@ namespace Lib9c.Tests.Action public class TransferAssetsTest { - private static readonly Address _sender = new Address( + private static readonly Address _sender = new ( new byte[] { - 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, } ); - private static readonly Address _recipient = new Address(new byte[] + private static readonly Address _recipient = new (new byte[] { - 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, } ); - private static readonly Address _recipient2 = new Address(new byte[] + private static readonly Address _recipient2 = new (new byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, @@ -45,7 +45,7 @@ public class TransferAssetsTest ); #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 private static readonly Currency _currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 @@ -74,14 +74,14 @@ public void Execute() .SetBalance(_sender, _currency * 1000) .SetBalance(_recipient, _currency * 10)); var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (_recipient, _currency * 100), (_recipient2, _currency * 100), } ); - IWorld nextState = action.Execute(new ActionContext() + var nextState = action.Execute(new ActionContext() { PreviousState = prevState, Signer = _sender, @@ -103,7 +103,7 @@ public void Execute_Throw_InvalidTransferSignerException() .SetBalance(_sender, _currency * 1000) .SetBalance(_recipient, _currency * 10)); var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (_recipient, _currency * 100), @@ -134,7 +134,7 @@ public void Execute_Throw_InvalidTransferRecipientException() .SetBalance(_sender, _currency * 1000)); // Should not allow TransferAsset with same sender and recipient. var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (_sender, _currency * 100), @@ -159,19 +159,19 @@ public void Execute_Throw_InvalidTransferRecipientException() public void Execute_Throw_InsufficientBalanceException() { var prevState = new World( - MockWorldState.CreateModern() - .SetBalance(_sender, _currency * 1000) - .SetBalance(_recipient, _currency * 10)) + MockWorldState.CreateModern() + .SetBalance(_sender, _currency * 1000) + .SetBalance(_recipient, _currency * 10)) .SetAgentState(_recipient, new AgentState(_recipient)); var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (_recipient, _currency * 100000), } ); - InsufficientBalanceException exc = Assert.Throws(() => + var exc = Assert.Throws(() => { action.Execute(new ActionContext() { @@ -193,12 +193,12 @@ public void Execute_Throw_InvalidTransferMinterException() var currencyBySender = Currency.Legacy("NCG", 2, _sender); #pragma warning restore CS0618 var prevState = new World( - MockWorldState.CreateModern() - .SetBalance(_sender, currencyBySender * 1000) - .SetBalance(_recipient, currencyBySender * 10)) + MockWorldState.CreateModern() + .SetBalance(_sender, currencyBySender * 1000) + .SetBalance(_recipient, currencyBySender * 10)) .SetAgentState(_recipient, new AgentState(_recipient)); var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (_recipient, currencyBySender * 100), @@ -214,7 +214,7 @@ public void Execute_Throw_InvalidTransferMinterException() }); }); - Assert.Equal(new[] { _sender }, ex.Minters); + Assert.Equal(new[] { _sender, }, ex.Minters); Assert.Equal(_sender, ex.Sender); Assert.Equal(_recipient, ex.Recipient); } @@ -233,8 +233,8 @@ public void PlainValue(string memo) memo ); - Dictionary plainValue = (Dictionary)action.PlainValue; - Dictionary values = (Dictionary)plainValue["values"]; + var plainValue = (Dictionary)action.PlainValue; + var values = (Dictionary)plainValue["values"]; var recipients = (List)values["recipients"]; var info = (List)recipients[0]; @@ -323,7 +323,7 @@ public void Execute_Throw_ArgumentOutOfRangeException() { var recipients = new List<(Address, FungibleAssetValue)>(); - for (int i = 0; i < TransferAssets.RecipientsCapacity + 1; i++) + for (var i = 0; i < TransferAssets.RecipientsCapacity + 1; i++) { recipients.Add((_recipient, _currency * 100)); } @@ -345,12 +345,12 @@ public void Execute_Throw_InvalidTransferCurrencyException() { var crystal = CrystalCalculator.CRYSTAL; var prevState = new World( - MockWorldState.CreateModern() - .SetBalance(_sender, crystal * 1000)) + MockWorldState.CreateModern() + .SetBalance(_sender, crystal * 1000)) .SetLegacyState(_recipient.Derive(ActivationKey.DeriveKey), true.Serialize()); var action = new TransferAssets( - sender: _sender, - recipients: new List<(Address, FungibleAssetValue)> + _sender, + new List<(Address, FungibleAssetValue)> { (_recipient, 1000 * crystal), (_recipient, 100 * _currency), @@ -369,7 +369,7 @@ public void Execute_Throw_ArgumentException() { var baseState = new World(MockWorldState.CreateModern().SetBalance(_sender, _currency * 1000)); var action = new TransferAssets( - sender: _sender, + _sender, new List<(Address, FungibleAssetValue)> { (StakeState.DeriveAddress(_recipient), _currency * 100), diff --git a/.Lib9c.Tests/Action/UnlockCombinationSlotTest.cs b/.Lib9c.Tests/Action/UnlockCombinationSlotTest.cs index 5b2407abf9..f742628c0d 100644 --- a/.Lib9c.Tests/Action/UnlockCombinationSlotTest.cs +++ b/.Lib9c.Tests/Action/UnlockCombinationSlotTest.cs @@ -1,211 +1,156 @@ -namespace Lib9c.Tests.Action; - -using System.Collections.Generic; -using System.Linq; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Libplanet.Mocks; -using Libplanet.Types.Assets; -using Nekoyume; -using Nekoyume.Action; -using Nekoyume.Extensions; -using Nekoyume.Model.Item; -using Nekoyume.Model.State; -using Nekoyume.Module; -using Nekoyume.TableData; -using Xunit; - -public class UnlockCombinationSlotTest +namespace Lib9c.Tests.Action { - public const int GoldenDustId = 600201; - public const int RubyDustId = 600202; + using System.Collections.Generic; + using System.Linq; + using Libplanet.Action.State; + using Libplanet.Crypto; + using Libplanet.Mocks; + using Libplanet.Types.Assets; + using Nekoyume; + using Nekoyume.Action; + using Nekoyume.Extensions; + using Nekoyume.Model.Item; + using Nekoyume.Model.State; + using Nekoyume.Module; + using Nekoyume.TableData; + using Xunit; + + public class UnlockCombinationSlotTest + { + public const int GoldenDustId = 600201; + public const int RubyDustId = 600202; - private static readonly Dictionary Sheets = - TableSheetsImporter.ImportSheets(); + private static readonly Dictionary Sheets = + TableSheetsImporter.ImportSheets(); - private static readonly TableSheets TableSheets = new (Sheets); + private static readonly TableSheets TableSheets = new (Sheets); #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1419 - private readonly Currency _goldCurrency = Currency.Legacy("NCG", 2, null); + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1419 + private readonly Currency _goldCurrency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - public IWorld Init(out Address agentAddress, out Address avatarAddress, out long blockIndex) - { - agentAddress = new PrivateKey().Address; - avatarAddress = new PrivateKey().Address; - blockIndex = TableSheets.ArenaSheet.Values.First().Round - .OrderBy(x => x.StartBlockIndex) - .First() - .StartBlockIndex; - - var goldCurrencyState = new GoldCurrencyState(_goldCurrency); - var state = new World(MockUtil.MockModernWorldState) - .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) - .SetAgentState(agentAddress, new AgentState(agentAddress)); - - foreach (var (key, value) in Sheets) - state = state.SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); - - var gameConfigState = new GameConfigState(Sheets[nameof(GameConfigSheet)]); - var avatarState = AvatarState.Create( - avatarAddress, - agentAddress, - 0, - TableSheets.GetAvatarSheets(), - default - ); - state = state.SetAvatarState(avatarAddress, avatarState); - return state.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); - } - - public IWorld MintAssetForCost(IWorld state, int slotIndex, ActionContext context, Address agentAddress, Address avatarAddress) - { - var sheets = state.GetSheets( - new[] - { - typeof(MaterialItemSheet), - typeof(UnlockCombinationSlotCostSheet), - }); - var costSheet = sheets.GetSheet(); - - if (!costSheet.ContainsKey(slotIndex)) + public IWorld Init(out Address agentAddress, out Address avatarAddress, out long blockIndex) { - return state; - } - - var price = costSheet[slotIndex]; - var useMaterial = false; - - Inventory inventory = null; - - // Use Crystal - if (price.CrystalPrice > 0) - { - var currency = Currencies.Crystal; - state = state.MintAsset(context, agentAddress, price.CrystalPrice * currency); - } + agentAddress = new PrivateKey().Address; + avatarAddress = new PrivateKey().Address; + blockIndex = TableSheets.ArenaSheet.Values.First().Round + .OrderBy(x => x.StartBlockIndex) + .First() + .StartBlockIndex; + + var goldCurrencyState = new GoldCurrencyState(_goldCurrency); + var state = new World(MockUtil.MockModernWorldState) + .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) + .SetAgentState(agentAddress, new AgentState(agentAddress)); + + foreach (var (key, value) in Sheets) + { + state = state.SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); + } - // Use GoldenDust - if (price.GoldenDustPrice > 0) - { - var materialSheet = sheets.GetSheet(); - inventory = state.GetInventoryV2(avatarAddress); - var goldenDust = - ItemFactory.CreateMaterial( - materialSheet.Values.First(row => row.Id == GoldenDustId)); - inventory.AddItem(goldenDust, price.GoldenDustPrice); - - useMaterial = true; + var gameConfigState = new GameConfigState(Sheets[nameof(GameConfigSheet)]); + var avatarState = AvatarState.Create( + avatarAddress, + agentAddress, + 0, + TableSheets.GetAvatarSheets(), + default + ); + state = state.SetAvatarState(avatarAddress, avatarState); + return state.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); } - // Use RubyDust - if (price.RubyDustPrice > 0) + public IWorld MintAssetForCost(IWorld state, int slotIndex, ActionContext context, Address agentAddress, Address avatarAddress) { - var materialSheet = sheets.GetSheet(); - inventory ??= state.GetInventoryV2(avatarAddress); - var rubyDust = - ItemFactory.CreateMaterial(materialSheet.Values.First(row => row.Id == RubyDustId)); - inventory.AddItem(rubyDust, price.RubyDustPrice); + var sheets = state.GetSheets( + new[] + { + typeof(MaterialItemSheet), + typeof(UnlockCombinationSlotCostSheet), + }); + var costSheet = sheets.GetSheet(); + + if (!costSheet.ContainsKey(slotIndex)) + { + return state; + } - useMaterial = true; - } + var price = costSheet[slotIndex]; + var useMaterial = false; - // Use NCG - if (price.NcgPrice > 0) - { - var currency = state.GetGoldCurrency(); - state = state.MintAsset(context, agentAddress, price.NcgPrice * currency); - } + Inventory inventory = null; - // useMaterial이 true일 경우에만 inventory를 업데이트한다. - if (useMaterial) - { - state = state.SetInventory(avatarAddress, inventory); - } + // Use Crystal + if (price.CrystalPrice > 0) + { + var currency = Currencies.Crystal; + state = state.MintAsset(context, agentAddress, price.CrystalPrice * currency); + } - return state; - } + // Use GoldenDust + if (price.GoldenDustPrice > 0) + { + var materialSheet = sheets.GetSheet(); + inventory = state.GetInventoryV2(avatarAddress); + var goldenDust = + ItemFactory.CreateMaterial( + materialSheet.Values.First(row => row.Id == GoldenDustId)); + inventory.AddItem(goldenDust, price.GoldenDustPrice); + + useMaterial = true; + } - /// - /// Unit test for validating the behavior of the UnlockCombinationSlot action.
- /// check 'IsUnlock', 'Index' property of slot, and used material count. - ///
- /// The index of the combination slot to be unlocked. - /// - /// This test initializes the game state, mints assets, and then executes the UnlockCombinationSlot action. - /// It verifies that the currency balances are correctly updated and ensures that the specified combination slot is unlocked. - /// Additionally, it checks that certain items (GoldenDust and RubyDust) are not present in the avatar's inventory after the action. - /// - [Theory] - [InlineData(4)] - [InlineData(6)] - public void Execute(int slotIndex) - { - var context = new ActionContext(); - var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); - state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); - var action = new UnlockCombinationSlot() - { - AvatarAddress = avatarAddress, - SlotIndex = slotIndex, - }; + // Use RubyDust + if (price.RubyDustPrice > 0) + { + var materialSheet = sheets.GetSheet(); + inventory ??= state.GetInventoryV2(avatarAddress); + var rubyDust = + ItemFactory.CreateMaterial(materialSheet.Values.First(row => row.Id == RubyDustId)); + inventory.AddItem(rubyDust, price.RubyDustPrice); - var ctx = new ActionContext - { - BlockIndex = blockIndex, - PreviousState = state, - RandomSeed = 0, - Signer = agentAddress, - }; - - state = action.Execute(ctx); - - // Check Items - var ncgCurrency = state.GetGoldCurrency(); - var ncgBalance = state.GetBalance(agentAddress, ncgCurrency); - var crystalBalance = state.GetBalance(agentAddress, Currencies.Crystal); - var inventory = state.GetInventoryV2(avatarAddress); - Assert.Equal("0", ncgBalance.GetQuantityString()); - Assert.Equal("0", crystalBalance.GetQuantityString()); - Assert.False(inventory.HasItem(GoldenDustId)); - Assert.False(inventory.HasItem(RubyDustId)); - - // Check Slot - var combinationSlotState = state.GetAllCombinationSlotState(avatarAddress); - var slotState = combinationSlotState.GetSlot(slotIndex); - Assert.True(slotState.IsUnlocked); - Assert.True(slotState.Index == slotIndex); - } + useMaterial = true; + } - /// - /// Unit test for validating the unlocking of all combination slots for an avatar. - /// - /// - /// This test initializes the game state, retrieves all combination slots, and iterates through each slot. - /// For locked slots, it mints the necessary assets and executes the UnlockCombinationSlot action to unlock them. - /// Finally, it verifies that all slots are unlocked successfully. - /// - [Fact] - public void Execute_All() - { - var context = new ActionContext(); - var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); - var allCombinationSlotState = state.GetAllCombinationSlotState(avatarAddress); + // Use NCG + if (price.NcgPrice > 0) + { + var currency = state.GetGoldCurrency(); + state = state.MintAsset(context, agentAddress, price.NcgPrice * currency); + } - foreach (var slotState in allCombinationSlotState) - { - if (slotState.IsUnlocked) + // useMaterial이 true일 경우에만 inventory를 업데이트한다. + if (useMaterial) { - continue; + state = state.SetInventory(avatarAddress, inventory); } - state = MintAssetForCost(state, slotState.Index, context, agentAddress, avatarAddress); + return state; + } + /// + /// Unit test for validating the behavior of the UnlockCombinationSlot action.
+ /// check 'IsUnlock', 'Index' property of slot, and used material count. + ///
+ /// The index of the combination slot to be unlocked. + /// + /// This test initializes the game state, mints assets, and then executes the UnlockCombinationSlot action. + /// It verifies that the currency balances are correctly updated and ensures that the specified combination slot is unlocked. + /// Additionally, it checks that certain items (GoldenDust and RubyDust) are not present in the avatar's inventory after the action. + /// + [Theory] + [InlineData(4)] + [InlineData(6)] + public void Execute(int slotIndex) + { + var context = new ActionContext(); + var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); + state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); var action = new UnlockCombinationSlot() { AvatarAddress = avatarAddress, - SlotIndex = slotState.Index, + SlotIndex = slotIndex, }; var ctx = new ActionContext @@ -217,138 +162,196 @@ public void Execute_All() }; state = action.Execute(ctx); - } - allCombinationSlotState = state.GetAllCombinationSlotState(avatarAddress); - foreach (var slotState in allCombinationSlotState) - { + // Check Items + var ncgCurrency = state.GetGoldCurrency(); + var ncgBalance = state.GetBalance(agentAddress, ncgCurrency); + var crystalBalance = state.GetBalance(agentAddress, Currencies.Crystal); + var inventory = state.GetInventoryV2(avatarAddress); + Assert.Equal("0", ncgBalance.GetQuantityString()); + Assert.Equal("0", crystalBalance.GetQuantityString()); + Assert.False(inventory.HasItem(GoldenDustId)); + Assert.False(inventory.HasItem(RubyDustId)); + + // Check Slot + var combinationSlotState = state.GetAllCombinationSlotState(avatarAddress); + var slotState = combinationSlotState.GetSlot(slotIndex); Assert.True(slotState.IsUnlocked); + Assert.True(slotState.Index == slotIndex); } - } - /// - /// Unit test for validating the behavior when attempting to unlock a default combination slot that is already unlocked. - /// - /// The index of the combination slot to be tested. - /// - /// This test initializes the game state, mints the necessary assets for the given slot, and attempts to execute the UnlockCombinationSlot action. - /// It verifies that the action throws a SlotAlreadyUnlockedException, indicating that the specified slot is already unlocked by default. - /// - [Theory] - [InlineData(1)] - [InlineData(3)] - public void Execute_DefaultSlot(int slotIndex) - { - var context = new ActionContext(); - var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); - state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); - var action = new UnlockCombinationSlot() + /// + /// Unit test for validating the unlocking of all combination slots for an avatar. + /// + /// + /// This test initializes the game state, retrieves all combination slots, and iterates through each slot. + /// For locked slots, it mints the necessary assets and executes the UnlockCombinationSlot action to unlock them. + /// Finally, it verifies that all slots are unlocked successfully. + /// + [Fact] + public void Execute_All() { - AvatarAddress = avatarAddress, - SlotIndex = slotIndex, - }; + var context = new ActionContext(); + var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); + var allCombinationSlotState = state.GetAllCombinationSlotState(avatarAddress); - var ctx = new ActionContext - { - BlockIndex = blockIndex, - PreviousState = state, - RandomSeed = 0, - Signer = agentAddress, - }; + foreach (var slotState in allCombinationSlotState) + { + if (slotState.IsUnlocked) + { + continue; + } + + state = MintAssetForCost(state, slotState.Index, context, agentAddress, avatarAddress); + + var action = new UnlockCombinationSlot() + { + AvatarAddress = avatarAddress, + SlotIndex = slotState.Index, + }; + + var ctx = new ActionContext + { + BlockIndex = blockIndex, + PreviousState = state, + RandomSeed = 0, + Signer = agentAddress, + }; + + state = action.Execute(ctx); + } - Assert.Throws(() => action.Execute(ctx)); - } + allCombinationSlotState = state.GetAllCombinationSlotState(avatarAddress); + foreach (var slotState in allCombinationSlotState) + { + Assert.True(slotState.IsUnlocked); + } + } - /// - /// Unit test for validating the behavior of the UnlockCombinationSlot action when provided with an invalid slot index. - /// - /// The invalid index of the combination slot to be tested. - /// - /// This test initializes the game state, attempts to mint the necessary assets for an invalid slot index, and then tries to execute the UnlockCombinationSlot action. - /// It verifies that the action throws an InvalidSlotIndexException, indicating that the specified slot index is out of the valid range. - /// - [Theory] - [InlineData(-1)] - [InlineData(0x5f5f)] - public void Execute_ValidateSlotIndex(int slotIndex) - { - var context = new ActionContext(); - var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); - state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); - var action = new UnlockCombinationSlot() + /// + /// Unit test for validating the behavior when attempting to unlock a default combination slot that is already unlocked. + /// + /// The index of the combination slot to be tested. + /// + /// This test initializes the game state, mints the necessary assets for the given slot, and attempts to execute the UnlockCombinationSlot action. + /// It verifies that the action throws a SlotAlreadyUnlockedException, indicating that the specified slot is already unlocked by default. + /// + [Theory] + [InlineData(1)] + [InlineData(3)] + public void Execute_DefaultSlot(int slotIndex) { - AvatarAddress = avatarAddress, - SlotIndex = slotIndex, - }; + var context = new ActionContext(); + var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); + state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); + var action = new UnlockCombinationSlot() + { + AvatarAddress = avatarAddress, + SlotIndex = slotIndex, + }; - var ctx = new ActionContext - { - BlockIndex = blockIndex, - PreviousState = state, - RandomSeed = 0, - Signer = agentAddress, - }; + var ctx = new ActionContext + { + BlockIndex = blockIndex, + PreviousState = state, + RandomSeed = 0, + Signer = agentAddress, + }; - Assert.Throws(() => action.Execute(ctx)); - } + Assert.Throws(() => action.Execute(ctx)); + } - /// - /// Unit test for validating the behavior of the UnlockCombinationSlot action when there are insufficient assets. - /// - /// The index of the combination slot to be tested. - /// - /// This test initializes the game state and attempts to execute the UnlockCombinationSlot action with different slot indices. - /// Depending on the slot index, it expects specific exceptions to be thrown, such as InsufficientBalanceException or NotEnoughMaterialException, - /// indicating that the action cannot be completed due to a lack of necessary resources. - /// - [Theory] - [InlineData(4)] - [InlineData(5)] - [InlineData(6)] - [InlineData(7)] - public void Execute_InsufficientAsset(int slotIndex) - { - var context = new ActionContext(); - var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); - var action = new UnlockCombinationSlot() + /// + /// Unit test for validating the behavior of the UnlockCombinationSlot action when provided with an invalid slot index. + /// + /// The invalid index of the combination slot to be tested. + /// + /// This test initializes the game state, attempts to mint the necessary assets for an invalid slot index, and then tries to execute the UnlockCombinationSlot action. + /// It verifies that the action throws an InvalidSlotIndexException, indicating that the specified slot index is out of the valid range. + /// + [Theory] + [InlineData(-1)] + [InlineData(0x5f5f)] + public void Execute_ValidateSlotIndex(int slotIndex) { - AvatarAddress = avatarAddress, - SlotIndex = slotIndex, - }; + var context = new ActionContext(); + var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); + state = MintAssetForCost(state, slotIndex, context, agentAddress, avatarAddress); + var action = new UnlockCombinationSlot() + { + AvatarAddress = avatarAddress, + SlotIndex = slotIndex, + }; - var ctx = new ActionContext - { - BlockIndex = blockIndex, - PreviousState = state, - RandomSeed = 0, - Signer = agentAddress, - }; - - var sheets = state.GetSheets( - new[] + var ctx = new ActionContext { - typeof(MaterialItemSheet), - typeof(UnlockCombinationSlotCostSheet), - }); - var costSheet = sheets.GetSheet(); + BlockIndex = blockIndex, + PreviousState = state, + RandomSeed = 0, + Signer = agentAddress, + }; - if (!costSheet.ContainsKey(slotIndex)) - { - return; + Assert.Throws(() => action.Execute(ctx)); } - var price = costSheet[slotIndex]; - var useMaterial = price.GoldenDustPrice > 0 || price.RubyDustPrice > 0; - var needCheckBalance = price.CrystalPrice > 0 || price.NcgPrice > 0; - - if (useMaterial) + /// + /// Unit test for validating the behavior of the UnlockCombinationSlot action when there are insufficient assets. + /// + /// The index of the combination slot to be tested. + /// + /// This test initializes the game state and attempts to execute the UnlockCombinationSlot action with different slot indices. + /// Depending on the slot index, it expects specific exceptions to be thrown, such as InsufficientBalanceException or NotEnoughMaterialException, + /// indicating that the action cannot be completed due to a lack of necessary resources. + /// + [Theory] + [InlineData(4)] + [InlineData(5)] + [InlineData(6)] + [InlineData(7)] + public void Execute_InsufficientAsset(int slotIndex) { - Assert.ThrowsAny(() => action.Execute(ctx)); - } + var context = new ActionContext(); + var state = Init(out var agentAddress, out var avatarAddress, out var blockIndex); + var action = new UnlockCombinationSlot() + { + AvatarAddress = avatarAddress, + SlotIndex = slotIndex, + }; - if (needCheckBalance) - { - Assert.ThrowsAny(() => action.Execute(ctx)); + var ctx = new ActionContext + { + BlockIndex = blockIndex, + PreviousState = state, + RandomSeed = 0, + Signer = agentAddress, + }; + + var sheets = state.GetSheets( + new[] + { + typeof(MaterialItemSheet), + typeof(UnlockCombinationSlotCostSheet), + }); + var costSheet = sheets.GetSheet(); + + if (!costSheet.ContainsKey(slotIndex)) + { + return; + } + + var price = costSheet[slotIndex]; + var useMaterial = price.GoldenDustPrice > 0 || price.RubyDustPrice > 0; + var needCheckBalance = price.CrystalPrice > 0 || price.NcgPrice > 0; + + if (useMaterial) + { + Assert.ThrowsAny(() => action.Execute(ctx)); + } + + if (needCheckBalance) + { + Assert.ThrowsAny(() => action.Execute(ctx)); + } } } } diff --git a/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs b/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs index 26edf9ad31..4d1e3cb591 100644 --- a/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs +++ b/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs @@ -64,26 +64,26 @@ public UnlockEquipmentRecipeTest() // Recipe 6 unlocks at stage 27 // Recipe 94 unlocks at stage 90 // Recipe 133 unlocks at stage 17 - [InlineData(new[] { 6, 5 }, true, false, true, true, null)] - [InlineData(new[] { 6 }, true, false, true, true, null)] + [InlineData(new[] { 6, 5, }, true, false, true, true, null)] + [InlineData(new[] { 6, }, true, false, true, true, null)] // Unlock Belt without Armor unlock. - [InlineData(new[] { 94 }, true, false, true, true, null)] + [InlineData(new[] { 94, }, true, false, true, true, null)] // Unlock Weapon & Ring - [InlineData(new[] { 6, 133 }, true, false, true, true, null)] + [InlineData(new[] { 6, 133, }, true, false, true, true, null)] // Invalid recipe id. - [InlineData(new[] { -1 }, true, false, false, false, typeof(InvalidRecipeIdException))] - [InlineData(new[] { 1 }, true, false, true, false, typeof(InvalidRecipeIdException))] + [InlineData(new[] { -1, }, true, false, false, false, typeof(InvalidRecipeIdException))] + [InlineData(new[] { 1, }, true, false, true, false, typeof(InvalidRecipeIdException))] [InlineData(new int[] { }, true, false, false, false, typeof(InvalidRecipeIdException))] // AvatarState is null. - [InlineData(new[] { 6 }, false, false, true, true, typeof(FailedLoadStateException))] + [InlineData(new[] { 6, }, false, false, true, true, typeof(FailedLoadStateException))] // Already unlocked recipe. - [InlineData(new[] { 6 }, true, true, true, true, typeof(AlreadyRecipeUnlockedException))] + [InlineData(new[] { 6, }, true, true, true, true, typeof(AlreadyRecipeUnlockedException))] // Skip prev recipe. - [InlineData(new[] { 5 }, true, false, true, true, typeof(InvalidRecipeIdException))] + [InlineData(new[] { 5, }, true, false, true, true, typeof(InvalidRecipeIdException))] // Stage not cleared. - [InlineData(new[] { 6 }, true, false, false, true, typeof(NotEnoughClearedStageLevelException))] + [InlineData(new[] { 6, }, true, false, false, true, typeof(NotEnoughClearedStageLevelException))] // Insufficient CRYSTAL. - [InlineData(new[] { 6 }, true, false, true, false, typeof(NotEnoughFungibleAssetValueException))] + [InlineData(new[] { 6, }, true, false, true, false, typeof(NotEnoughFungibleAssetValueException))] public void Execute( IEnumerable ids, bool stateExist, @@ -94,12 +94,12 @@ Type exc ) { var context = new ActionContext(); - List recipeIds = ids.ToList(); + var recipeIds = ids.ToList(); var rows = _tableSheets.EquipmentItemRecipeSheet.Values .Where(r => recipeIds.Contains(r.Id)).ToList(); var balance = balanceEnough ? rows.Sum(r => r.CRYSTAL) : 1; var state = _initialState.MintAsset(context, _agentAddress, balance * _currency); - Address unlockedRecipeIdsAddress = _avatarAddress.Derive("recipe_ids"); + var unlockedRecipeIdsAddress = _avatarAddress.Derive("recipe_ids"); if (stateExist) { var stage = rows.Any() ? rows.Max(r => r.UnlockStage) : 1; @@ -109,7 +109,7 @@ Type exc var worldInformation = _avatarState.worldInformation; if (stageCleared) { - for (int j = 1; j < worldId + 1; j++) + for (var j = 1; j < worldId + 1; j++) { for (var i = 1; i < stage + 1; i++) { @@ -145,7 +145,7 @@ Type exc if (exc is null) { - IWorld nextState = action.Execute(new ActionContext + var nextState = action.Execute(new ActionContext { PreviousState = state, Signer = _agentAddress, @@ -186,10 +186,10 @@ public void UnlockedIds(ItemSubType itemSubType) .Where(i => i.ItemSubType == itemSubType && i.Id != 1 && i.UnlockStage != 999 && i.CRYSTAL != 0); // Clear Stage - for (int i = 0; i < _tableSheets.WorldSheet.Count; i++) + for (var i = 0; i < _tableSheets.WorldSheet.Count; i++) { var worldRow = _tableSheets.WorldSheet.OrderedList[i]; - for (int v = worldRow.StageBegin; v < worldRow.StageEnd + 1; v++) + for (var v = worldRow.StageBegin; v < worldRow.StageEnd + 1; v++) { worldInformation.ClearStage(worldRow.Id, v, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } diff --git a/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs b/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs index a26c8e5766..e84973cab6 100644 --- a/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs +++ b/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs @@ -214,7 +214,7 @@ public void Execute_CRYSTAL(bool legacyState, int slotIndex) state = state.MintAsset(context, agentAddress, cost * Currencies.Crystal); if (legacyState) { - foreach (var battleType in new[] { BattleType.Adventure, BattleType.Arena, BattleType.Raid }) + foreach (var battleType in new[] { BattleType.Adventure, BattleType.Arena, BattleType.Raid, }) { var runeSlotState = new RuneSlotState(battleType); var serialized = (List)runeSlotState.Serialize(); diff --git a/.Lib9c.Tests/Action/UnlockWorldTest.cs b/.Lib9c.Tests/Action/UnlockWorldTest.cs index 3d5eee7f9e..435dcc4bb6 100644 --- a/.Lib9c.Tests/Action/UnlockWorldTest.cs +++ b/.Lib9c.Tests/Action/UnlockWorldTest.cs @@ -56,27 +56,27 @@ public UnlockWorldTest() } [Theory] - [InlineData(new[] { 2 }, true, false, true, 500, null)] + [InlineData(new[] { 2, }, true, false, true, 500, null)] // Migration AvatarState. - [InlineData(new[] { 2, 3, 4, 5 }, true, false, true, 153000, null)] + [InlineData(new[] { 2, 3, 4, 5, }, true, false, true, 153000, null)] // TODO: add world 6 unlock //[InlineData(new[] { 2, 3, 4, 5, 6 }, true, false, true, 153000, null)] // Try open Yggdrasil. - [InlineData(new[] { 1 }, false, false, true, 0, typeof(InvalidWorldException))] + [InlineData(new[] { 1, }, false, false, true, 0, typeof(InvalidWorldException))] // Try open Mimisbrunnr. - [InlineData(new[] { GameConfig.MimisbrunnrWorldId }, false, false, true, 0, typeof(InvalidWorldException))] + [InlineData(new[] { GameConfig.MimisbrunnrWorldId, }, false, false, true, 0, typeof(InvalidWorldException))] // Empty WorldId. [InlineData(new int[] { }, false, false, true, 0, typeof(InvalidWorldException))] // AvatarState is null. - [InlineData(new[] { 2 }, false, false, true, 0, typeof(FailedLoadStateException))] + [InlineData(new[] { 2, }, false, false, true, 0, typeof(FailedLoadStateException))] // Already unlocked world. - [InlineData(new[] { 2 }, true, true, true, 0, typeof(AlreadyWorldUnlockedException))] + [InlineData(new[] { 2, }, true, true, true, 0, typeof(AlreadyWorldUnlockedException))] // Skip previous world. - [InlineData(new[] { 3 }, true, false, true, 0, typeof(FailedToUnlockWorldException))] + [InlineData(new[] { 3, }, true, false, true, 0, typeof(FailedToUnlockWorldException))] // Stage not cleared. - [InlineData(new[] { 2 }, true, false, false, 0, typeof(FailedToUnlockWorldException))] + [InlineData(new[] { 2, }, true, false, false, 0, typeof(FailedToUnlockWorldException))] // Insufficient CRYSTAL. - [InlineData(new[] { 2 }, true, false, true, 100, typeof(NotEnoughFungibleAssetValueException))] + [InlineData(new[] { 2, }, true, false, true, 100, typeof(NotEnoughFungibleAssetValueException))] public void Execute( IEnumerable ids, bool stateExist, @@ -87,7 +87,7 @@ Type exc ) { var context = new ActionContext(); - var state = (balance > 0) + var state = balance > 0 ? _initialState.MintAsset(context, _agentAddress, balance * _currency) : _initialState; var worldIds = ids.ToList(); @@ -109,13 +109,13 @@ Type exc if (!(prevRow is null)) { var prevWorldRow = _tableSheets.WorldSheet[prevRow.WorldId]; - for (int i = prevWorldRow.StageBegin; i < prevWorldRow.StageEnd + 1; i++) + for (var i = prevWorldRow.StageBegin; i < prevWorldRow.StageEnd + 1; i++) { worldInformation.ClearStage(prevWorldRow.Id, i, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } } - for (int i = worldRow.StageBegin; i < worldRow.StageEnd + 1; i++) + for (var i = worldRow.StageBegin; i < worldRow.StageEnd + 1; i++) { worldInformation.ClearStage(worldRow.Id, i, 0, _tableSheets.WorldSheet, _tableSheets.WorldUnlockSheet); } @@ -145,7 +145,7 @@ Type exc if (exc is null) { - IWorld nextState = action.Execute(new ActionContext + var nextState = action.Execute(new ActionContext { PreviousState = state, Signer = _agentAddress, diff --git a/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs b/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs index 547ad8a699..758b8d6d6f 100644 --- a/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs +++ b/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs @@ -69,7 +69,7 @@ public void CheckPermission_Throws_PermissionDenied() .SetLegacyState(AdminState.Address, adminState.Serialize()); var action = ValidatorSetOperate.Append(_validator); - PermissionDeniedException exc1 = Assert.Throws(() => + var exc1 = Assert.Throws(() => { action.Execute( new ActionContext() @@ -87,7 +87,7 @@ public void CheckPermission_Throws_PermissionDenied() public void Append_Throws_WhenAlreadyExistValidator() { var action = ValidatorSetOperate.Append(_validator); - InvalidOperationException exc = Assert.Throws(() => + var exc = Assert.Throws(() => action.Execute(new ActionContext { PreviousState = _initialState, @@ -102,7 +102,7 @@ public void Update_Throws_WhenDoNotExistValidator() { var state = new World(MockUtil.MockModernWorldState); var action = ValidatorSetOperate.Update(_validator); - InvalidOperationException exc = Assert.Throws(() => + var exc = Assert.Throws(() => action.Execute(new ActionContext { PreviousState = state, @@ -117,7 +117,7 @@ public void Remove_Throws_WhenDoNotExistValidator() { var state = new World(MockUtil.MockModernWorldState); var action = ValidatorSetOperate.Remove(_validator); - InvalidOperationException exc = Assert.Throws(() => + var exc = Assert.Throws(() => action.Execute(new ActionContext { PreviousState = state, @@ -130,7 +130,7 @@ public void Remove_Throws_WhenDoNotExistValidator() [Fact] public void Append() { - PublicKey validatorPubKey = new PrivateKey().PublicKey; + var validatorPubKey = new PrivateKey().PublicKey; var validator = new Validator(validatorPubKey, BigInteger.One); var action = ValidatorSetOperate.Append(validator); var states = action.Execute(new ActionContext diff --git a/.Lib9c.Tests/Action/WorldBossHelperTest.cs b/.Lib9c.Tests/Action/WorldBossHelperTest.cs index eb4dfaec31..1ba5773fcd 100644 --- a/.Lib9c.Tests/Action/WorldBossHelperTest.cs +++ b/.Lib9c.Tests/Action/WorldBossHelperTest.cs @@ -13,8 +13,7 @@ public class WorldBossHelperTest { private readonly Currency _crystalCurrency = CrystalCalculator.CRYSTAL; - private readonly TableSheets _tableSheets = - new TableSheets(TableSheetsImporter.ImportSheets()); + private readonly TableSheets _tableSheets = new (TableSheetsImporter.ImportSheets()); [Theory] [InlineData(10, 10, 0, 10)] diff --git a/.Lib9c.Tests/AddressesTest.cs b/.Lib9c.Tests/AddressesTest.cs index 880f1ff81a..a6b9fc1ba9 100644 --- a/.Lib9c.Tests/AddressesTest.cs +++ b/.Lib9c.Tests/AddressesTest.cs @@ -1,75 +1,76 @@ -namespace Lib9c.Tests; - -using System; -using System.Collections.Generic; -using System.Reflection; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Nekoyume; -using Xunit; - -public class AddressesTest +namespace Lib9c.Tests { - [Fact] - public void There_Are_No_Address_Conflicts() - { - var addressesInTypes = new List
(); - InsertStaticAddressFieldValues(typeof(ReservedAddresses)); - InsertStaticAddressFieldValues(typeof(Addresses)); + using System; + using System.Collections.Generic; + using System.Reflection; + using Libplanet.Action.State; + using Libplanet.Crypto; + using Nekoyume; + using Xunit; - var addresses = new HashSet
(); - foreach (var address in addressesInTypes) + public class AddressesTest + { + [Fact] + public void There_Are_No_Address_Conflicts() { - Assert.DoesNotContain(address, addresses); - Assert.False(Addresses.IsArenaParticipantAccountAddress(address)); - addresses.Add(address); - } + var addressesInTypes = new List
(); + InsertStaticAddressFieldValues(typeof(ReservedAddresses)); + InsertStaticAddressFieldValues(typeof(Addresses)); - return; + var addresses = new HashSet
(); + foreach (var address in addressesInTypes) + { + Assert.DoesNotContain(address, addresses); + Assert.False(Addresses.IsArenaParticipantAccountAddress(address)); + addresses.Add(address); + } - void InsertStaticAddressFieldValues(Type type) - { - var addressFields = type.GetFields(BindingFlags.Public | BindingFlags.Static); - foreach (var field in addressFields) + return; + + void InsertStaticAddressFieldValues(Type type) { - if (field.FieldType != typeof(Address)) + var addressFields = type.GetFields(BindingFlags.Public | BindingFlags.Static); + foreach (var field in addressFields) { - continue; - } + if (field.FieldType != typeof(Address)) + { + continue; + } - // GetValue(null) because the fields are static - var address = (Address)field.GetValue(null)!; - addressesInTypes.Add(address); + // GetValue(null) because the fields are static + var address = (Address)field.GetValue(null)!; + addressesInTypes.Add(address); + } } } - } - [Theory] - [InlineData(0, 0, "0100000000000000000000000000000000000000")] - [InlineData(1, 1, "0100000000000000000000000000000000000101")] - [InlineData(int.MaxValue, 99, "0100000000000000000000000000214748364799")] - public void GetArenaParticipantAccountAddressTest(int championshipId, int round, string expectedHex) - { - var address = Addresses.GetArenaParticipantAccountAddress(championshipId, round); - Assert.Equal(expectedHex, address.ToHex()); - } - - [Theory] - [InlineData("0000000000000000000000000000000000000000", false)] - [InlineData("0099999999999999999999999999999999999999", false)] - [InlineData("0100000000000000000000000000000000000000", true)] - [InlineData("0199999999999999999999999999999999999999", true)] - [InlineData("0200000000000000000000000000000000000000", false)] - public void IsArenaParticipantAccountAddressTest(string addressHex, bool expected) - { - var address = new Address(addressHex); - if (expected) + [Theory] + [InlineData(0, 0, "0100000000000000000000000000000000000000")] + [InlineData(1, 1, "0100000000000000000000000000000000000101")] + [InlineData(int.MaxValue, 99, "0100000000000000000000000000214748364799")] + public void GetArenaParticipantAccountAddressTest(int championshipId, int round, string expectedHex) { - Assert.True(Addresses.IsArenaParticipantAccountAddress(address)); + var address = Addresses.GetArenaParticipantAccountAddress(championshipId, round); + Assert.Equal(expectedHex, address.ToHex()); } - else + + [Theory] + [InlineData("0000000000000000000000000000000000000000", false)] + [InlineData("0099999999999999999999999999999999999999", false)] + [InlineData("0100000000000000000000000000000000000000", true)] + [InlineData("0199999999999999999999999999999999999999", true)] + [InlineData("0200000000000000000000000000000000000000", false)] + public void IsArenaParticipantAccountAddressTest(string addressHex, bool expected) { - Assert.False(Addresses.IsArenaParticipantAccountAddress(address)); + var address = new Address(addressHex); + if (expected) + { + Assert.True(Addresses.IsArenaParticipantAccountAddress(address)); + } + else + { + Assert.False(Addresses.IsArenaParticipantAccountAddress(address)); + } } } } diff --git a/.Lib9c.Tests/Battle/CPHelperTest.cs b/.Lib9c.Tests/Battle/CPHelperTest.cs index 2f48513370..ebbeef2701 100644 --- a/.Lib9c.Tests/Battle/CPHelperTest.cs +++ b/.Lib9c.Tests/Battle/CPHelperTest.cs @@ -27,7 +27,7 @@ public CPHelperTest() [InlineData(10)] public void GetStatsCp(int level) { - CharacterSheet.Row row = + var row = _tableSheets.CharacterSheet[GameConfig.DefaultAvatarCharacterId]; var characterStats = new CharacterStats(row, level); Assert.Equal(CPHelper.GetStatsCP(row.ToStats(level), level), CPHelper.GetStatsCP(characterStats, level)); @@ -36,24 +36,24 @@ public void GetStatsCp(int level) [Fact] public void TotalCP() { - CharacterSheet.Row row = + var row = _tableSheets.CharacterSheet[GameConfig.DefaultAvatarCharacterId]; - CostumeStatSheet costumeStatSheet = _tableSheets.CostumeStatSheet; + var costumeStatSheet = _tableSheets.CostumeStatSheet; var random = new TestRandom(); // Arrange - List equipments = new List(); // Populate your equipments + var equipments = new List(); // Populate your equipments var equipment = (Equipment)ItemFactory.CreateItem(_tableSheets.EquipmentItemSheet.Values.First(), random); var skill = SkillFactory.Get(_tableSheets.SkillSheet.Values.First(), 0, 0, 0, StatType.HP); equipment.Skills.Add(skill); equipments.Add(equipment); - List costumes = new List(); // Populate your costumes + var costumes = new List(); // Populate your costumes var costume = ItemFactory.CreateCostume(_tableSheets.CostumeItemSheet.Values.First(), random.GenerateRandomGuid()); costumes.Add(costume); - List runeOptions = new List(); // Populate your runeOptions + var runeOptions = new List(); // Populate your runeOptions var runeOptionInfo = _tableSheets.RuneOptionSheet.Values.First().LevelOptionMap[1]; runeOptions.Add(runeOptionInfo); - int level = 1; // A level for testing - List collectionStatModifiers = new List(); // Populate your collectionStatModifiers + var level = 1; // A level for testing + var collectionStatModifiers = new List(); // Populate your collectionStatModifiers var result = CPHelper.TotalCP(equipments, costumes, runeOptions, level, row, costumeStatSheet, collectionStatModifiers, 0); var characterStats = new CharacterStats(row, level); characterStats.SetEquipments(equipments, new EquipmentItemSetEffectSheet()); diff --git a/.Lib9c.Tests/Battle/SimplePriorityQueueTest.cs b/.Lib9c.Tests/Battle/SimplePriorityQueueTest.cs index 17c082b37a..ccaa24b5b0 100644 --- a/.Lib9c.Tests/Battle/SimplePriorityQueueTest.cs +++ b/.Lib9c.Tests/Battle/SimplePriorityQueueTest.cs @@ -13,19 +13,19 @@ public class SimplePriorityQueueTest [InlineData(1000000, 0.000001)] public void DeterministicFirstDequeue(int loopCount, decimal spd) { - List results = new List(); - for (int i = 0; i < loopCount; i++) + var results = new List(); + for (var i = 0; i < loopCount; i++) { - SimplePriorityQueue queue = new SimplePriorityQueue(); + var queue = new SimplePriorityQueue(); queue.Enqueue(0, spd); queue.Enqueue(1, spd); queue.Enqueue(2, spd); - Assert.True(queue.TryDequeue(out int index)); + Assert.True(queue.TryDequeue(out var index)); results.Add(index); } - for (int i = 0; i < results.Count - 1; i++) + for (var i = 0; i < results.Count - 1; i++) { Assert.Equal(results[i], results[i + 1]); } @@ -36,22 +36,22 @@ public void DeterministicFirstDequeue(int loopCount, decimal spd) [InlineData(1000000, 0.000001)] public void DeterministicIterateDequeueAndEnqueue(int loopCount, decimal spd) { - List results1 = new List(); - List results2 = new List(); - for (int i = 0; i < 2; i++) + var results1 = new List(); + var results2 = new List(); + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); + var queue = new SimplePriorityQueue(); queue.Enqueue(0, spd); queue.Enqueue(1, spd); queue.Enqueue(2, spd); - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out int index)); + Assert.True(queue.TryDequeue(out var index)); targetResults.Add(index); queue.Enqueue(index, spd); @@ -66,23 +66,23 @@ public void DeterministicIterateDequeueAndEnqueue(int loopCount, decimal spd) [InlineData(1000000, 0.000001)] public void DeterministicIterateDequeueAndEnqueueWithMultiplier(int loopCount, decimal spd) { - List results1 = new List(); - List results2 = new List(); + var results1 = new List(); + var results2 = new List(); const decimal multiplier = 0.6m; - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); + var queue = new SimplePriorityQueue(); queue.Enqueue(0, spd * multiplier); queue.Enqueue(1, spd * multiplier); queue.Enqueue(2, spd * multiplier); - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out int index)); + Assert.True(queue.TryDequeue(out var index)); targetResults.Add(index); queue.Enqueue(index, spd * multiplier); @@ -97,23 +97,23 @@ public void DeterministicIterateDequeueAndEnqueueWithMultiplier(int loopCount, d [InlineData(1000000, 0.000001)] public void DeterministicIterateDequeueAndEnqueueWithDivisor(int loopCount, decimal spd) { - List results1 = new List(); - List results2 = new List(); + var results1 = new List(); + var results2 = new List(); const decimal divisor = 987654321m; - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); + var queue = new SimplePriorityQueue(); queue.Enqueue(0, spd / divisor); queue.Enqueue(1, spd / divisor); queue.Enqueue(2, spd / divisor); - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out int index)); + Assert.True(queue.TryDequeue(out var index)); targetResults.Add(index); queue.Enqueue(index, spd / divisor); @@ -128,27 +128,27 @@ public void DeterministicIterateDequeueAndEnqueueWithDivisor(int loopCount, deci [InlineData(1000000, 0.000001)] public void DeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, decimal spd) { - List results1 = new List(); - List results2 = new List(); - for (int i = 0; i < 2; i++) + var results1 = new List(); + var results2 = new List(); + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); + var queue = new SimplePriorityQueue(); queue.Enqueue(0, spd); queue.Enqueue(1, spd); queue.Enqueue(2, spd); - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out int index)); + Assert.True(queue.TryDequeue(out var index)); targetResults.Add(index); - foreach (int otherIndex in queue) + foreach (var otherIndex in queue) { - decimal priority = queue.GetPriority(otherIndex); + var priority = queue.GetPriority(otherIndex); queue.UpdatePriority(otherIndex, priority); } @@ -164,35 +164,35 @@ public void DeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, decima [InlineData(1000000, 0.000001)] public void GuidDeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, decimal spd) { - List results1 = new List(); - List results2 = new List(); - Guid[] guids = new[] + var results1 = new List(); + var results2 = new List(); + var guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), }; - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); - for (int j = 0; j < guids.Length; j++) + var queue = new SimplePriorityQueue(); + for (var j = 0; j < guids.Length; j++) { queue.Enqueue(guids[j], spd); } - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out Guid guid)); + Assert.True(queue.TryDequeue(out var guid)); targetResults.Add(guid); - foreach (Guid otherGuid in queue) + foreach (var otherGuid in queue) { - decimal priority = queue.GetPriority(otherGuid); + var priority = queue.GetPriority(otherGuid); queue.UpdatePriority(otherGuid, priority); } @@ -209,8 +209,8 @@ public void GuidDeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, de public void PlayerDeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, decimal spd) { var sheets = TableSheetsImporter.ImportSheets(); - TableSheets tableSheets = new TableSheets(sheets); - Player[] players = new[] + var tableSheets = new TableSheets(sheets); + var players = new[] { new Player( 1, @@ -229,28 +229,28 @@ public void PlayerDeterministicIterateDequeueAndUpdateAndEnqueue(int loopCount, tableSheets.EquipmentItemSetEffectSheet), }; - List results1 = new List(); - List results2 = new List(); - for (int i = 0; i < 2; i++) + var results1 = new List(); + var results2 = new List(); + for (var i = 0; i < 2; i++) { - List targetResults = i == 0 + var targetResults = i == 0 ? results1 : results2; - SimplePriorityQueue queue = new SimplePriorityQueue(); - for (int j = 0; j < players.Length; j++) + var queue = new SimplePriorityQueue(); + for (var j = 0; j < players.Length; j++) { queue.Enqueue(players[j], spd); } - for (int j = 0; j < loopCount; j++) + for (var j = 0; j < loopCount; j++) { - Assert.True(queue.TryDequeue(out Player player)); + Assert.True(queue.TryDequeue(out var player)); targetResults.Add(player); - foreach (Player otherPlayer in queue) + foreach (var otherPlayer in queue) { - decimal priority = queue.GetPriority(otherPlayer); + var priority = queue.GetPriority(otherPlayer); queue.UpdatePriority(otherPlayer, priority); } diff --git a/.Lib9c.Tests/CrystalCalculatorTest.cs b/.Lib9c.Tests/CrystalCalculatorTest.cs index 2861ac3186..2e303fa1c5 100644 --- a/.Lib9c.Tests/CrystalCalculatorTest.cs +++ b/.Lib9c.Tests/CrystalCalculatorTest.cs @@ -56,8 +56,8 @@ public void CalculateRecipeUnlockCost(int recipeCount) } [Theory] - [InlineData(new[] { 2 }, 500)] - [InlineData(new[] { 2, 3 }, 3000)] + [InlineData(new[] { 2, }, 500)] + [InlineData(new[] { 2, 3, }, 3000)] public void CalculateWorldUnlockCost(IEnumerable worldIds, int expected) { Assert.Equal(expected * CrystalCalculator.CRYSTAL, CrystalCalculator.CalculateWorldUnlockCost(worldIds, _worldUnlockSheet)); @@ -118,7 +118,7 @@ public void CalculateCombinationCost(int psCrystal, int bpsCrystal, int expected r.Type == CrystalFluctuationSheet.ServiceType.Combination); Assert.Equal( expected * CrystalCalculator.CRYSTAL, - CrystalCalculator.CalculateCombinationCost(crystal, row, prevWeeklyCostState: ps, bps) + CrystalCalculator.CalculateCombinationCost(crystal, row, ps, bps) ); } @@ -156,7 +156,7 @@ public void CalculateMaterialCost(int materialId, int materialCount, int expecte private class CalculateCrystalData : IEnumerable { - private readonly List _data = new List + private readonly List _data = new() { // 1 + ((2^0 - 1) * 1) = 1 // enchant level 2 @@ -259,9 +259,15 @@ private class CalculateCrystalData : IEnumerable }, }; - public IEnumerator GetEnumerator() => _data.GetEnumerator(); + public IEnumerator GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => _data.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return _data.GetEnumerator(); + } } } } diff --git a/.Lib9c.Tests/CurrenciesTest.cs b/.Lib9c.Tests/CurrenciesTest.cs index f1b37078c6..c9a2d4e0f6 100644 --- a/.Lib9c.Tests/CurrenciesTest.cs +++ b/.Lib9c.Tests/CurrenciesTest.cs @@ -52,11 +52,11 @@ public static IEnumerable GetSampleCurrencies() if (majorUnit.IsZero) { foreach (var minorUnit in new[] - { - BigInteger.Zero, - maxMinorUnit * BigInteger.One, - maxMinorUnit * BigInteger.MinusOne, - }) + { + BigInteger.Zero, + maxMinorUnit * BigInteger.One, + maxMinorUnit * BigInteger.MinusOne, + }) { yield return new object[] { @@ -67,10 +67,10 @@ public static IEnumerable GetSampleCurrencies() else { foreach (var minorUnit in new[] - { - BigInteger.Zero, - maxMinorUnit * BigInteger.One, - }) + { + BigInteger.Zero, + maxMinorUnit * BigInteger.One, + }) { yield return new object[] { @@ -210,7 +210,7 @@ public void SelectRecipientAddress() Assert.Equal(agentAddress, Currencies.PickAddress(Currencies.Crystal, agentAddress, avatarAddress)); Assert.Equal(agentAddress, Currencies.PickAddress(Currencies.Garage, agentAddress, avatarAddress)); Assert.Equal(agentAddress, Currencies.PickAddress(Currencies.Mead, agentAddress, avatarAddress)); - Assert.Equal(agentAddress, Currencies.PickAddress(Currency.Legacy("NCG", decimalPlaces: 2, minter: new PrivateKey().Address), agentAddress, avatarAddress)); + Assert.Equal(agentAddress, Currencies.PickAddress(Currency.Legacy("NCG", 2, new PrivateKey().Address), agentAddress, avatarAddress)); Assert.Equal(avatarAddress, Currencies.PickAddress(Currencies.DailyRewardRune, agentAddress, avatarAddress)); } } diff --git a/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs b/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs index 4447631442..03eb60a8b9 100644 --- a/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs @@ -1,29 +1,30 @@ -namespace Lib9c.Tests.Extensions; - -using System; -using Bencodex.Types; -using Nekoyume.Exceptions; -using Xunit; - -public class BencodexTypesExtensionsTest +namespace Lib9c.Tests.Extensions { - [Theory] - [InlineData(0, 0, true)] - [InlineData(1, 0, false)] - [InlineData(2, 1, false)] - [InlineData(2, 2, true)] - public void Replace_List(int count, int index, bool throwException) + using System; + using Bencodex.Types; + using Nekoyume.Exceptions; + using Xunit; + + public class BencodexTypesExtensionsTest { - var list = new List(new int[count]); - if (throwException) - { - Assert.Throws(() => - list.Replace(index, (Integer)1)); - } - else + [Theory] + [InlineData(0, 0, true)] + [InlineData(1, 0, false)] + [InlineData(2, 1, false)] + [InlineData(2, 2, true)] + public void Replace_List(int count, int index, bool throwException) { - list = list.Replace(index, (Integer)1); - Assert.Equal(1, (int)(Integer)list[index]); + var list = new List(new int[count]); + if (throwException) + { + Assert.Throws(() => + list.Replace(index, (Integer)1)); + } + else + { + list = list.Replace(index, (Integer)1); + Assert.Equal(1, (int)(Integer)list[index]); + } } } } diff --git a/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs b/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs index a78c64e747..fbb776b4bd 100644 --- a/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs @@ -11,10 +11,12 @@ public class EventDungeonExtensionsTest [InlineData(99_999_999, 9_999)] public void ToEventDungeonStageNumber( int eventDungeonStageId, - int expected) => + int expected) + { Assert.Equal( expected, eventDungeonStageId.ToEventDungeonStageNumber()); + } [Theory] [InlineData(int.MinValue)] @@ -30,8 +32,10 @@ public void ToEventDungeonStageNumber( [InlineData(100_000_000)] [InlineData(int.MaxValue)] public void ToEventDungeonStageNumber_Throw_ArgumentException( - int eventDungeonStageId) => + int eventDungeonStageId) + { Assert.Throws(() => eventDungeonStageId.ToEventDungeonStageNumber()); + } } } diff --git a/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs b/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs index 4f5e853e49..75e4692ea7 100644 --- a/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs @@ -13,10 +13,12 @@ public class EventScheduleExtensionsTest [InlineData(99_999_999, 9_999)] public void ToEventScheduleId( int eventDungeonId, - int expected) => + int expected) + { Assert.Equal( expected, eventDungeonId.ToEventScheduleId()); + } [Theory] [InlineData(int.MinValue)] @@ -32,9 +34,11 @@ public void ToEventScheduleId( [InlineData(100_000_000)] [InlineData(int.MaxValue)] public void ToEventScheduleId_Throw_ArgumentException( - int eventDungeonId) => + int eventDungeonId) + { Assert.Throws(() => eventDungeonId.ToEventScheduleId()); + } [Theory] [InlineData(0, 0, 0, 0L)] diff --git a/.Lib9c.Tests/Fixtures/TableCSV/CollectionSheetFixture.cs b/.Lib9c.Tests/Fixtures/TableCSV/CollectionSheetFixture.cs index 200b7324bb..1d351ddc71 100644 --- a/.Lib9c.Tests/Fixtures/TableCSV/CollectionSheetFixture.cs +++ b/.Lib9c.Tests/Fixtures/TableCSV/CollectionSheetFixture.cs @@ -1,8 +1,9 @@ -namespace Lib9c.Tests.Fixtures.TableCSV; - -public static class CollectionSheetFixture +namespace Lib9c.Tests.Fixtures.TableCSV { - public const string Default = @"id,item_id1,count1,level1,skill1,item_id2,count2,level2,skill2,item_id3,count3,level3,skill3,item_id4,count4,level4,skill4,item_id5,count5,level5,skill5,item_id6,count6,level6,skill6,stat_type1,modify_type1,modify_value1,stat_type2,modify_type2,modify_value2,stat_type3,modify_type3,modify_value3 + public static class CollectionSheetFixture + { + public const string Default = + @"id,item_id1,count1,level1,skill1,item_id2,count2,level2,skill2,item_id3,count3,level3,skill3,item_id4,count4,level4,skill4,item_id5,count5,level5,skill5,item_id6,count6,level6,skill6,stat_type1,modify_type1,modify_value1,stat_type2,modify_type2,modify_value2,stat_type3,modify_type3,modify_value3 1,10110000,1,0,TRUE,10211000,1,0,TRUE,10510000,1,0,TRUE,10120000,1,0,TRUE,10222000,1,0,TRUE,,,,,HP,Add,310,ATK,Add,110,DEF,Add,22 2,10110000,1,0,TRUE,10114000,1,0,TRUE,,,,,,,,,,,,,,,,,ATK,Add,177,,,,,, 3,10120000,1,0,TRUE,10124000,1,0,TRUE,,,,,,,,,,,,,,,,,ATK,Add,125,,,,,, @@ -576,4 +577,5 @@ public static class CollectionSheetFixture 1000178,600203,20,,FALSE,,,,,,,,,,,,,,,,,,,,,DEF,Percentage,4,,,,,, 1000179,600203,20,,FALSE,,,,,,,,,,,,,,,,,,,,,HIT,Percentage,4,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,CDMG,Percentage,10,,,,,,"; + } } diff --git a/.Lib9c.Tests/Fixtures/TableCSV/EquipmentItemSheetFixture.cs b/.Lib9c.Tests/Fixtures/TableCSV/EquipmentItemSheetFixture.cs index d88c358904..ded7fc85ee 100644 --- a/.Lib9c.Tests/Fixtures/TableCSV/EquipmentItemSheetFixture.cs +++ b/.Lib9c.Tests/Fixtures/TableCSV/EquipmentItemSheetFixture.cs @@ -181,7 +181,8 @@ public static class EquipmentItemSheetFixture 176,10640001,303304,360,0,0,3000,335,104540011,,,1000000,Necklace 177,10650001,303304,360,0,0,3000,335,104540011,,,1000000,Necklace"; - public const string LegacyEnhancementCostSheetV2 = @"id,item_sub_type,grade,level,cost,success_ratio,great_success_ratio,fail_ratio,success_required_block_index,great_success_required_block_index,fail_required_block_index,base_stat_growth_min,base_stat_growth_max,extra_stat_growth_min,extra_stat_growth_max,extra_skill_damage_growth_min,extra_skill_damage_growth_max,extra_skill_chance_growth_min,extra_skill_chance_growth_max + public const string LegacyEnhancementCostSheetV2 = + @"id,item_sub_type,grade,level,cost,success_ratio,great_success_ratio,fail_ratio,success_required_block_index,great_success_required_block_index,fail_required_block_index,base_stat_growth_min,base_stat_growth_max,extra_stat_growth_min,extra_stat_growth_max,extra_skill_damage_growth_min,extra_skill_damage_growth_max,extra_skill_chance_growth_min,extra_skill_chance_growth_max 1,Weapon,1,1,0,7500,2500,0,25,31,50,800,1200,0,0,0,0,0,0 2,Weapon,1,2,0,7500,2500,0,62,77,50,800,1200,0,0,0,0,0,0 3,Weapon,1,3,0,7500,2500,0,125,156,50,800,1200,0,0,0,0,0,0 diff --git a/.Lib9c.Tests/Fixtures/TableCSV/RuneOptionSheetFixture.cs b/.Lib9c.Tests/Fixtures/TableCSV/RuneOptionSheetFixture.cs index 680e69860e..6b551da6f1 100644 --- a/.Lib9c.Tests/Fixtures/TableCSV/RuneOptionSheetFixture.cs +++ b/.Lib9c.Tests/Fixtures/TableCSV/RuneOptionSheetFixture.cs @@ -1,8 +1,8 @@ -namespace Lib9c.Tests.Fixtures.TableCSV; - -public static class RuneOptionSheetFixture +namespace Lib9c.Tests.Fixtures.TableCSV { - public const string Default = @"rune_id,level,total_cp,stat_type_1,value_1,value_type_1,stat_type_2,value_2,value_type_2,stat_type_3,value_3,value_type3,skillId,cooldown,chance,skill_value,skill_stat_ratio,skill_value_type,stat_reference_type,buff_duration + public static class RuneOptionSheetFixture + { + public const string Default = @"rune_id,level,total_cp,stat_type_1,value_1,value_type_1,stat_type_2,value_2,value_type_2,stat_type_3,value_3,value_type3,skillId,cooldown,chance,skill_value,skill_stat_ratio,skill_value_type,stat_reference_type,buff_duration 30001,1,364,HP,520,Add,NONE,0,Add,NONE,0,Add,,,,,,,, 30001,2,504,HP,720,Add,NONE,0,Add,NONE,0,Add,,,,,,,, 30001,3,644,HP,920,Add,NONE,0,Add,NONE,0,Add,,,,,,,, @@ -6903,4 +6903,5 @@ public static class RuneOptionSheetFixture 10035,298,2033000,CRI,19.92,Add,NONE,0,Add,NONE,0,Add,,,,,,,, 10035,299,2048000,CRI,19.96,Add,NONE,0,Add,NONE,0,Add,,,,,,,, 10035,300,2063000,CRI,20,Add,NONE,0,Add,NONE,0,Add,,,,,,,,"; + } } diff --git a/.Lib9c.Tests/Fixtures/TableCSV/Summon/SummonSheetFixtures.cs b/.Lib9c.Tests/Fixtures/TableCSV/Summon/SummonSheetFixtures.cs index 338025e8b2..dd3ce2f1cd 100644 --- a/.Lib9c.Tests/Fixtures/TableCSV/Summon/SummonSheetFixtures.cs +++ b/.Lib9c.Tests/Fixtures/TableCSV/Summon/SummonSheetFixtures.cs @@ -12,7 +12,8 @@ public class SummonSheetFixtures 10001,800201,10,0,171,70,172,29,173,1,,,,,,,,,,,,,,,,,,,,,,,, 10002,600201,20,0,174,6500,175,2940,176,510,177,45,178,5,179,6500,180,2940,181,510,182,45,183,5,184,6500,185,2940,186,510,187,45,188,5"; - public const string V3 = @"groupID,cost_material,cost_material_count,cost_ncg,recipe1ID,recipe1ratio,recipe2ID,recipe2ratio,recipe3ID,recipe3ratio,recipe4ID,recipe4ratio,recipe5ID,recipe5ratio,recipe6ID,recipe6ratio,recipe7ID,recipe7ratio,recipe8ID,recipe8ratio,recipe9ID,recipe9ratio,recipe10ID,recipe10ratio,recipe11ID,recipe11ratio,recipe12ID,recipe12ratio,recipe13ID,recipe13ratio,recipe14ID,recipe14ratio,recipe15ID,recipe15ratio + public const string V3 = + @"groupID,cost_material,cost_material_count,cost_ncg,recipe1ID,recipe1ratio,recipe2ID,recipe2ratio,recipe3ID,recipe3ratio,recipe4ID,recipe4ratio,recipe5ID,recipe5ratio,recipe6ID,recipe6ratio,recipe7ID,recipe7ratio,recipe8ID,recipe8ratio,recipe9ID,recipe9ratio,recipe10ID,recipe10ratio,recipe11ID,recipe11ratio,recipe12ID,recipe12ratio,recipe13ID,recipe13ratio,recipe14ID,recipe14ratio,recipe15ID,recipe15ratio 10001,800201,10,0,171,70,172,29,173,1,,,,,,,,,,,,,,,,,,,,,,,, 10002,600201,20,0,174,6500,175,2940,176,510,177,45,178,5,179,6500,180,2940,181,510,182,45,183,5,184,6500,185,2940,186,510,187,45,188,5 20001,600201,10,0,10021,20,10022,20,10023,20,10024,20,10025,60,10026,60,10027,60,10028,60,10001,40,10002,100,10003,200,10011,40,10012,100,10013,200,, diff --git a/.Lib9c.Tests/JsonStatesLoader.cs b/.Lib9c.Tests/JsonStatesLoader.cs index 866e4349af..f6ed1502d1 100644 --- a/.Lib9c.Tests/JsonStatesLoader.cs +++ b/.Lib9c.Tests/JsonStatesLoader.cs @@ -18,7 +18,7 @@ public JsonStatesLoader(IFileSystem fileSystem) _fileSystem = fileSystem; } - public static JsonStatesLoader Default => new JsonStatesLoader(new FileSystem()); + public static JsonStatesLoader Default => new (new FileSystem()); public Dictionary Load(string jsonFilePath) { @@ -32,8 +32,8 @@ public Dictionary Load(string jsonFilePath) throw new FileNotFoundException(); } - string rawJsonString = _fileSystem.File.ReadAllText(jsonFilePath); - Dictionary json = JsonSerializer.Deserialize>(rawJsonString); + var rawJsonString = _fileSystem.File.ReadAllText(jsonFilePath); + var json = JsonSerializer.Deserialize>(rawJsonString); var codec = new Codec(); return json.ToDictionary(pair => pair.Key, pair => codec.Decode(pair.Value)); } diff --git a/.Lib9c.Tests/JsonStatesLoaderTest.cs b/.Lib9c.Tests/JsonStatesLoaderTest.cs index b413d284c1..72b793dc7e 100644 --- a/.Lib9c.Tests/JsonStatesLoaderTest.cs +++ b/.Lib9c.Tests/JsonStatesLoaderTest.cs @@ -15,7 +15,7 @@ public class JsonStatesLoaderTest public void Load() { var codec = new Codec(); - Text barValue = (Text)"bar"; + var barValue = (Text)"bar"; IFileSystem fileSystem = new MockFileSystem(new Dictionary { { "/foo", new MockFileData($"{{\"foo\": \"{Convert.ToBase64String(codec.Encode(barValue))}\"}}") }, diff --git a/.Lib9c.Tests/Model/ActivationKeyTest.cs b/.Lib9c.Tests/Model/ActivationKeyTest.cs index 75948036f2..b0debd50ab 100644 --- a/.Lib9c.Tests/Model/ActivationKeyTest.cs +++ b/.Lib9c.Tests/Model/ActivationKeyTest.cs @@ -12,8 +12,8 @@ public class ActivationKeyTest public void Create() { var privateKey = new PrivateKey(ByteUtil.ParseHex("ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716")); - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; - (ActivationKey ak, PendingActivationState pending) = ActivationKey.Create(privateKey, nonce); + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; + (var ak, var pending) = ActivationKey.Create(privateKey, nonce); Assert.Equal(privateKey, ak.PrivateKey); Assert.Equal(pending.address, ak.PendingAddress); @@ -25,8 +25,8 @@ public void Create() public void Encode() { var privateKey = new PrivateKey(ByteUtil.ParseHex("ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716")); - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; - (ActivationKey ak, var _) = ActivationKey.Create(privateKey, nonce); + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; + var (ak, _) = ActivationKey.Create(privateKey, nonce); Assert.Equal("ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716/46c4365d645647791768b9a9e6e4a9376b15c643", ak.Encode()); } @@ -34,8 +34,8 @@ public void Encode() [Fact] public void Decode() { - string encoded = "ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716/46c4365d645647791768b9a9e6e4a9376b15c643"; - ActivationKey ak = ActivationKey.Decode(encoded); + var encoded = "ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716/46c4365d645647791768b9a9e6e4a9376b15c643"; + var ak = ActivationKey.Decode(encoded); Assert.Equal(new Address("46c4365d645647791768b9a9e6e4a9376b15c643"), ak.PendingAddress); Assert.Equal(new PrivateKey(ByteUtil.ParseHex("ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716")), ak.PrivateKey); diff --git a/.Lib9c.Tests/Model/Arena/ArenaParticipantTest.cs b/.Lib9c.Tests/Model/Arena/ArenaParticipantTest.cs index b1da575ee1..2e51655860 100644 --- a/.Lib9c.Tests/Model/Arena/ArenaParticipantTest.cs +++ b/.Lib9c.Tests/Model/Arena/ArenaParticipantTest.cs @@ -1,46 +1,47 @@ -namespace Lib9c.Tests.Model.Arena; - -using Libplanet.Crypto; -using Nekoyume.Model.Arena; -using Xunit; - -public class ArenaParticipantTest +namespace Lib9c.Tests.Model.Arena { - [Fact] - public void Serialize() + using Libplanet.Crypto; + using Nekoyume.Model.Arena; + using Xunit; + + public class ArenaParticipantTest { - var avatarAddr = new PrivateKey().Address; - var state = new ArenaParticipant(avatarAddr) + [Fact] + public void Serialize() { - Name = "Joy", - PortraitId = 1, - Level = 99, - Cp = 999_999_999, - Score = 999_999, - Ticket = 7, - TicketResetCount = 1, - PurchasedTicketCount = 1, - Win = 100, - Lose = 99, - LastBattleBlockIndex = long.MaxValue, - }; - var serialized = state.Bencoded; - var deserialized = new ArenaParticipant(serialized); + var avatarAddr = new PrivateKey().Address; + var state = new ArenaParticipant(avatarAddr) + { + Name = "Joy", + PortraitId = 1, + Level = 99, + Cp = 999_999_999, + Score = 999_999, + Ticket = 7, + TicketResetCount = 1, + PurchasedTicketCount = 1, + Win = 100, + Lose = 99, + LastBattleBlockIndex = long.MaxValue, + }; + var serialized = state.Bencoded; + var deserialized = new ArenaParticipant(serialized); - Assert.Equal(state.AvatarAddr, deserialized.AvatarAddr); - Assert.Equal(state.Name, deserialized.Name); - Assert.Equal(state.PortraitId, deserialized.PortraitId); - Assert.Equal(state.Level, deserialized.Level); - Assert.Equal(state.Cp, deserialized.Cp); - Assert.Equal(state.Score, deserialized.Score); - Assert.Equal(state.Ticket, deserialized.Ticket); - Assert.Equal(state.TicketResetCount, deserialized.TicketResetCount); - Assert.Equal(state.PurchasedTicketCount, deserialized.PurchasedTicketCount); - Assert.Equal(state.Win, deserialized.Win); - Assert.Equal(state.Lose, deserialized.Lose); - Assert.Equal(state.LastBattleBlockIndex, deserialized.LastBattleBlockIndex); + Assert.Equal(state.AvatarAddr, deserialized.AvatarAddr); + Assert.Equal(state.Name, deserialized.Name); + Assert.Equal(state.PortraitId, deserialized.PortraitId); + Assert.Equal(state.Level, deserialized.Level); + Assert.Equal(state.Cp, deserialized.Cp); + Assert.Equal(state.Score, deserialized.Score); + Assert.Equal(state.Ticket, deserialized.Ticket); + Assert.Equal(state.TicketResetCount, deserialized.TicketResetCount); + Assert.Equal(state.PurchasedTicketCount, deserialized.PurchasedTicketCount); + Assert.Equal(state.Win, deserialized.Win); + Assert.Equal(state.Lose, deserialized.Lose); + Assert.Equal(state.LastBattleBlockIndex, deserialized.LastBattleBlockIndex); - var serialized2 = deserialized.Bencoded; - Assert.Equal(serialized, serialized2); + var serialized2 = deserialized.Bencoded; + Assert.Equal(serialized, serialized2); + } } } diff --git a/.Lib9c.Tests/Model/Arena/PlayerDigestTest.cs b/.Lib9c.Tests/Model/Arena/PlayerDigestTest.cs index 061a0f35ee..44799f5880 100644 --- a/.Lib9c.Tests/Model/Arena/PlayerDigestTest.cs +++ b/.Lib9c.Tests/Model/Arena/PlayerDigestTest.cs @@ -57,8 +57,8 @@ public PlayerDigestTest() _avatarState = avatarState; _arenaAvatarState = new ArenaAvatarState(_avatarState); - _arenaAvatarState.UpdateEquipment(new List() { weapon.ItemId, armor.ItemId }); - _arenaAvatarState.UpdateCostumes(new List() { costume.ItemId, costume2.ItemId }); + _arenaAvatarState.UpdateEquipment(new List() { weapon.ItemId, armor.ItemId, }); + _arenaAvatarState.UpdateCostumes(new List() { costume.ItemId, costume2.ItemId, }); } [Fact] @@ -98,8 +98,8 @@ public void SerializeWithoutRune() [Theory] [InlineData(new int[] { })] - [InlineData(new[] { 10001 })] - [InlineData(new[] { 10001, 10002 })] + [InlineData(new[] { 10001, })] + [InlineData(new[] { 10001, 10002, })] public void SerializeWithRune(int[] runeIds) { var runes = new AllRuneState(); diff --git a/.Lib9c.Tests/Model/ArenaSimulatorTest.cs b/.Lib9c.Tests/Model/ArenaSimulatorTest.cs index a40940ceb0..397e9f285c 100644 --- a/.Lib9c.Tests/Model/ArenaSimulatorTest.cs +++ b/.Lib9c.Tests/Model/ArenaSimulatorTest.cs @@ -82,7 +82,7 @@ public void Simulate() _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet ); - CharacterSheet.Row row = + var row = _tableSheets.CharacterSheet[GameConfig.DefaultAvatarCharacterId]; var expectedHp = (new CharacterStats(row, myDigest.Level).HP + 100) * simulator.HpModifier; @@ -302,7 +302,7 @@ public void Bleed() var runes = new AllRuneState(10003, 89); var runeSlotState = new RuneSlotState(BattleType.Arena); - runeSlotState.UpdateSlot(new List { new (3, 10003) }, _tableSheets.RuneListSheet); + runeSlotState.UpdateSlot(new List { new (3, 10003), }, _tableSheets.RuneListSheet); const int runeBonus = 896; // Base stat 1777 * 50.424% bonus from RuneLevelBonusSheet const int finalAtk = totalAtk + runeBonus; @@ -376,8 +376,8 @@ public void IceShield() avatarState2.inventory.AddItem(equipment); var runeSlotState = new RuneSlotState(BattleType.Arena); var simulator = new ArenaSimulator(random); - var myDigest = new ArenaPlayerDigest(avatarState1, new List(), new List { equipment }, runes, runeSlotState); - var enemyDigest = new ArenaPlayerDigest(avatarState2, new List(), new List { equipment }, runes, runeSlotState); + var myDigest = new ArenaPlayerDigest(avatarState1, new List(), new List { equipment, }, runes, runeSlotState); + var enemyDigest = new ArenaPlayerDigest(avatarState2, new List(), new List { equipment, }, runes, runeSlotState); var arenaSheets = _tableSheets.GetArenaSimulatorSheets(); var log = simulator.Simulate(myDigest, enemyDigest, arenaSheets, new List(), new List(), _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet, true); var spawns = log.Events.OfType().ToList(); diff --git a/.Lib9c.Tests/Model/BattleLogTest.cs b/.Lib9c.Tests/Model/BattleLogTest.cs index f1f6c66ac1..0b5564ba51 100644 --- a/.Lib9c.Tests/Model/BattleLogTest.cs +++ b/.Lib9c.Tests/Model/BattleLogTest.cs @@ -57,7 +57,7 @@ public void IsClearBeforeSimulate() new List(), _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet - ); + ); Assert.False(simulator.Log.IsClear); } diff --git a/.Lib9c.Tests/Model/CharacterStatsTest.cs b/.Lib9c.Tests/Model/CharacterStatsTest.cs index b6f5c45e9e..7ea14684d7 100644 --- a/.Lib9c.Tests/Model/CharacterStatsTest.cs +++ b/.Lib9c.Tests/Model/CharacterStatsTest.cs @@ -28,14 +28,14 @@ public void DeBuffLimit() var groupId = deBuff.RowData.GroupId; deBuffLimitSheet.Set($"group_id,percentage\n{groupId},-50"); var def = stats.DEF; - stats.AddBuff(deBuff, deBuffLimitSheet: deBuffLimitSheet); + stats.AddBuff(deBuff, deBuffLimitSheet); var modifier = deBuffLimitSheet[groupId].GetModifier(deBuff.RowData.StatType); Assert.Equal(modifier.GetModifiedAll(def), stats.DEF); // -500% critical with no limit var deBuff2 = new StatBuff(_tableSheets.StatBuffSheet[204003]); Assert.True(stats.CRI > 0); - stats.AddBuff(deBuff2, deBuffLimitSheet: deBuffLimitSheet); + stats.AddBuff(deBuff2, deBuffLimitSheet); Assert.Equal(0, stats.CRI); } } diff --git a/.Lib9c.Tests/Model/Coupons/CouponTest.cs b/.Lib9c.Tests/Model/Coupons/CouponTest.cs index 695e1e6b89..0ea3366336 100644 --- a/.Lib9c.Tests/Model/Coupons/CouponTest.cs +++ b/.Lib9c.Tests/Model/Coupons/CouponTest.cs @@ -40,7 +40,7 @@ public void Constructors() coupon, new Coupon( Guid.Parse("4a09d5d1-d702-45d5-aa6f-44e19bdab42d"), - new List<(int, uint)> { (1, 2U), (3, 4U) } + new List<(int, uint)> { (1, 2U), (3, 4U), } ) ); Assert.Equal( diff --git a/.Lib9c.Tests/Model/Coupons/RewardSetTest.cs b/.Lib9c.Tests/Model/Coupons/RewardSetTest.cs index 3a531683b6..d301ca8194 100644 --- a/.Lib9c.Tests/Model/Coupons/RewardSetTest.cs +++ b/.Lib9c.Tests/Model/Coupons/RewardSetTest.cs @@ -18,7 +18,7 @@ public void Constructors() Assert.Equal(emptySet, new RewardSet(new (int, uint)[0])); var set = new RewardSet(ImmutableDictionary.Empty.Add(1, 2).Add(3, 4)); - Assert.Equal(set, new RewardSet(new List<(int, uint)> { (1, 2U), (3, 4U) })); + Assert.Equal(set, new RewardSet(new List<(int, uint)> { (1, 2U), (3, 4U), })); Assert.Equal(set, new RewardSet((1, 2U), (3, 4U))); } diff --git a/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs b/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs index 081f6e0d36..19d93b9a0e 100644 --- a/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs +++ b/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs @@ -57,13 +57,15 @@ public void Constructor_Throw_ArgumentException( int resetTicketsInterval, int remainingTickets, int numberOfTicketPurchases, - int clearedStageId) => + int clearedStageId) + { Assert.Throws(() => new EventDungeonInfo( resetTicketsInterval, remainingTickets, numberOfTicketPurchases, clearedStageId)); + } [Theory] [InlineData(1)] diff --git a/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs b/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs index 7f68960c43..4f2aa0b435 100644 --- a/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs +++ b/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs @@ -15,8 +15,8 @@ public class FungibleItemGarageTest public FungibleItemGarageTest() { if (!TableSheetsImporter.TryGetCsv( - nameof(MaterialItemSheet), - out var materialItemSheetCsv)) + nameof(MaterialItemSheet), + out var materialItemSheetCsv)) { throw new Exception("Failed to load MaterialItemSheet.csv"); } diff --git a/.Lib9c.Tests/Model/Item/CostumeTest.cs b/.Lib9c.Tests/Model/Item/CostumeTest.cs index a3df0ac735..b02a56cad0 100644 --- a/.Lib9c.Tests/Model/Item/CostumeTest.cs +++ b/.Lib9c.Tests/Model/Item/CostumeTest.cs @@ -78,7 +78,7 @@ public void SerializeWithRequiredBlockIndex() { // Check RequiredBlockIndex 0 case; var costume = new Costume(_costumeRow, Guid.NewGuid()); - Dictionary serialized = (Dictionary)costume.Serialize(); + var serialized = (Dictionary)costume.Serialize(); Assert.False(serialized.ContainsKey(RequiredBlockIndexKey)); Assert.Equal(costume, new Costume(serialized)); @@ -94,7 +94,7 @@ public void DeserializeThrowArgumentOurOfRangeException() var costume = new Costume(_costumeRow, Guid.NewGuid()); Assert.Equal(0, costume.RequiredBlockIndex); - Dictionary serialized = (Dictionary)costume.Serialize(); + var serialized = (Dictionary)costume.Serialize(); serialized = serialized.SetItem(RequiredBlockIndexKey, "-1"); Assert.Throws(() => new Costume(serialized)); } diff --git a/.Lib9c.Tests/Model/Item/EquipmentTest.cs b/.Lib9c.Tests/Model/Item/EquipmentTest.cs index 78c8c28b24..f775138c39 100644 --- a/.Lib9c.Tests/Model/Item/EquipmentTest.cs +++ b/.Lib9c.Tests/Model/Item/EquipmentTest.cs @@ -61,7 +61,7 @@ public void Serialize(long exp) public void LevelUp() { var row = new EquipmentItemSheet.Row(); - row.Set(new List() { "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000" }); + row.Set(new List() { "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", }); var equipment = (Equipment)ItemFactory.CreateItemUsable(row, default, 0, 0); Assert.Equal(1m, equipment.StatsMap.ATK); diff --git a/.Lib9c.Tests/Model/Item/InventoryTest.cs b/.Lib9c.Tests/Model/Item/InventoryTest.cs index 034a9a9fdd..acc3d25385 100644 --- a/.Lib9c.Tests/Model/Item/InventoryTest.cs +++ b/.Lib9c.Tests/Model/Item/InventoryTest.cs @@ -954,7 +954,7 @@ public void RemoveConsumable() { var row = TableSheets.ConsumableItemSheet.Values.First(); var inventory = new Inventory(); - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { var consumable = ItemFactory.CreateItemUsable(row, Guid.NewGuid(), 4 + i); inventory.AddItem(consumable); diff --git a/.Lib9c.Tests/Model/Item/ShopItemTest.cs b/.Lib9c.Tests/Model/Item/ShopItemTest.cs index 366d947f65..06d4aacf7c 100644 --- a/.Lib9c.Tests/Model/Item/ShopItemTest.cs +++ b/.Lib9c.Tests/Model/Item/ShopItemTest.cs @@ -99,17 +99,20 @@ public void DeserializeThrowArgumentOurOfRangeException() new FungibleAssetValue(_currency, 100, 0), 0, (ITradableItem)equipment); - Dictionary serialized = (Dictionary)shopItem.Serialize(); + var serialized = (Dictionary)shopItem.Serialize(); serialized = serialized.SetItem(ShopItem.ExpiredBlockIndexKey, "-1"); Assert.Throws(() => new ShopItem(serialized)); } - private static ShopItem[] GetShopItems() => new[] + private static ShopItem[] GetShopItems() { - GetShopItemWithFirstCostume(), - GetShopItemWithFirstEquipment(), - GetShopItemWithFirstMaterial(), - }; + return new[] + { + GetShopItemWithFirstCostume(), + GetShopItemWithFirstEquipment(), + GetShopItemWithFirstMaterial(), + }; + } private static ShopItem GetShopItemWithFirstCostume() { diff --git a/.Lib9c.Tests/Model/ItemUsableTest.cs b/.Lib9c.Tests/Model/ItemUsableTest.cs index 7372d75090..94193b4d9e 100644 --- a/.Lib9c.Tests/Model/ItemUsableTest.cs +++ b/.Lib9c.Tests/Model/ItemUsableTest.cs @@ -20,8 +20,8 @@ public void Serialize() { var row = _tableSheets.EquipmentItemSheet.Values.First(); var itemUsable = (Equipment)ItemFactory.CreateItemUsable(row, default, 0); - var skillIds = new[] { 100001, 100003 }; - var buffIds = new[] { 200000, 210000 }; + var skillIds = new[] { 100001, 100003, }; + var buffIds = new[] { 200000, 210000, }; for (var index = 0; index < skillIds.Length; index++) { var skillId = skillIds[index]; diff --git a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs index 8c32c7afa3..c32f24f952 100644 --- a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs @@ -1,36 +1,37 @@ -namespace Lib9c.Tests.Model.Mail; - -using System; -using System.Collections.Generic; -using Bencodex.Types; -using Nekoyume.Model.Item; -using Nekoyume.Model.Mail; -using Nekoyume.TableData; -using Xunit; -using Libplanet.Types.Assets; - -public class CustomCraftMailTest +namespace Lib9c.Tests.Model.Mail { + using System; + using System.Collections.Generic; + using Bencodex.Types; + using Nekoyume.Model.Item; + using Nekoyume.Model.Mail; + using Nekoyume.TableData; + using Xunit; + using Libplanet.Types.Assets; + + public class CustomCraftMailTest + { #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 - private readonly Currency _currency = Currency.Legacy("CRYSTAL", 18, null); + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 + private readonly Currency _currency = Currency.Legacy("CRYSTAL", 18, null); #pragma warning restore CS0618 - [Fact] - public void Serialize() - { - var row = new EquipmentItemSheet.Row(); - row.Set(new List - { "20151000", "Weapon", "6", "Normal", "0", "ATK", "10", "0", "20160000", "0" }); - var equipment = (Equipment)ItemFactory.CreateItemUsable(row, Guid.NewGuid(), 1L); - var mail = new CustomCraftMail(1, Guid.NewGuid(), 2, equipment); - var serialized = (Dictionary)mail.Serialize(); - var deserialized = (CustomCraftMail)Nekoyume.Model.Mail.Mail.Deserialize(serialized); + [Fact] + public void Serialize() + { + var row = new EquipmentItemSheet.Row(); + row.Set(new List + { "20151000", "Weapon", "6", "Normal", "0", "ATK", "10", "0", "20160000", "0", }); + var equipment = (Equipment)ItemFactory.CreateItemUsable(row, Guid.NewGuid(), 1L); + var mail = new CustomCraftMail(1, Guid.NewGuid(), 2, equipment); + var serialized = (Dictionary)mail.Serialize(); + var deserialized = (CustomCraftMail)Nekoyume.Model.Mail.Mail.Deserialize(serialized); - Assert.Equal(1, deserialized.blockIndex); - Assert.Equal(2, deserialized.requiredBlockIndex); - var eq = deserialized.Equipment; - Assert.Equal(ItemSubType.Weapon, eq.ItemSubType); - Assert.Equal(20151000, eq.IconId); + Assert.Equal(1, deserialized.blockIndex); + Assert.Equal(2, deserialized.requiredBlockIndex); + var eq = deserialized.Equipment; + Assert.Equal(ItemSubType.Weapon, eq.ItemSubType); + Assert.Equal(20151000, eq.IconId); + } } } diff --git a/.Lib9c.Tests/Model/Mail/MonsterCollectMailTest.cs b/.Lib9c.Tests/Model/Mail/MonsterCollectMailTest.cs index 0b6b559618..99263db192 100644 --- a/.Lib9c.Tests/Model/Mail/MonsterCollectMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/MonsterCollectMailTest.cs @@ -24,20 +24,20 @@ public MonsterCollectMailTest() [Fact] public void Serialize() { - Guid guid = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); - Address address = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); - List rewards = _tableSheets.MonsterCollectionRewardSheet.First!.Rewards; + var guid = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); + var address = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); + var rewards = _tableSheets.MonsterCollectionRewardSheet.First!.Rewards; Assert.Equal(2, rewards.Count); - MonsterCollectionResult result = new MonsterCollectionResult(guid, address, rewards); - MonsterCollectionMail mail = new MonsterCollectionMail(result, 1, guid, 2); - Dictionary serialized = (Dictionary)mail.Serialize(); - MonsterCollectionMail deserialized = new MonsterCollectionMail(serialized); + var result = new MonsterCollectionResult(guid, address, rewards); + var mail = new MonsterCollectionMail(result, 1, guid, 2); + var serialized = (Dictionary)mail.Serialize(); + var deserialized = new MonsterCollectionMail(serialized); Assert.Equal(1, deserialized.blockIndex); Assert.Equal(2, deserialized.requiredBlockIndex); Assert.Equal(guid, deserialized.id); - MonsterCollectionResult attachment = (MonsterCollectionResult)deserialized.attachment; + var attachment = (MonsterCollectionResult)deserialized.attachment; Assert.Equal(2, attachment.rewards.Count); Assert.Equal(rewards.First(), attachment.rewards.First()); } @@ -45,24 +45,24 @@ public void Serialize() [Fact] public void Serialize_DotNet_API() { - Guid guid = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); - Address address = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); - List rewards = _tableSheets.MonsterCollectionRewardSheet.First!.Rewards; + var guid = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); + var address = new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"); + var rewards = _tableSheets.MonsterCollectionRewardSheet.First!.Rewards; Assert.Equal(2, rewards.Count); - MonsterCollectionResult result = new MonsterCollectionResult(guid, address, rewards); - MonsterCollectionMail mail = new MonsterCollectionMail(result, 1, guid, 2); - BinaryFormatter formatter = new BinaryFormatter(); - using MemoryStream ms = new MemoryStream(); + var result = new MonsterCollectionResult(guid, address, rewards); + var mail = new MonsterCollectionMail(result, 1, guid, 2); + var formatter = new BinaryFormatter(); + using var ms = new MemoryStream(); formatter.Serialize(ms, mail); ms.Seek(0, SeekOrigin.Begin); - MonsterCollectionMail deserialized = (MonsterCollectionMail)formatter.Deserialize(ms); + var deserialized = (MonsterCollectionMail)formatter.Deserialize(ms); Assert.Equal(1, deserialized.blockIndex); Assert.Equal(2, deserialized.requiredBlockIndex); Assert.Equal(guid, deserialized.id); - MonsterCollectionResult attachment = (MonsterCollectionResult)deserialized.attachment; + var attachment = (MonsterCollectionResult)deserialized.attachment; Assert.Equal(2, attachment.rewards.Count); Assert.Equal(rewards.First(), attachment.rewards.First()); } diff --git a/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs b/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs index d90dcea3cf..bbee6a595a 100644 --- a/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs @@ -16,8 +16,9 @@ namespace Lib9c.Tests.Model.Mail public class UnloadFromMyGaragesRecipientMailTest { - public static IEnumerable Get_Sample_PlainValue() => - UnloadFromMyGaragesTest.Get_Sample_PlainValue().Select(objects => + public static IEnumerable Get_Sample_PlainValue() + { + return UnloadFromMyGaragesTest.Get_Sample_PlainValue().Select(objects => new[] { // objects[0], This test doesn't need to test recipientAvatarAddr. @@ -25,6 +26,7 @@ public static IEnumerable Get_Sample_PlainValue() => objects[2], objects[3], }); + } [Theory] [MemberData(nameof(Get_Sample_PlainValue))] @@ -45,9 +47,9 @@ public void Serialize( var mailValue = mail.Serialize(); var de = new UnloadFromMyGaragesRecipientMail((Dictionary)mailValue); Assert.True(mail.FungibleAssetValues?.SequenceEqual(de.FungibleAssetValues!) ?? - de.FungibleAssetValues is null); + de.FungibleAssetValues is null); Assert.True(mail.FungibleIdAndCounts?.SequenceEqual(de.FungibleIdAndCounts!) ?? - de.FungibleIdAndCounts is null); + de.FungibleIdAndCounts is null); Assert.Equal(mail.Memo, de.Memo); var mailValue2 = de.Serialize(); Assert.Equal(mailValue, mailValue2); diff --git a/.Lib9c.Tests/Model/MonsterCollectSheetTest.cs b/.Lib9c.Tests/Model/MonsterCollectSheetTest.cs index 6393a44ad9..deeb66452a 100644 --- a/.Lib9c.Tests/Model/MonsterCollectSheetTest.cs +++ b/.Lib9c.Tests/Model/MonsterCollectSheetTest.cs @@ -10,7 +10,7 @@ public void Set() { var sheet = new MonsterCollectionSheet(); sheet.Set("level,required_gold,reward_id\n1,500,1"); - MonsterCollectionSheet.Row row = sheet[1]; + var row = sheet[1]; Assert.Equal(1, row.Level); Assert.Equal(500, row.RequiredGold); Assert.Equal(1, row.RewardId); diff --git a/.Lib9c.Tests/Model/MonsterCollectionRewardSheetTest.cs b/.Lib9c.Tests/Model/MonsterCollectionRewardSheetTest.cs index 5f78f09142..7d3e5d95fb 100644 --- a/.Lib9c.Tests/Model/MonsterCollectionRewardSheetTest.cs +++ b/.Lib9c.Tests/Model/MonsterCollectionRewardSheetTest.cs @@ -12,13 +12,13 @@ public void SetToSheet() var sheet = new MonsterCollectionRewardSheet(); sheet.Set("collection_level,item_id,quantity\n1,1,1\n1,2,2"); - MonsterCollectionRewardSheet.Row row = sheet[1]; + var row = sheet[1]; Assert.Equal(1, row.MonsterCollectionLevel); - List rewards = row.Rewards; - for (int i = 0; i < rewards.Count; i++) + var rewards = row.Rewards; + for (var i = 0; i < rewards.Count; i++) { - MonsterCollectionRewardSheet.RewardInfo reward = rewards[i]; + var reward = rewards[i]; Assert.Equal(i + 1, reward.ItemId); Assert.Equal(i + 1, reward.Quantity); } diff --git a/.Lib9c.Tests/Model/Order/FungibleOrderTest.cs b/.Lib9c.Tests/Model/Order/FungibleOrderTest.cs index aa0f788135..37a185320a 100644 --- a/.Lib9c.Tests/Model/Order/FungibleOrderTest.cs +++ b/.Lib9c.Tests/Model/Order/FungibleOrderTest.cs @@ -41,9 +41,9 @@ public FungibleOrderTest() [Fact] public void Serialize() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); - Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var order = OrderFactory.CreateFungibleOrder( Addresses.Admin, Addresses.Blacksmith, orderId, @@ -64,7 +64,7 @@ public void Serialize() Assert.Equal(2, order.ItemCount); Assert.Equal(ItemSubType.Hourglass, order.ItemSubType); - Dictionary serialized = (Dictionary)order.Serialize(); + var serialized = (Dictionary)order.Serialize(); Assert.Equal(order, new FungibleOrder(serialized)); } @@ -72,13 +72,13 @@ public void Serialize() [Fact] public void Serialize_DotNet_Api() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); - Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 - Currency currency = Currency.Legacy("NCG", 2, null); + var currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( Addresses.Admin, Addresses.Blacksmith, orderId, @@ -127,10 +127,10 @@ Type exc { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); ItemBase item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = requiredBlockIndex; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( agentAddress, avatarAddress, orderId, @@ -166,9 +166,9 @@ Type exc public void Sell(OrderData orderData) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - Guid tradableId = TradableMaterial.DeriveTradableId(row.ItemId); - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableId = TradableMaterial.DeriveTradableId(row.ItemId); + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -181,7 +181,7 @@ public void Sell(OrderData orderData) foreach (var (blockIndex, count, _) in orderData.InventoryData) { ItemBase item = ItemFactory.CreateTradableMaterial(row); - ITradableItem tradableItem = (ITradableItem)item; + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = blockIndex; _avatarState.inventory.AddItem(item, count); } @@ -190,7 +190,7 @@ public void Sell(OrderData orderData) if (orderData.Exception is null) { - ITradableItem result = order.Sell2(_avatarState); + var result = order.Sell2(_avatarState); Assert.Equal(order.ExpiredBlockIndex, result.RequiredBlockIndex); Assert.Equal(order.TradableId, result.TradableId); @@ -208,9 +208,9 @@ public void Sell(OrderData orderData) public void Sell2(OrderData orderData) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - Guid tradableId = TradableMaterial.DeriveTradableId(row.ItemId); - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableId = TradableMaterial.DeriveTradableId(row.ItemId); + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -223,7 +223,7 @@ public void Sell2(OrderData orderData) foreach (var (blockIndex, count, isLock) in orderData.InventoryData) { ItemBase item = ItemFactory.CreateTradableMaterial(row); - ITradableItem tradableItem = (ITradableItem)item; + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = blockIndex; OrderLock? orderLock = null; if (isLock) @@ -239,7 +239,7 @@ public void Sell2(OrderData orderData) if (orderData.Exception is null) { - ITradableItem result = order.Sell(_avatarState); + var result = order.Sell(_avatarState); Assert.Equal(order.ExpiredBlockIndex, result.RequiredBlockIndex); Assert.Equal(order.TradableId, result.TradableId); @@ -260,10 +260,10 @@ public void Sell2(OrderData orderData) public void Digest(ItemSubType itemSubType, bool add, Type exc) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); item.RequiredBlockIndex = 1; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -285,7 +285,7 @@ public void Digest(ItemSubType itemSubType, bool add, Type exc) Assert.True(_avatarState.inventory.TryGetTradableItem(order.TradableId, order.ExpiredBlockIndex, 1, out _)); Assert.False(_avatarState.inventory.TryGetTradableItem(order.TradableId, 1, 1, out _)); - ITradableItem result = order.Cancel2(_avatarState, 1); + var result = order.Cancel2(_avatarState, 1); Assert.False(_avatarState.inventory.TryGetTradableItem(order.TradableId, order.ExpiredBlockIndex, 1, out _)); Assert.True(_avatarState.inventory.TryGetTradableItem(order.TradableId, 1, 1, out _)); @@ -317,13 +317,13 @@ Type exc ) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); + var item = ItemFactory.CreateTradableMaterial(row); item.RequiredBlockIndex = 1; - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; var tradableId = useTradableId ? item.TradableId : default; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( agentAddress, avatarAddress, orderId, @@ -370,13 +370,13 @@ Type exc ) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); + var item = ItemFactory.CreateTradableMaterial(row); item.RequiredBlockIndex = 1; - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; var tradableId = useTradableId ? item.TradableId : default; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( agentAddress, avatarAddress, orderId, @@ -411,10 +411,10 @@ Type exc public void Cancel(ItemSubType itemSubType, bool add, bool exist, long blockIndex, int itemCount, Type exc) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); item.RequiredBlockIndex = 1; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -441,11 +441,11 @@ public void Cancel(ItemSubType itemSubType, bool add, bool exist, long blockInde Assert.True(_avatarState.inventory.TryGetTradableItem(item.TradableId, order.ExpiredBlockIndex, itemCount, out _)); Assert.Equal(exist, _avatarState.inventory.TryGetTradableItem(item.TradableId, blockIndex, 1, out _)); - ITradableItem result = order.Cancel2(_avatarState, blockIndex); + var result = order.Cancel2(_avatarState, blockIndex); Assert.Equal(item.TradableId, result.TradableId); Assert.Equal(blockIndex, result.RequiredBlockIndex); - int expectedCount = exist ? itemCount + 1 : 1; + var expectedCount = exist ? itemCount + 1 : 1; Assert.False(_avatarState.inventory.TryGetTradableItem(item.TradableId, order.ExpiredBlockIndex, 1, out _)); Assert.True(_avatarState.inventory.TryGetTradableItem(item.TradableId, blockIndex, expectedCount, out _)); } @@ -462,10 +462,10 @@ public void Cancel(ItemSubType itemSubType, bool add, bool exist, long blockInde public void Cancel2(ItemSubType itemSubType, bool isLock, bool exist, long blockIndex, int itemCount, Type exc) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); item.RequiredBlockIndex = 1; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -493,11 +493,11 @@ public void Cancel2(ItemSubType itemSubType, bool isLock, bool exist, long block Assert.True(_avatarState.inventory.TryGetLockedItem(orderLock, out _)); Assert.Equal(exist, _avatarState.inventory.TryGetTradableItem(item.TradableId, blockIndex, 1, out _)); - ITradableItem result = order.Cancel(_avatarState, blockIndex); + var result = order.Cancel(_avatarState, blockIndex); Assert.Equal(item.TradableId, result.TradableId); Assert.Equal(blockIndex, result.RequiredBlockIndex); - int expectedCount = exist ? itemCount + 1 : 1; + var expectedCount = exist ? itemCount + 1 : 1; Assert.False(_avatarState.inventory.TryGetLockedItem(orderLock, out _)); Assert.True(_avatarState.inventory.TryGetTradableItems(item.TradableId, blockIndex, expectedCount, out _)); } @@ -531,11 +531,11 @@ int expected ) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); var agentAddress = equalAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = equalAvatarAddress ? _avatarState.address : default; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( agentAddress, avatarAddress, orderId, @@ -545,10 +545,10 @@ int expected 2, equalItemType ? ItemSubType.Hourglass : ItemSubType.ApStone ); - FungibleAssetValue price = equalPrice ? order.Price : _currency * 0; - Guid tradableId = equalTradableId ? item.TradableId : default; - int itemCount = equalCount ? order.ItemCount : order.ItemCount - 1; - long blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; + var price = equalPrice ? order.Price : _currency * 0; + var tradableId = equalTradableId ? item.TradableId : default; + var itemCount = equalCount ? order.ItemCount : order.ItemCount - 1; + var blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; item.RequiredBlockIndex = blockIndex; if (add) @@ -583,11 +583,11 @@ int expected ) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); var agentAddress = equalAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = equalAvatarAddress ? _avatarState.address : default; - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var order = OrderFactory.CreateFungibleOrder( agentAddress, avatarAddress, orderId, @@ -597,10 +597,10 @@ int expected 2, equalItemType ? ItemSubType.Hourglass : ItemSubType.ApStone ); - FungibleAssetValue price = equalPrice ? order.Price : _currency * 0; - Guid tradableId = equalTradableId ? item.TradableId : default; - int itemCount = equalCount ? order.ItemCount : order.ItemCount - 1; - long blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; + var price = equalPrice ? order.Price : _currency * 0; + var tradableId = equalTradableId ? item.TradableId : default; + var itemCount = equalCount ? order.ItemCount : order.ItemCount - 1; + var blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; item.RequiredBlockIndex = blockIndex; if (add) @@ -617,9 +617,9 @@ int expected public void Transfer(bool add, Type exc) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -649,8 +649,8 @@ public void Transfer(bool add, Type exc) { order.Transfer2(_avatarState, buyer, 100); Assert.False(_avatarState.inventory.TryGetTradableItem(order.TradableId, 100, 1, out _)); - Assert.True(buyer.inventory.TryGetTradableItem(order.TradableId, 100, 1, out Inventory.Item inventoryItem)); - ITradableFungibleItem result = (ITradableFungibleItem)inventoryItem.item; + Assert.True(buyer.inventory.TryGetTradableItem(order.TradableId, 100, 1, out var inventoryItem)); + var result = (ITradableFungibleItem)inventoryItem.item; Assert.Equal(100, result.RequiredBlockIndex); } else @@ -665,9 +665,9 @@ public void Transfer(bool add, Type exc) public void Transfer2(bool add, Type exc) { var row = _tableSheets.MaterialItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Hourglass); - TradableMaterial item = ItemFactory.CreateTradableMaterial(row); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - FungibleOrder order = OrderFactory.CreateFungibleOrder( + var item = ItemFactory.CreateTradableMaterial(row); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var order = OrderFactory.CreateFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -697,8 +697,8 @@ public void Transfer2(bool add, Type exc) { order.Transfer(_avatarState, buyer, 100); Assert.False(_avatarState.inventory.TryGetTradableItem(order.TradableId, 100, 1, out _)); - Assert.True(buyer.inventory.TryGetTradableItem(order.TradableId, 100, 1, out Inventory.Item inventoryItem)); - ITradableFungibleItem result = (ITradableFungibleItem)inventoryItem.item; + Assert.True(buyer.inventory.TryGetTradableItem(order.TradableId, 100, 1, out var inventoryItem)); + var result = (ITradableFungibleItem)inventoryItem.item; Assert.Equal(100, result.RequiredBlockIndex); } else @@ -708,310 +708,319 @@ public void Transfer2(bool add, Type exc) } #pragma warning disable SA1204 - public static IEnumerable ValidateMemberData() => new List + public static IEnumerable ValidateMemberData() { - new object[] + return new List { - 1, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - null, - }, - new object[] - { - 1, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - true, - typeof(ItemDoesNotExistException), - }, - new object[] - { - 1, - 1, - 0, - default, - default, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(InvalidAddressException), - }, - new object[] - { - 0, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(InvalidItemCountException), - }, - new object[] - { - 1, - 2, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(InvalidItemCountException), - }, - new object[] - { - 2, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(InvalidItemCountException), - }, - new object[] - { - -1, - 2, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(InvalidItemCountException), - }, - new object[] - { - 1, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(ItemDoesNotExistException), - }, - new object[] - { - 1, - 1, - 2, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Hourglass, - ItemSubType.Hourglass, - false, - typeof(ItemDoesNotExistException), - }, - new object[] - { - 1, - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Hourglass, - ItemSubType.Food, - false, - typeof(InvalidItemTypeException), - }, - }; - - public static IEnumerable SellMemberData() => new List + new object[] + { + 1, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + null, + }, + new object[] + { + 1, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + true, + typeof(ItemDoesNotExistException), + }, + new object[] + { + 1, + 1, + 0, + default, + default, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(InvalidAddressException), + }, + new object[] + { + 0, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(InvalidItemCountException), + }, + new object[] + { + 1, + 2, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(InvalidItemCountException), + }, + new object[] + { + 2, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(InvalidItemCountException), + }, + new object[] + { + -1, + 2, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(InvalidItemCountException), + }, + new object[] + { + 1, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(ItemDoesNotExistException), + }, + new object[] + { + 1, + 1, + 2, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Hourglass, + ItemSubType.Hourglass, + false, + typeof(ItemDoesNotExistException), + }, + new object[] + { + 1, + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Hourglass, + ItemSubType.Food, + false, + typeof(InvalidItemTypeException), + }, + }; + } + + public static IEnumerable SellMemberData() { - new object[] + return new List { - new OrderData + new object[] { - SellCount = 1, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), + SellCount = 1, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 3, - BlockIndex = 10, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), - (5, 2, false), + SellCount = 3, + BlockIndex = 10, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + (5, 2, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 3, - BlockIndex = 100, - InventoryData = new List<(long, int, bool)> + new OrderData { - (10, 20, false), + SellCount = 3, + BlockIndex = 100, + InventoryData = new List<(long, int, bool)> + { + (10, 20, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 1, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (3, 2, false), - (5, 3, false), + SellCount = 1, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (3, 2, false), + (5, 3, false), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 2, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), - (2, 100, false), + SellCount = 2, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + (2, 100, false), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - }; + }; + } - public static IEnumerable SellMemberData2() => new List + public static IEnumerable SellMemberData2() { - new object[] + return new List { - new OrderData + new object[] { - SellCount = 1, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), + SellCount = 1, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 3, - BlockIndex = 10, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), - (5, 2, false), + SellCount = 3, + BlockIndex = 10, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + (5, 2, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 3, - BlockIndex = 100, - InventoryData = new List<(long, int, bool)> + new OrderData { - (10, 20, false), + SellCount = 3, + BlockIndex = 100, + InventoryData = new List<(long, int, bool)> + { + (10, 20, false), + }, + Exception = null, }, - Exception = null, }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 1, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (3, 2, false), - (5, 3, false), + SellCount = 1, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (3, 2, false), + (5, 3, false), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 2, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), - (2, 100, false), + SellCount = 2, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + (2, 100, false), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 1, - BlockIndex = 1, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, true), + SellCount = 1, + BlockIndex = 1, + InventoryData = new List<(long, int, bool)> + { + (1, 1, true), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - new object[] - { - new OrderData + new object[] { - SellCount = 3, - BlockIndex = 10, - InventoryData = new List<(long, int, bool)> + new OrderData { - (1, 1, false), - (5, 2, true), + SellCount = 3, + BlockIndex = 10, + InventoryData = new List<(long, int, bool)> + { + (1, 1, false), + (5, 2, true), + }, + Exception = typeof(ItemDoesNotExistException), }, - Exception = typeof(ItemDoesNotExistException), }, - }, - }; + }; + } #pragma warning restore SA1204 public class OrderData diff --git a/.Lib9c.Tests/Model/Order/NonFungibleOrderTest.cs b/.Lib9c.Tests/Model/Order/NonFungibleOrderTest.cs index 44ac533134..e2faba8747 100644 --- a/.Lib9c.Tests/Model/Order/NonFungibleOrderTest.cs +++ b/.Lib9c.Tests/Model/Order/NonFungibleOrderTest.cs @@ -43,9 +43,9 @@ public NonFungibleOrderTest() [Fact] public void Serialize() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); - Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var order = OrderFactory.CreateNonFungibleOrder( Addresses.Admin, Addresses.Blacksmith, orderId, @@ -64,7 +64,7 @@ public void Serialize() Assert.Equal(itemId, order.TradableId); Assert.Equal(ItemSubType.Weapon, order.ItemSubType); - Dictionary serialized = (Dictionary)order.Serialize(); + var serialized = (Dictionary)order.Serialize(); Assert.Equal(order, new NonFungibleOrder(serialized)); } @@ -72,13 +72,13 @@ public void Serialize() [Fact] public void Serialize_DotNet_Api() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); - Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 - Currency currency = Currency.Legacy("NCG", 2, null); + var currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( Addresses.Admin, Addresses.Blacksmith, orderId, @@ -122,11 +122,11 @@ Type exc ) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = requiredBlockIndex; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( agentAddress, avatarAddress, orderId, @@ -158,10 +158,10 @@ Type exc public void Sell(ItemSubType itemSubType, bool add, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -184,7 +184,7 @@ public void Sell(ItemSubType itemSubType, bool add, Type exc) if (exc is null) { - ITradableItem result = order.Sell2(_avatarState); + var result = order.Sell2(_avatarState); Assert.Equal(order.ExpiredBlockIndex, result.RequiredBlockIndex); if (result is IEquippableItem equippableItem1) { @@ -209,10 +209,10 @@ public void Sell(ItemSubType itemSubType, bool add, Type exc) public void Sell2(ItemSubType itemSubType, bool add, bool isLock, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -244,14 +244,14 @@ public void Sell2(ItemSubType itemSubType, bool add, bool isLock, Type exc) if (exc is null) { - ITradableItem result = order.Sell(_avatarState); + var result = order.Sell(_avatarState); Assert.Equal(order.ExpiredBlockIndex, result.RequiredBlockIndex); if (result is IEquippableItem equippableItem1) { Assert.False(equippableItem1.Equipped); } - Assert.True(_avatarState.inventory.TryGetLockedItem(new OrderLock(orderId), out Inventory.Item inventoryItem)); + Assert.True(_avatarState.inventory.TryGetLockedItem(new OrderLock(orderId), out var inventoryItem)); Assert.Equal(result, (ITradableItem)inventoryItem.item); } else @@ -268,11 +268,11 @@ public void Sell2(ItemSubType itemSubType, bool add, bool isLock, Type exc) public void Digest(ItemSubType itemSubType, bool add, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -289,9 +289,9 @@ public void Digest(ItemSubType itemSubType, bool add, Type exc) if (exc is null) { - int cp = tradableItem is INonFungibleItem nonFungibleItem ? CPHelper.GetCP(nonFungibleItem, _tableSheets.CostumeStatSheet) : 0; + var cp = tradableItem is INonFungibleItem nonFungibleItem ? CPHelper.GetCP(nonFungibleItem, _tableSheets.CostumeStatSheet) : 0; Assert.True(cp > 0); - OrderDigest digest = order.Digest2(_avatarState, _tableSheets.CostumeStatSheet); + var digest = order.Digest2(_avatarState, _tableSheets.CostumeStatSheet); Assert.Equal(orderId, digest.OrderId); Assert.Equal(order.StartedBlockIndex, digest.StartedBlockIndex); @@ -325,14 +325,14 @@ Type exc ) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; var tradableId = useTradableId ? tradableItem.TradableId : default; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( agentAddress, avatarAddress, orderId, @@ -374,14 +374,14 @@ Type exc ) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; var tradableId = useTradableId ? tradableItem.TradableId : default; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( agentAddress, avatarAddress, orderId, @@ -417,11 +417,11 @@ Type exc public void Cancel(ItemSubType itemSubType, long blockIndex, bool add, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -447,7 +447,7 @@ out INonFungibleItem nonFungibleItem ); Assert.Equal(order.ExpiredBlockIndex, nonFungibleItem.RequiredBlockIndex); - ITradableItem result = order.Cancel2(_avatarState, blockIndex); + var result = order.Cancel2(_avatarState, blockIndex); Assert.Equal(blockIndex, result.RequiredBlockIndex); Assert.Equal(itemSubType, result.ItemSubType); @@ -473,11 +473,11 @@ out INonFungibleItem nextNonFungibleItem public void Cancel2(ItemSubType itemSubType, long blockIndex, bool isLock, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == itemSubType); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -498,12 +498,12 @@ public void Cancel2(ItemSubType itemSubType, long blockIndex, bool isLock, Type { var orderLock = new OrderLock(orderId); Assert.True( - _avatarState.inventory.TryGetLockedItem(orderLock, out Inventory.Item inventoryItem) + _avatarState.inventory.TryGetLockedItem(orderLock, out var inventoryItem) ); var nonFungibleItem = (INonFungibleItem)inventoryItem.item; Assert.Equal(order.ExpiredBlockIndex, nonFungibleItem.RequiredBlockIndex); - ITradableItem result = order.Cancel(_avatarState, blockIndex); + var result = order.Cancel(_avatarState, blockIndex); Assert.Equal(blockIndex, result.RequiredBlockIndex); Assert.Equal(itemSubType, result.ItemSubType); @@ -545,13 +545,13 @@ int expected ) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Weapon); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( agentAddress, avatarAddress, orderId, @@ -560,15 +560,15 @@ int expected 1, equalItemSubtype ? ItemSubType.Weapon : ItemSubType.Armor ); - FungibleAssetValue price = usePrice ? order.Price : _currency * 0; - Guid tradableId = useTradableId ? tradableItem.TradableId : default; + var price = usePrice ? order.Price : _currency * 0; + var tradableId = useTradableId ? tradableItem.TradableId : default; if (add) { _avatarState.inventory.AddNonFungibleItem(item); order.Sell2(_avatarState); } - long blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; + var blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; Assert.Equal(expected, order.ValidateTransfer2(_avatarState, tradableId, price, blockIndex)); } @@ -595,13 +595,13 @@ int expected ) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Weapon); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; var agentAddress = useAgentAddress ? _avatarState.agentAddress : default; var avatarAddress = useAvatarAddress ? _avatarState.address : default; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( agentAddress, avatarAddress, orderId, @@ -610,15 +610,15 @@ int expected 1, equalItemSubtype ? ItemSubType.Weapon : ItemSubType.Armor ); - FungibleAssetValue price = usePrice ? order.Price : _currency * 0; - Guid tradableId = useTradableId ? tradableItem.TradableId : default; + var price = usePrice ? order.Price : _currency * 0; + var tradableId = useTradableId ? tradableItem.TradableId : default; if (add) { _avatarState.inventory.AddNonFungibleItem(item); order.Sell(_avatarState); } - long blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; + var blockIndex = expire ? order.ExpiredBlockIndex + 1 : order.ExpiredBlockIndex; Assert.Equal(expected, order.ValidateTransfer(_avatarState, tradableId, price, blockIndex)); } @@ -629,11 +629,11 @@ int expected public void Transfer(bool add, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Weapon); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -677,11 +677,11 @@ public void Transfer(bool add, Type exc) public void Transfer2(bool add, Type exc) { var row = _tableSheets.ItemSheet.OrderedList.First(r => r.ItemSubType == ItemSubType.Weapon); - ItemBase item = ItemFactory.CreateItem(row, new TestRandom()); - Guid orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); - ITradableItem tradableItem = (ITradableItem)item; + var item = ItemFactory.CreateItem(row, new TestRandom()); + var orderId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var tradableItem = (ITradableItem)item; tradableItem.RequiredBlockIndex = 1; - NonFungibleOrder order = OrderFactory.CreateNonFungibleOrder( + var order = OrderFactory.CreateNonFungibleOrder( _avatarState.agentAddress, _avatarState.address, orderId, @@ -720,97 +720,100 @@ public void Transfer2(bool add, Type exc) } #pragma warning disable SA1204 - public static IEnumerable ValidateMemberData() => new List + public static IEnumerable ValidateMemberData() { - new object[] - { - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Weapon, - ItemSubType.Weapon, - null, - }, - new object[] - { - 1, - 0, - default, - default, - false, - ItemSubType.Weapon, - ItemSubType.Weapon, - typeof(InvalidAddressException), - }, - new object[] - { - 0, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Food, - ItemSubType.Food, - typeof(InvalidItemCountException), - }, - new object[] - { - -1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Food, - ItemSubType.Food, - typeof(InvalidItemCountException), - }, - new object[] - { - 2, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.FullCostume, - ItemSubType.FullCostume, - typeof(InvalidItemCountException), - }, - new object[] + return new List { - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - false, - ItemSubType.Weapon, - ItemSubType.Weapon, - typeof(ItemDoesNotExistException), - }, - new object[] - { - 1, - 0, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Weapon, - ItemSubType.Food, - typeof(InvalidItemTypeException), - }, - new object[] - { - 1, - 100, - Addresses.Admin, - Addresses.Blacksmith, - true, - ItemSubType.Weapon, - ItemSubType.Weapon, - typeof(RequiredBlockIndexException), - }, - }; + new object[] + { + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Weapon, + ItemSubType.Weapon, + null, + }, + new object[] + { + 1, + 0, + default, + default, + false, + ItemSubType.Weapon, + ItemSubType.Weapon, + typeof(InvalidAddressException), + }, + new object[] + { + 0, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Food, + ItemSubType.Food, + typeof(InvalidItemCountException), + }, + new object[] + { + -1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Food, + ItemSubType.Food, + typeof(InvalidItemCountException), + }, + new object[] + { + 2, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.FullCostume, + ItemSubType.FullCostume, + typeof(InvalidItemCountException), + }, + new object[] + { + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + false, + ItemSubType.Weapon, + ItemSubType.Weapon, + typeof(ItemDoesNotExistException), + }, + new object[] + { + 1, + 0, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Weapon, + ItemSubType.Food, + typeof(InvalidItemTypeException), + }, + new object[] + { + 1, + 100, + Addresses.Admin, + Addresses.Blacksmith, + true, + ItemSubType.Weapon, + ItemSubType.Weapon, + typeof(RequiredBlockIndexException), + }, + }; + } #pragma warning restore SA1204 } } diff --git a/.Lib9c.Tests/Model/Order/OrderDigestListStateTest.cs b/.Lib9c.Tests/Model/Order/OrderDigestListStateTest.cs index 70bfaa2f59..d1177f7455 100644 --- a/.Lib9c.Tests/Model/Order/OrderDigestListStateTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderDigestListStateTest.cs @@ -25,7 +25,7 @@ public OrderDigestListStateTest() orderId, tradableId, #pragma warning disable CS0618 - // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 + // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 Currency.Legacy("NCG", 2, null) * 1, #pragma warning restore CS0618 2, @@ -43,7 +43,7 @@ public void Add() orderDigestList.Add(_orderDigest); Assert.Single(orderDigestList.OrderDigestList); - OrderDigest orderDigest = orderDigestList.OrderDigestList.First(); + var orderDigest = orderDigestList.OrderDigestList.First(); Assert.Equal(_orderDigest, orderDigest); Assert.Throws(() => orderDigestList.Add(_orderDigest)); @@ -56,7 +56,7 @@ public void Serialize() var orderDigestList = new OrderDigestListState(address); orderDigestList.Add(_orderDigest); - Dictionary serialized = (Dictionary)orderDigestList.Serialize(); + var serialized = (Dictionary)orderDigestList.Serialize(); Assert.Equal(orderDigestList, new OrderDigestListState(serialized)); } diff --git a/.Lib9c.Tests/Model/Order/OrderDigestTest.cs b/.Lib9c.Tests/Model/Order/OrderDigestTest.cs index 6e0474d944..c324d1d6ae 100644 --- a/.Lib9c.Tests/Model/Order/OrderDigestTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderDigestTest.cs @@ -35,7 +35,7 @@ public void Serialize() 100, 1 ); - Dictionary serialized = (Dictionary)digest.Serialize(); + var serialized = (Dictionary)digest.Serialize(); Assert.Equal(digest, new OrderDigest(serialized)); } @@ -55,12 +55,12 @@ public void Serialize_DotNet_Api() 1 ); - BinaryFormatter formatter = new BinaryFormatter(); - using MemoryStream ms = new MemoryStream(); + var formatter = new BinaryFormatter(); + using var ms = new MemoryStream(); formatter.Serialize(ms, digest); ms.Seek(0, SeekOrigin.Begin); - OrderDigest deserialized = (OrderDigest)formatter.Deserialize(ms); + var deserialized = (OrderDigest)formatter.Deserialize(ms); Assert.Equal(digest, deserialized); } } diff --git a/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs b/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs index 5579685795..7f9a244dfb 100644 --- a/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs @@ -27,7 +27,7 @@ public OrderFactoryTest() public void Create(ItemType itemType, long blockIndex, Order.OrderType orderType) { ITradableItem tradableItem; - Guid itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); + var itemId = new Guid("15396359-04db-68d5-f24a-d89c18665900"); switch (itemType) { case ItemType.Consumable: @@ -61,9 +61,9 @@ public void Create(ItemType itemType, long blockIndex, Order.OrderType orderType // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); - Order order = OrderFactory.Create( + var order = OrderFactory.Create( Addresses.Admin, Addresses.Blacksmith, orderId, @@ -138,7 +138,7 @@ public void Deserialize(ItemType itemType, long blockIndex, Order.OrderType orde // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var currency = Currency.Legacy("NCG", 2, null); #pragma warning restore CS0618 - Order order = OrderFactory.Create( + var order = OrderFactory.Create( Addresses.Admin, Addresses.Blacksmith, default, @@ -149,8 +149,8 @@ public void Deserialize(ItemType itemType, long blockIndex, Order.OrderType orde 1 ); - Dictionary serialized = (Dictionary)order.Serialize(); - Order deserialized = OrderFactory.Deserialize(serialized); + var serialized = (Dictionary)order.Serialize(); + var deserialized = OrderFactory.Deserialize(serialized); Assert.Equal(order, deserialized); Assert.Equal(orderType, deserialized.Type); } diff --git a/.Lib9c.Tests/Model/Order/OrderReceiptTest.cs b/.Lib9c.Tests/Model/Order/OrderReceiptTest.cs index c41c2210bf..47cdd9eda5 100644 --- a/.Lib9c.Tests/Model/Order/OrderReceiptTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderReceiptTest.cs @@ -13,9 +13,9 @@ public class OrderReceiptTest [Fact] public void Serialize() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); var receipt = new OrderReceipt(orderId, Addresses.Admin, Addresses.Blacksmith, 10); - Dictionary serialized = (Dictionary)receipt.Serialize(); + var serialized = (Dictionary)receipt.Serialize(); var deserialized = new OrderReceipt(serialized); Assert.Equal(orderId, deserialized.OrderId); @@ -27,7 +27,7 @@ public void Serialize() [Fact] public void Serialize_DotNet_Api() { - Guid orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); + var orderId = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8"); var receipt = new OrderReceipt(orderId, Addresses.Admin, Addresses.Blacksmith, 10); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); diff --git a/.Lib9c.Tests/Model/PlayerTest.cs b/.Lib9c.Tests/Model/PlayerTest.cs index b4455650b1..b8daf38b22 100644 --- a/.Lib9c.Tests/Model/PlayerTest.cs +++ b/.Lib9c.Tests/Model/PlayerTest.cs @@ -357,7 +357,7 @@ public void GetExpV2(int level, int count = 1) _tableSheets.EquipmentItemSetEffectSheet); Assert.Empty(player.eventMap); - for (int i = 0; i < count; ++i) + for (var i = 0; i < count; ++i) { var requiredExp = _tableSheets.CharacterLevelSheet[level].ExpNeed; player.GetExp3(requiredExp); @@ -404,7 +404,7 @@ public void GetExpV3(int nextLevel, bool log) Assert.Empty(player.eventMap); Assert.Empty(simulator.Log); long requiredExp = 0; - for (int i = player.Level; i < nextLevel; ++i) + for (var i = player.Level; i < nextLevel; ++i) { requiredExp += _tableSheets.CharacterLevelSheet[i + 1].ExpNeed; } @@ -503,7 +503,7 @@ public void GetStun() var log = simulator.Log; var logCount = log.Count; var logList = log.ToList(); - for (int i = 0; i < logCount; i++) + for (var i = 0; i < logCount; i++) { var currLog = logList[i]; if (currLog is Tick) @@ -555,7 +555,7 @@ public void GiveStun() _tableSheets.BuffLinkSheet ); var skill = SkillFactory.Get(_tableSheets.SkillSheet[700004], 0, 100, 0, StatType.NONE); - skill.CustomField = new SkillCustomField { BuffDuration = 2 }; + skill.CustomField = new SkillCustomField { BuffDuration = 2, }; var player = simulator.Player; var enemy = new Enemy(player, _tableSheets.CharacterSheet.Values.First(), 1); player.Targets.Add(enemy); @@ -576,7 +576,7 @@ public void GiveStun() var log = simulator.Log; var logCount = log.Count; var logList = log.ToList(); - for (int i = 0; i < logCount; i++) + for (var i = 0; i < logCount; i++) { var currLog = logList[i]; if (currLog is Tick) @@ -657,7 +657,7 @@ public void Vampiric(int duration, int percent) // force add buff 'Vampiric' // 705000 is ActionBuff id of Vampiric var vampiric = (Vampiric)BuffFactory.GetCustomActionBuff( - new SkillCustomField { BuffDuration = duration, BuffValue = percent }, actionBuffSheet[705000]); + new SkillCustomField { BuffDuration = duration, BuffValue = percent, }, actionBuffSheet[705000]); player.AddBuff(vampiric); var row = actionBuffSheet.Values.First(); var bleed = BuffFactory.GetActionBuff(enemy.Stats, row); @@ -668,7 +668,7 @@ public void Vampiric(int duration, int percent) var log = simulator.Log; var logCount = log.Count; var logList = log.ToList(); - for (int i = 0; i < logCount; i++) + for (var i = 0; i < logCount; i++) { var currLog = logList[i]; if (currLog is Nekoyume.Model.BattleStatus.NormalAttack) @@ -791,7 +791,7 @@ public void StatsLayerTest() } } - StatBuff stageAtkBuff = statBuffs.Single(s => s.GetModifier().StatType == StatType.ATK); + var stageAtkBuff = statBuffs.Single(s => s.GetModifier().StatType == StatType.ATK); var stageModifier = stageAtkBuff.GetModifier(); var stageBuffAtk = (long)stageModifier.GetModifiedValue(collectionLayerAtk); // StageBuffStats 1101(50%) @@ -979,7 +979,7 @@ public void IceShield() // increase def by ice shield buff Assert.True(character.DEF > def); enemy.InitAI(); - for (int i = 0; i < 4; i++) + for (var i = 0; i < 4; i++) { enemy.Tick(); e = log.Last(); diff --git a/.Lib9c.Tests/Model/QuestListTest.cs b/.Lib9c.Tests/Model/QuestListTest.cs index d25604e389..37eb352596 100644 --- a/.Lib9c.Tests/Model/QuestListTest.cs +++ b/.Lib9c.Tests/Model/QuestListTest.cs @@ -20,9 +20,12 @@ public QuestListTest() } [Fact] - public void SerializeExceptions() => ExceptionTest.AssertException( - new UpdateListVersionException("test"), - new UpdateListQuestsCountException("test")); + public void SerializeExceptions() + { + ExceptionTest.AssertException( + new UpdateListVersionException("test"), + new UpdateListQuestsCountException("test")); + } [Fact] public void GetEnumerator() diff --git a/.Lib9c.Tests/Model/RankingSimulatorV1Test.cs b/.Lib9c.Tests/Model/RankingSimulatorV1Test.cs index ef06822fa9..92ba4e840c 100644 --- a/.Lib9c.Tests/Model/RankingSimulatorV1Test.cs +++ b/.Lib9c.Tests/Model/RankingSimulatorV1Test.cs @@ -198,7 +198,7 @@ public void CheckToReceiveAllRewardItems(int level, int simulationCount) new ArenaInfo(avatarState, _tableSheets.CharacterSheet, false)); var rewardIds = new HashSet(); - for (int i = 0; i < simulationCount; ++i) + for (var i = 0; i < simulationCount; ++i) { simulator.SimulateV2(); foreach (var itemBase in simulator.Reward) diff --git a/.Lib9c.Tests/Model/Rune/AllRuneStateTest.cs b/.Lib9c.Tests/Model/Rune/AllRuneStateTest.cs index 0246439cf6..74919c1431 100644 --- a/.Lib9c.Tests/Model/Rune/AllRuneStateTest.cs +++ b/.Lib9c.Tests/Model/Rune/AllRuneStateTest.cs @@ -8,8 +8,8 @@ namespace Lib9c.Tests.Model.Rune public class AllRuneStateTest { [Theory] - [InlineData(new[] { 10001 })] - [InlineData(new[] { 10001, 10002 })] + [InlineData(new[] { 10001, })] + [InlineData(new[] { 10001, 10002, })] public void Serialize(int[] runeIds) { var levelOffset = new TestRandom().Next(0, 100); diff --git a/.Lib9c.Tests/Model/SimulatorTest.cs b/.Lib9c.Tests/Model/SimulatorTest.cs index 70b73584a0..4b0498de3b 100644 --- a/.Lib9c.Tests/Model/SimulatorTest.cs +++ b/.Lib9c.Tests/Model/SimulatorTest.cs @@ -38,7 +38,7 @@ public void SetRewardAll() var reward = Simulator.SetReward(itemSelector, _random.Next(2, 2), _random, _materialItemSheet); Assert.Equal(2, reward.Count); Assert.NotEmpty(reward); - Assert.Equal(new[] { 303000, 306043 }, reward.Select(i => i.Id).ToArray()); + Assert.Equal(new[] { 303000, 306043, }, reward.Select(i => i.Id).ToArray()); } [Fact] diff --git a/.Lib9c.Tests/Model/Skill/Adventure/CombatTest.cs b/.Lib9c.Tests/Model/Skill/Adventure/CombatTest.cs index 2f63cf7f1b..25fc9d57bd 100644 --- a/.Lib9c.Tests/Model/Skill/Adventure/CombatTest.cs +++ b/.Lib9c.Tests/Model/Skill/Adventure/CombatTest.cs @@ -34,7 +34,7 @@ public CombatTest() default); _player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); @@ -138,9 +138,9 @@ public void Bleed() } [Theory] - [InlineData(700009, 50, 3, new[] { 600001 }, new[] { 600001, 707000 })] - [InlineData(700009, 100, 0, new[] { 600001 }, new[] { 707000 })] - [InlineData(700010, 100, 0, new[] { 600001, 704000 }, new[] { 707000 })] + [InlineData(700009, 50, 3, new[] { 600001, }, new[] { 600001, 707000, })] + [InlineData(700009, 100, 0, new[] { 600001, }, new[] { 707000, })] + [InlineData(700010, 100, 0, new[] { 600001, 704000, }, new[] { 707000, })] public void DispelOnUse(int dispelId, int chance, int seed, int[] debuffIdList, int[] expectedResult) { var simulator = new TestSimulator( @@ -163,13 +163,13 @@ public void DispelOnUse(int dispelId, int chance, int seed, int[] debuffIdList, // Use Dispel var actionBuffRow = new ActionBuffSheet.Row(); - actionBuffRow.Set(new[] { "707000", "707000", chance.ToString(), "0", "Self", "Dispel", "Normal", "0" }); + actionBuffRow.Set(new[] { "707000", "707000", chance.ToString(), "0", "Self", "Dispel", "Normal", "0", }); var dispelRow = _tableSheets.SkillSheet.Values.First(bf => bf.Id == dispelId); var dispel = new BuffSkill(dispelRow, 0, chance, 0, StatType.NONE); var battleStatus = dispel.Use( _player, 0, - new List() { new Dispel(actionBuffRow) }, + new List() { new Dispel(actionBuffRow), }, false); Assert.NotNull(battleStatus); // Remove Bleed, add Dispel diff --git a/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs b/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs index dba821db23..909afb9abb 100644 --- a/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs +++ b/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs @@ -73,7 +73,7 @@ public void Use(int enemyHp, int ratioBp, bool expectedEnemyDead, bool copyChara _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet, copyCharacter, - shatterStrikeMaxDamage: gameConfigState.ShatterStrikeMaxDamage + gameConfigState.ShatterStrikeMaxDamage ); var player = new Player(avatarState, simulator); var enemyRow = _tableSheets.CharacterSheet.OrderedList @@ -153,7 +153,7 @@ public void Use_MaxDamage(bool copyCharacter) _tableSheets.DeBuffLimitSheet, _tableSheets.BuffLinkSheet, copyCharacter, - shatterStrikeMaxDamage: gameConfigState.ShatterStrikeMaxDamage + gameConfigState.ShatterStrikeMaxDamage ); var player = new Player(avatarState, simulator); var enemyRow = _tableSheets.CharacterSheet.OrderedList diff --git a/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs b/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs index 20d37cbdd1..3692faebf0 100644 --- a/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs +++ b/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs @@ -44,8 +44,8 @@ public ArenaCombatTest() } [Theory] - [InlineData(700009, new[] { 600001 })] - [InlineData(700009, new[] { 600001, 704000 })] + [InlineData(700009, new[] { 600001, })] + [InlineData(700009, new[] { 600001, 704000, })] public void DispelOnUse(int dispelId, int[] debuffIdList) { var arenaSheets = _tableSheets.GetArenaSimulatorSheets(); diff --git a/.Lib9c.Tests/Model/Skill/Arena/ArenaShatterStrikeTest.cs b/.Lib9c.Tests/Model/Skill/Arena/ArenaShatterStrikeTest.cs index aef5f46bff..db7133f2ff 100644 --- a/.Lib9c.Tests/Model/Skill/Arena/ArenaShatterStrikeTest.cs +++ b/.Lib9c.Tests/Model/Skill/Arena/ArenaShatterStrikeTest.cs @@ -56,8 +56,8 @@ public void Use(int hpModifier, int ratioBp, bool expectedEnemyDead) new GameConfigState((Text)_tableSheets.GameConfigSheet.Serialize()); var simulator = new ArenaSimulator( new TestRandom(), - hpModifier: hpModifier, - shatterStrikeMaxDamage: gameConfigState.ShatterStrikeMaxDamage + hpModifier, + gameConfigState.ShatterStrikeMaxDamage ); var myDigest = new ArenaPlayerDigest(_avatar1, _arenaAvatar1); var enemyDigest = new ArenaPlayerDigest(_avatar2, _arenaAvatar2); diff --git a/.Lib9c.Tests/Model/Skill/BuffFactoryTest.cs b/.Lib9c.Tests/Model/Skill/BuffFactoryTest.cs index d6fdf997c5..6b672474d3 100644 --- a/.Lib9c.Tests/Model/Skill/BuffFactoryTest.cs +++ b/.Lib9c.Tests/Model/Skill/BuffFactoryTest.cs @@ -72,7 +72,7 @@ public void GetBuffs_Arena(bool setExtraValueBuffBeforeGetBuffs) public void GetBuffs() { var player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); @@ -96,7 +96,7 @@ public void GetBuffs() public void Thorns() { var player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); @@ -120,7 +120,7 @@ public void Thorns() var equipmentRow = _tableSheets.EquipmentItemSheet.Values.Where(r => r.Stat.StatType == StatType.HP).OrderByDescending(r => r.Stat.TotalValue).First(); var equipment = (Equipment)ItemFactory.CreateItem(equipmentRow, new TestRandom()); - player.Stats.SetEquipments(new[] { equipment }, _tableSheets.EquipmentItemSetEffectSheet); + player.Stats.SetEquipments(new[] { equipment, }, _tableSheets.EquipmentItemSetEffectSheet); Assert.True(player.Stats.HP > hp); buffs = BuffFactory.GetBuffs( player.Stats, @@ -157,15 +157,15 @@ public void Thorns() public void IsDebuff(int buffId, bool hasCustom) { var player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); var skillId = _tableSheets.SkillBuffSheet.Values.First(r => r.BuffIds.Contains(buffId)).SkillId; var skillRow = _tableSheets.SkillSheet[skillId]; - int power = hasCustom ? 0 : 100; - int statPower = hasCustom ? 250 : 0; - StatType referencedStat = hasCustom ? StatType.HP : StatType.NONE; + var power = hasCustom ? 0 : 100; + var statPower = hasCustom ? 250 : 0; + var referencedStat = hasCustom ? StatType.HP : StatType.NONE; var skill = SkillFactory.Get(skillRow, power, 100, statPower, referencedStat); var buffs = BuffFactory.GetBuffs( player.Stats, @@ -188,15 +188,15 @@ public void IsDebuff(int buffId, bool hasCustom) public void IsBuff(int buffId, bool hasCustom) { var player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); var skillId = _tableSheets.SkillBuffSheet.Values.First(r => r.BuffIds.Contains(buffId)).SkillId; var skillRow = _tableSheets.SkillSheet[skillId]; - int power = hasCustom ? 0 : 100; - int statPower = hasCustom ? 250 : 0; - StatType referencedStat = hasCustom ? StatType.ATK : StatType.NONE; + var power = hasCustom ? 0 : 100; + var statPower = hasCustom ? 250 : 0; + var referencedStat = hasCustom ? StatType.ATK : StatType.NONE; var skill = SkillFactory.Get(skillRow, power, 100, statPower, referencedStat); var buffs = BuffFactory.GetBuffs( player.Stats, @@ -217,7 +217,7 @@ public void IsBuff(int buffId, bool hasCustom) public void IceShield() { var player = new Player( - level: 1, + 1, _tableSheets.CharacterSheet, _tableSheets.CharacterLevelSheet, _tableSheets.EquipmentItemSetEffectSheet); @@ -241,7 +241,7 @@ public void IceShield() var frostBite = iceShield.FrostBite(_tableSheets.StatBuffSheet, _tableSheets.BuffLinkSheet); Assert.Null(frostBite.CustomField); var power = frostBite.RowData.Value; - for (int i = 0; i < frostBite.RowData.MaxStack; i++) + for (var i = 0; i < frostBite.RowData.MaxStack; i++) { frostBite.SetStack(i); var modifier = frostBite.GetModifier(); diff --git a/.Lib9c.Tests/Model/Skill/Raid/NormalAttackTest.cs b/.Lib9c.Tests/Model/Skill/Raid/NormalAttackTest.cs index b97a5d669f..99b0309e29 100644 --- a/.Lib9c.Tests/Model/Skill/Raid/NormalAttackTest.cs +++ b/.Lib9c.Tests/Model/Skill/Raid/NormalAttackTest.cs @@ -52,7 +52,7 @@ public void FocusSkill() var buffRow = new ActionBuffSheet.Row(); buffRow.Set( new List - { "706000", "706000", "100", "9999", "Self", "Focus", "Normal", "0" } + { "706000", "706000", "100", "9999", "Self", "Focus", "Normal", "0", } ); player.AddBuff(new Focus(buffRow)); diff --git a/.Lib9c.Tests/Model/State/AuthorizedMinersStateTest.cs b/.Lib9c.Tests/Model/State/AuthorizedMinersStateTest.cs index b1682e2a12..74dd8d6d03 100644 --- a/.Lib9c.Tests/Model/State/AuthorizedMinersStateTest.cs +++ b/.Lib9c.Tests/Model/State/AuthorizedMinersStateTest.cs @@ -12,9 +12,9 @@ public void Serialize() { var miners = GetNewMiners(); var state = new AuthorizedMinersState( - miners: miners, - interval: 50, - validUntil: 1000 + miners, + 50, + 1000 ); var serialized = (Dictionary)state.Serialize(); diff --git a/.Lib9c.Tests/Model/State/AvatarStateTest.cs b/.Lib9c.Tests/Model/State/AvatarStateTest.cs index 7b8824dcff..0b57bb7ce7 100644 --- a/.Lib9c.Tests/Model/State/AvatarStateTest.cs +++ b/.Lib9c.Tests/Model/State/AvatarStateTest.cs @@ -32,8 +32,8 @@ public AvatarStateTest() [Fact] public void Serialize() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); var serialized = avatarState.SerializeList(); @@ -53,14 +53,17 @@ public void Serialize() [InlineData(4)] public async Task ConstructDeterministic(int waitMilliseconds) { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; - AvatarState avatarStateA = GetNewAvatarState(avatarAddress, agentAddress); + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; + var avatarStateA = GetNewAvatarState(avatarAddress, agentAddress); await Task.Delay(waitMilliseconds); - AvatarState avatarStateB = GetNewAvatarState(avatarAddress, agentAddress); + var avatarStateB = GetNewAvatarState(avatarAddress, agentAddress); + + HashDigest Hash(AvatarState avatarState) + { + return HashDigest.DeriveFrom(new Codec().Encode(avatarState.SerializeList())); + } - HashDigest Hash(AvatarState avatarState) => - HashDigest.DeriveFrom(new Codec().Encode(avatarState.SerializeList())); Assert.Equal(Hash(avatarStateA), Hash(avatarStateB)); } @@ -68,8 +71,8 @@ HashDigest Hash(AvatarState avatarState) => public void UpdateFromQuestRewardDeterministic() { var rankingState = new RankingState1(); - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = AvatarState.Create( avatarAddress, agentAddress, @@ -114,8 +117,8 @@ public void UpdateFromQuestRewardDeterministic() [InlineData(5, GameConfig.RequireCharacterLevel.CharacterConsumableSlot5)] public void ValidateConsumable(int count, int level) { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = level; @@ -135,8 +138,8 @@ public void ValidateConsumable(int count, int level) [Fact] public void ValidateConsumableThrowRequiredBlockIndexException() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); var consumableIds = new List(); @@ -151,8 +154,8 @@ public void ValidateConsumableThrowRequiredBlockIndexException() [Fact] public void ValidateConsumableThrowConsumableSlotOutOfRangeException() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = GameConfig.RequireCharacterLevel.CharacterConsumableSlot5; @@ -177,8 +180,8 @@ public void ValidateConsumableThrowConsumableSlotOutOfRangeException() [InlineData(5, GameConfig.RequireCharacterLevel.CharacterConsumableSlot5)] public void ValidateConsumableSlotThrowConsumableSlotUnlockException(int count, int level) { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = level - 1; @@ -198,8 +201,8 @@ public void ValidateConsumableSlotThrowConsumableSlotUnlockException(int count, [Fact] public void ValidateCostume() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = 100; @@ -233,8 +236,8 @@ public void ValidateCostume() [InlineData(ItemSubType.Title)] public void ValidateCostumeThrowDuplicateCostumeException(ItemSubType type) { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = 100; @@ -258,8 +261,8 @@ public void ValidateCostumeThrowDuplicateCostumeException(ItemSubType type) [Fact] public void ValidateCostumeThrowInvalidItemTypeException() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = 100; @@ -268,7 +271,7 @@ public void ValidateCostumeThrowInvalidItemTypeException() var serialized = (Dictionary)costume.Serialize(); serialized = serialized.SetItem("item_sub_type", ItemSubType.Armor.Serialize()); var costume2 = new Costume(serialized); - var costumeIds = new HashSet { costume2.Id }; + var costumeIds = new HashSet { costume2.Id, }; avatarState.inventory.AddItem(costume2); Assert.Throws(() => avatarState.ValidateCostume(costumeIds)); @@ -283,14 +286,14 @@ public void ValidateCostumeThrowInvalidItemTypeException() [InlineData(ItemSubType.Title, GameConfig.RequireCharacterLevel.CharacterTitleSlot)] public void ValidateCostumeThrowCostumeSlotUnlockException(ItemSubType type, int level) { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); avatarState.level = level - 1; var row = _tableSheets.CostumeItemSheet.Values.First(r => r.ItemSubType == type); var costume = ItemFactory.CreateCostume(row, default); - var costumeIds = new HashSet { costume.Id }; + var costumeIds = new HashSet { costume.Id, }; avatarState.inventory.AddItem(costume); Assert.Throws(() => avatarState.ValidateCostume(costumeIds)); @@ -299,8 +302,8 @@ public void ValidateCostumeThrowCostumeSlotUnlockException(ItemSubType type, int [Fact] public void UpdateV2() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); var result = new CombinationConsumable5.ResultModel() { @@ -324,8 +327,8 @@ public void UpdateV2() [Fact] public void UpdateV4() { - Address avatarAddress = new PrivateKey().Address; - Address agentAddress = new PrivateKey().Address; + var avatarAddress = new PrivateKey().Address; + var agentAddress = new PrivateKey().Address; var avatarState = GetNewAvatarState(avatarAddress, agentAddress); var result = new CombinationConsumable5.ResultModel() { @@ -451,9 +454,9 @@ private void ValidateEquipmentsV2(ItemSubType type, int count, int maxCount, lon foreach (var row in weaponRows) { var equipment = ItemFactory.CreateItemUsable( - _tableSheets.EquipmentItemSheet[row.Id], - Guid.NewGuid(), - requiredBlockIndex) + _tableSheets.EquipmentItemSheet[row.Id], + Guid.NewGuid(), + requiredBlockIndex) as Equipment; equipments.Add(equipment.ItemId); diff --git a/.Lib9c.Tests/Model/State/CreditsStateTest.cs b/.Lib9c.Tests/Model/State/CreditsStateTest.cs index ca03844163..be77d03327 100644 --- a/.Lib9c.Tests/Model/State/CreditsStateTest.cs +++ b/.Lib9c.Tests/Model/State/CreditsStateTest.cs @@ -18,7 +18,7 @@ public void Serialize() } ); - Dictionary serialized = (Dictionary)credits.Serialize(); + var serialized = (Dictionary)credits.Serialize(); var deserialized = new CreditsState(serialized); Assert.Equal(credits.Names, deserialized.Names); diff --git a/.Lib9c.Tests/Model/State/CrystalRandomSkillStateTest.cs b/.Lib9c.Tests/Model/State/CrystalRandomSkillStateTest.cs index f3c279745d..d9f7f63a9e 100644 --- a/.Lib9c.Tests/Model/State/CrystalRandomSkillStateTest.cs +++ b/.Lib9c.Tests/Model/State/CrystalRandomSkillStateTest.cs @@ -22,7 +22,7 @@ public void Serialize() var address = new PrivateKey().Address; var state = new CrystalRandomSkillState(address, 1); state.Update(100_000_000, _tableSheets.CrystalStageBuffGachaSheet); - state.Update(new List { 1, 2, 3 }); + state.Update(new List { 1, 2, 3, }); var serialized = state.Serialize(); var deserialized = new CrystalRandomSkillState(address, (List)serialized); diff --git a/.Lib9c.Tests/Model/State/GameConfigStateTest.cs b/.Lib9c.Tests/Model/State/GameConfigStateTest.cs index ca99c697cf..0c853ef53d 100644 --- a/.Lib9c.Tests/Model/State/GameConfigStateTest.cs +++ b/.Lib9c.Tests/Model/State/GameConfigStateTest.cs @@ -74,7 +74,7 @@ public void Update() var state = GetDefaultGameConfigState(); Assert.Equal(3, state.HourglassPerBlock); var row = new GameConfigSheet.Row(); - row.Set(new[] { "hourglass_per_block", "5" }); + row.Set(new[] { "hourglass_per_block", "5", }); state.Update(row); Assert.Equal(5, state.HourglassPerBlock); } diff --git a/.Lib9c.Tests/Model/State/GoldCurrencyStateTest.cs b/.Lib9c.Tests/Model/State/GoldCurrencyStateTest.cs index db03bbb89f..425dac8521 100644 --- a/.Lib9c.Tests/Model/State/GoldCurrencyStateTest.cs +++ b/.Lib9c.Tests/Model/State/GoldCurrencyStateTest.cs @@ -19,7 +19,7 @@ public void Serialize() #pragma warning restore CS0618 var state = new GoldCurrencyState(currency); var serialized = (Dictionary)state.Serialize(); - GoldCurrencyState deserialized = new GoldCurrencyState(serialized); + var deserialized = new GoldCurrencyState(serialized); Assert.Equal(currency.Hash, deserialized.Currency.Hash); Assert.Equal(1000000000, deserialized.InitialSupply); @@ -47,13 +47,13 @@ public void SerializeWithDotnetAPI() [Fact] public void SerializeWithInitialSupply() { - #pragma warning disable CS0618 +#pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var currency = Currency.Legacy("NCG", 2, default(Address)); #pragma warning restore CS0618 var state = new GoldCurrencyState(currency, 0L); var serialized = (Dictionary)state.Serialize(); - GoldCurrencyState deserialized = new GoldCurrencyState(serialized); + var deserialized = new GoldCurrencyState(serialized); Assert.Equal(currency.Hash, deserialized.Currency.Hash); Assert.Equal(0, deserialized.InitialSupply); diff --git a/.Lib9c.Tests/Model/State/LazyStateTest.cs b/.Lib9c.Tests/Model/State/LazyStateTest.cs index 9b07246e9c..c3beb79ad2 100644 --- a/.Lib9c.Tests/Model/State/LazyStateTest.cs +++ b/.Lib9c.Tests/Model/State/LazyStateTest.cs @@ -120,9 +120,12 @@ public SampleState(IValue iValue) public string Bar { get; set; } - public override IValue Serialize() => ((Dictionary)SerializeBase()) - .Add("foo", Foo) - .Add("bar", Bar); + public override IValue Serialize() + { + return ((Dictionary)SerializeBase()) + .Add("foo", Foo) + .Add("bar", Bar); + } } } } diff --git a/.Lib9c.Tests/Model/State/MonsterCollectionState0Test.cs b/.Lib9c.Tests/Model/State/MonsterCollectionState0Test.cs index 0d64c21103..2f1880aa81 100644 --- a/.Lib9c.Tests/Model/State/MonsterCollectionState0Test.cs +++ b/.Lib9c.Tests/Model/State/MonsterCollectionState0Test.cs @@ -26,15 +26,15 @@ public MonsterCollectionState0Test() [Fact] public void Serialize() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); - Dictionary serialized = (Dictionary)monsterCollectionState.Serialize(); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var serialized = (Dictionary)monsterCollectionState.Serialize(); Assert.Equal(serialized, new MonsterCollectionState0(serialized).Serialize()); } [Fact] public void Serialize_DotNet_API() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); formatter.Serialize(ms, monsterCollectionState); @@ -48,15 +48,15 @@ public void Serialize_DotNet_API() [Fact] public void SerializeV2() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000); - Dictionary serialized = (Dictionary)monsterCollectionState.SerializeV2(); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000); + var serialized = (Dictionary)monsterCollectionState.SerializeV2(); Assert.Equal(serialized, new MonsterCollectionState0(serialized).SerializeV2()); } [Fact] public void SerializeV2_DotNet_API() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); formatter.Serialize(ms, monsterCollectionState); @@ -74,15 +74,15 @@ public void SerializeV2_DotNet_API() [InlineData(3)] public void Update(long rewardLevel) { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); Assert.Equal(1, monsterCollectionState.Level); Assert.Equal(10000, monsterCollectionState.StartedBlockIndex); Assert.Equal(MonsterCollectionState0.RewardInterval * 4 + 10000, monsterCollectionState.ExpiredBlockIndex); monsterCollectionState.Update(2, rewardLevel, _tableSheets.MonsterCollectionRewardSheet); Assert.Equal(2, monsterCollectionState.Level); - List rewards = _tableSheets.MonsterCollectionRewardSheet[2].Rewards; - for (long i = rewardLevel; i < 4; i++) + var rewards = _tableSheets.MonsterCollectionRewardSheet[2].Rewards; + for (var i = rewardLevel; i < 4; i++) { Assert.Equal(rewards, monsterCollectionState.RewardLevelMap[i + 1]); } @@ -91,12 +91,12 @@ public void Update(long rewardLevel) [Fact] public void UpdateRewardMap() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); Assert.Empty(monsterCollectionState.RewardMap); Address avatarAddress = default; - List rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; - MonsterCollectionResult result = new MonsterCollectionResult(Guid.NewGuid(), avatarAddress, rewards); + var rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; + var result = new MonsterCollectionResult(Guid.NewGuid(), avatarAddress, rewards); monsterCollectionState.UpdateRewardMap(1, result, 14000); Assert.Single(monsterCollectionState.RewardMap); Assert.Equal(result, monsterCollectionState.RewardMap[1]); @@ -109,19 +109,19 @@ public void UpdateRewardMap() [InlineData(5)] public void UpdateRewardMap_Throw_ArgumentOutOfRangeException(long rewardLevel) { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); - List rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; - MonsterCollectionResult result = new MonsterCollectionResult(Guid.NewGuid(), _address, rewards); + var rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; + var result = new MonsterCollectionResult(Guid.NewGuid(), _address, rewards); Assert.Throws(() => monsterCollectionState.UpdateRewardMap(rewardLevel, result, 0)); } [Fact] public void UpdateRewardMap_Throw_AlreadyReceivedException() { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); - List rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; - MonsterCollectionResult result = new MonsterCollectionResult(Guid.NewGuid(), default, rewards); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 10000, _tableSheets.MonsterCollectionRewardSheet); + var rewards = _tableSheets.MonsterCollectionRewardSheet[1].Rewards; + var result = new MonsterCollectionResult(Guid.NewGuid(), default, rewards); monsterCollectionState.UpdateRewardMap(1, result, 14000); Assert.Throws(() => monsterCollectionState.UpdateRewardMap(1, result, 0)); } @@ -136,8 +136,8 @@ public void UpdateRewardMap_Throw_AlreadyReceivedException() [InlineData(5, 4)] public void GetRewardLevel(int interval, long expected) { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 0, _tableSheets.MonsterCollectionRewardSheet); - long blockIndex = MonsterCollectionState0.RewardInterval * interval; + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 0, _tableSheets.MonsterCollectionRewardSheet); + var blockIndex = MonsterCollectionState0.RewardInterval * interval; Assert.Equal(expected, monsterCollectionState.GetRewardLevel(blockIndex)); } @@ -148,8 +148,8 @@ public void GetRewardLevel(int interval, long expected) [InlineData(MonsterCollectionState0.RewardInterval, 0, MonsterCollectionState0.RewardInterval * 1.5, false)] public void CanReceive(long startedBlockIndex, long receivedBlockIndex, long blockIndex, bool expected) { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, startedBlockIndex, _tableSheets.MonsterCollectionRewardSheet); - Dictionary serialized = (Dictionary)monsterCollectionState.Serialize(); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, startedBlockIndex, _tableSheets.MonsterCollectionRewardSheet); + var serialized = (Dictionary)monsterCollectionState.Serialize(); serialized = serialized.SetItem(ReceivedBlockIndexKey, receivedBlockIndex.Serialize()); monsterCollectionState = new MonsterCollectionState0(serialized); Assert.Equal(receivedBlockIndex, monsterCollectionState.ReceivedBlockIndex); @@ -163,7 +163,7 @@ public void CanReceive(long startedBlockIndex, long receivedBlockIndex, long blo [InlineData(MonsterCollectionState0.LockUpInterval + 1, false)] public void IsLock(long blockIndex, bool expected) { - MonsterCollectionState0 monsterCollectionState = new MonsterCollectionState0(_address, 1, 0); + var monsterCollectionState = new MonsterCollectionState0(_address, 1, 0); Assert.Equal(expected, monsterCollectionState.IsLock(blockIndex)); } } diff --git a/.Lib9c.Tests/Model/State/PendingActivationStateTest.cs b/.Lib9c.Tests/Model/State/PendingActivationStateTest.cs index ec0e172fb7..941655c290 100644 --- a/.Lib9c.Tests/Model/State/PendingActivationStateTest.cs +++ b/.Lib9c.Tests/Model/State/PendingActivationStateTest.cs @@ -13,7 +13,7 @@ public class PendingActivationStateTest [Fact] public void Serialize() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); @@ -33,7 +33,7 @@ public void Serialize() [Fact] public void SerializeWithDotNetAPI() { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); diff --git a/.Lib9c.Tests/Model/State/RankingMapStateTest.cs b/.Lib9c.Tests/Model/State/RankingMapStateTest.cs index d512af6723..bd5cf02b9b 100644 --- a/.Lib9c.Tests/Model/State/RankingMapStateTest.cs +++ b/.Lib9c.Tests/Model/State/RankingMapStateTest.cs @@ -16,7 +16,7 @@ public class RankingMapStateTest public RankingMapStateTest() { _tableSheets = new TableSheets(TableSheetsImporter.ImportSheets()); - _agentAddress = default(Address); + _agentAddress = default; _rankingMapAddress = _agentAddress.Derive("ranking_map"); } diff --git a/.Lib9c.Tests/Model/State/ShardedShopStateTest.cs b/.Lib9c.Tests/Model/State/ShardedShopStateTest.cs index ba735e0046..bc01615726 100644 --- a/.Lib9c.Tests/Model/State/ShardedShopStateTest.cs +++ b/.Lib9c.Tests/Model/State/ShardedShopStateTest.cs @@ -31,8 +31,8 @@ public ShardedShopStateTest() [InlineData(ItemSubType.FullCostume, "9", "2d977CC12057F55173e50847c8D397b92eFf9d9c")] public void DeriveAddress(ItemSubType itemSubType, string nonce, string addressHex) { - Guid guid = new Guid($"{nonce}9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); - Address expectedAddress = new Address(addressHex); + var guid = new Guid($"{nonce}9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); + var expectedAddress = new Address(addressHex); Assert.Equal(expectedAddress, ShardedShopState.DeriveAddress(itemSubType, guid)); } @@ -49,15 +49,15 @@ public void DeriveAddress_Throw_InvalidItemTypeException(ItemSubType itemSubType [Fact] public void Register() { - ShardedShopState shardedShopState = new ShardedShopState(default(Address)); + var shardedShopState = new ShardedShopState(default(Address)); Assert.Empty(shardedShopState.Products); - Guid itemId = Guid.NewGuid(); + var itemId = Guid.NewGuid(); var itemUsable = new Weapon( _tableSheets.EquipmentItemSheet.First, itemId, 0); - ShopItem shopItem = new ShopItem( + var shopItem = new ShopItem( default, default, default, @@ -70,14 +70,14 @@ public void Register() [Fact] public void Serialize() { - ShardedShopState shardedShopState = new ShardedShopState(default(Address)); - for (int i = 0; i < 4; i++) + var shardedShopState = new ShardedShopState(default(Address)); + for (var i = 0; i < 4; i++) { var itemUsable = new Weapon( _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 0); - ShopItem shopItem = new ShopItem( + var shopItem = new ShopItem( default, default, Guid.NewGuid(), @@ -88,8 +88,8 @@ public void Serialize() Assert.NotEmpty(shardedShopState.Products); - Dictionary serialized = (Dictionary)shardedShopState.Serialize(); - ShardedShopState deserialized = new ShardedShopState(serialized); + var serialized = (Dictionary)shardedShopState.Serialize(); + var deserialized = new ShardedShopState(serialized); Assert.NotEmpty(deserialized.Products); Assert.Equal(shardedShopState.address, deserialized.address); Assert.Equal(shardedShopState.Products.First(), deserialized.Products.First()); diff --git a/.Lib9c.Tests/Model/State/ShardedShopStateV2Test.cs b/.Lib9c.Tests/Model/State/ShardedShopStateV2Test.cs index e575d6f3e5..811b96c731 100644 --- a/.Lib9c.Tests/Model/State/ShardedShopStateV2Test.cs +++ b/.Lib9c.Tests/Model/State/ShardedShopStateV2Test.cs @@ -34,8 +34,8 @@ public ShardedShopStateV2Test() [InlineData(ItemSubType.FullCostume, "9", "006681cA9BD83Bb35cb6675f2cbAE7bD1Fb15F4D")] public void DeriveAddress(ItemSubType itemSubType, string nonce, string addressHex) { - Guid guid = new Guid($"{nonce}9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); - Address expectedAddress = new Address(addressHex); + var guid = new Guid($"{nonce}9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); + var expectedAddress = new Address(addressHex); Assert.Equal(expectedAddress, ShardedShopStateV2.DeriveAddress(itemSubType, guid)); } @@ -55,7 +55,7 @@ public void Add() var orderId = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); var orderId2 = new Guid("936DA01F-9ABD-4d9d-80C7-02AF85C822A8"); - ShardedShopStateV2 shardedShopState = new ShardedShopStateV2(default(Address)); + var shardedShopState = new ShardedShopStateV2(default(Address)); Assert.Empty(shardedShopState.OrderDigestList); var orderDigest = new OrderDigest( @@ -95,8 +95,8 @@ public void Add() [Fact] public void Serialize() { - ShardedShopStateV2 shardedShopState = new ShardedShopStateV2(default(Address)); - for (int i = 0; i < 4; i++) + var shardedShopState = new ShardedShopStateV2(default(Address)); + for (var i = 0; i < 4; i++) { var orderDigest = new OrderDigest( default, @@ -115,8 +115,8 @@ public void Serialize() Assert.NotEmpty(shardedShopState.OrderDigestList); - Dictionary serialized = (Dictionary)shardedShopState.Serialize(); - ShardedShopStateV2 deserialized = new ShardedShopStateV2(serialized); + var serialized = (Dictionary)shardedShopState.Serialize(); + var deserialized = new ShardedShopStateV2(serialized); Assert.NotEmpty(deserialized.OrderDigestList); Assert.Equal(shardedShopState.address, deserialized.address); Assert.Equal(shardedShopState.OrderDigestList.First(), deserialized.OrderDigestList.First()); @@ -125,8 +125,8 @@ public void Serialize() [Fact] public void Serialize_DotNet_Api() { - ShardedShopStateV2 shardedShopState = new ShardedShopStateV2(default(Address)); - for (int i = 0; i < 4; i++) + var shardedShopState = new ShardedShopStateV2(default(Address)); + for (var i = 0; i < 4; i++) { var orderDigest = new OrderDigest( default, @@ -179,7 +179,7 @@ public void Remove() var orderId = new Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"); var orderId2 = new Guid("936DA01F-9ABD-4d9d-80C7-02AF85C822A8"); - ShardedShopStateV2 shardedShopState = new ShardedShopStateV2(default(Address)); + var shardedShopState = new ShardedShopStateV2(default(Address)); Assert.Empty(shardedShopState.OrderDigestList); var order = OrderFactory.Create( diff --git a/.Lib9c.Tests/Model/State/SheetStateTest.cs b/.Lib9c.Tests/Model/State/SheetStateTest.cs index cdbad1ef6b..fedfcd2f19 100644 --- a/.Lib9c.Tests/Model/State/SheetStateTest.cs +++ b/.Lib9c.Tests/Model/State/SheetStateTest.cs @@ -21,15 +21,15 @@ public SheetStateTest(ITestOutputHelper testOutputHelper) [Fact] public void PrintSheetAddresses() { - Assembly assembly = Assembly.GetAssembly(typeof(ISheet)); + var assembly = Assembly.GetAssembly(typeof(ISheet)); Assert.NotNull(assembly); - IEnumerable sheetNames = assembly.GetTypes() + var sheetNames = assembly.GetTypes() .Where(type => type.IsClass && !type.IsAbstract && typeof(ISheet).IsAssignableFrom(type)) .Select(type => type.Name); - foreach (string sheetName in sheetNames) + foreach (var sheetName in sheetNames) { - Address address = Addresses.GetSheetAddress(sheetName); + var address = Addresses.GetSheetAddress(sheetName); _testOutputHelper.WriteLine("{0}: {1}", sheetName, address.ToHex()); } } diff --git a/.Lib9c.Tests/Model/State/StateExtensionsTest.cs b/.Lib9c.Tests/Model/State/StateExtensionsTest.cs index 5f1e99d731..353d2c156e 100644 --- a/.Lib9c.Tests/Model/State/StateExtensionsTest.cs +++ b/.Lib9c.Tests/Model/State/StateExtensionsTest.cs @@ -10,16 +10,16 @@ public class StateExtensionsTest { public static IEnumerable Get_Long_MemberData() { - yield return new object[] { long.MinValue }; - yield return new object[] { 0L }; - yield return new object[] { long.MaxValue }; + yield return new object[] { long.MinValue, }; + yield return new object[] { 0L, }; + yield return new object[] { long.MaxValue, }; } public static IEnumerable Get_BigInteger_MemberData() { - yield return new object[] { (BigInteger)decimal.MinValue }; - yield return new object[] { (BigInteger)0 }; - yield return new object[] { (BigInteger)decimal.MaxValue }; + yield return new object[] { (BigInteger)decimal.MinValue, }; + yield return new object[] { (BigInteger)0, }; + yield return new object[] { (BigInteger)decimal.MaxValue, }; } [Fact] diff --git a/.Lib9c.Tests/Model/WeightedSelectorTest.cs b/.Lib9c.Tests/Model/WeightedSelectorTest.cs index b10376aec6..c0c895232c 100644 --- a/.Lib9c.Tests/Model/WeightedSelectorTest.cs +++ b/.Lib9c.Tests/Model/WeightedSelectorTest.cs @@ -65,8 +65,8 @@ public void SelectV2Single() .Select(r => r.Key) .ToArray(); - Assert.Equal(new[] { 1, 2, 3, 4 }, ordered); - Assert.Equal(new[] { 1, 2, 3, 4 }, ordered2); + Assert.Equal(new[] { 1, 2, 3, 4, }, ordered); + Assert.Equal(new[] { 1, 2, 3, 4, }, ordered2); } [Fact] @@ -118,8 +118,8 @@ public void SelectV2Multiple() .Select(r => r.Key) .ToArray(); - Assert.Equal(new[] { 1, 4, 2, 3 }, ordered); - Assert.Equal(new[] { 1, 2, 3, 4 }, ordered2); + Assert.Equal(new[] { 1, 4, 2, 3, }, ordered); + Assert.Equal(new[] { 1, 2, 3, 4, }, ordered2); } [Theory] @@ -153,7 +153,7 @@ public void Select(int count) .Select(r => r.Key) .ToArray(); - Assert.Equal(new[] { 1, 2, 3, 4 }, ordered); + Assert.Equal(new[] { 1, 2, 3, 4, }, ordered); } private WeightedSelector GetSelector() diff --git a/.Lib9c.Tests/Module/CollectionModuleTest.cs b/.Lib9c.Tests/Module/CollectionModuleTest.cs index fe3e7c5cc5..abf7e54b07 100644 --- a/.Lib9c.Tests/Module/CollectionModuleTest.cs +++ b/.Lib9c.Tests/Module/CollectionModuleTest.cs @@ -41,7 +41,7 @@ public void CollectionStates() IWorld states = new World(MockUtil.MockModernWorldState); var address = new PrivateKey().Address; var address2 = new PrivateKey().Address; - var addresses = new[] { address, address2 }; + var addresses = new[] { address, address2, }; var result = states.GetCollectionStates(addresses); Assert.Empty(result); diff --git a/.Lib9c.Tests/Policy/BlockPolicySourceTest.cs b/.Lib9c.Tests/Policy/BlockPolicySourceTest.cs index 1b4bd538c0..8b08dc4e7a 100644 --- a/.Lib9c.Tests/Policy/BlockPolicySourceTest.cs +++ b/.Lib9c.Tests/Policy/BlockPolicySourceTest.cs @@ -36,13 +36,13 @@ public void IsObsolete() 0, new PrivateKey(), OdinGenesisHash, - new[] { buy.PlainValue } + new[] { buy.PlainValue, } ); var heimdallTx = Transaction.Create( 0, new PrivateKey(), HeimdallGenesisHash, - new[] { buy.PlainValue } + new[] { buy.PlainValue, } ); var ncActionLoader = new NCActionLoader(); @@ -54,19 +54,19 @@ public void IsObsolete() 0, new PrivateKey(), OdinGenesisHash, - new[] { Dictionary.Empty } + new[] { Dictionary.Empty, } ); var heimdallTx2 = Transaction.Create( 0, new PrivateKey(), HeimdallGenesisHash, - new[] { Dictionary.Empty } + new[] { Dictionary.Empty, } ); var newActionLoader = new SingleActionLoader(typeof(NewAction)); Assert.False(BlockPolicySource.IsObsolete(odinTx2, newActionLoader, 1)); Assert.False(BlockPolicySource.IsObsolete(odinTx2, newActionLoader, 50)); - Assert.True(BlockPolicySource.IsObsolete(odinTx2, newActionLoader, 103)); // Due to +2 offset for odin bug + Assert.True(BlockPolicySource.IsObsolete(odinTx2, newActionLoader, 103)); // Due to +2 offset for odin bug Assert.False(BlockPolicySource.IsObsolete(heimdallTx2, newActionLoader, 1)); Assert.True(BlockPolicySource.IsObsolete(heimdallTx2, newActionLoader, 51)); } diff --git a/.Lib9c.Tests/Policy/BlockPolicyTest.cs b/.Lib9c.Tests/Policy/BlockPolicyTest.cs index 7283abe1c1..539cc75b30 100644 --- a/.Lib9c.Tests/Policy/BlockPolicyTest.cs +++ b/.Lib9c.Tests/Policy/BlockPolicyTest.cs @@ -51,30 +51,30 @@ public void ValidateNextBlockTx_Mead() var adminAddress = adminPrivateKey.Address; var blockPolicySource = new BlockPolicySource(); var actionTypeLoader = new NCActionLoader(); - IBlockPolicy policy = blockPolicySource.GetPolicy(null, null, null, null); + var policy = blockPolicySource.GetPolicy(null, null, null, null); IStagePolicy stagePolicy = new VolatileStagePolicy(); var mint = new PrepareRewardAssets { RewardPoolAddress = adminAddress, Assets = new List - { - 1 * Currencies.Mead, - }, + { + 1 * Currencies.Mead, + }, }; var mint2 = new PrepareRewardAssets { RewardPoolAddress = MeadConfig.PatronAddress, Assets = new List - { - 1 * Currencies.Mead, - }, + { + 1 * Currencies.Mead, + }, }; - Block genesis = MakeGenesisBlock( + var genesis = MakeGenesisBlock( adminAddress, ImmutableHashSet
.Empty, initialValidators: new Dictionary - { { adminPrivateKey.PublicKey, BigInteger.One } }, - actionBases: new[] { mint, mint2 }, + { { adminPrivateKey.PublicKey, BigInteger.One }, }, + actionBases: new[] { mint, mint2, }, privateKey: adminPrivateKey ); using var store = new DefaultStore(null); @@ -87,13 +87,13 @@ public void ValidateNextBlockTx_Mead() genesis, new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ), - renderers: new[] { new BlockRenderer() } + new[] { new BlockRenderer(), } ); - Block block = blockChain.ProposeBlock(adminPrivateKey); + var block = blockChain.ProposeBlock(adminPrivateKey); blockChain.Append(block, GenerateBlockCommit(block, adminPrivateKey)); Assert.Equal( @@ -111,7 +111,7 @@ public void ValidateNextBlockTx_Mead() avatarAddress = adminAddress, }; - Transaction txEmpty = + var txEmpty = Transaction.Create( 0, adminPrivateKey, @@ -120,34 +120,34 @@ public void ValidateNextBlockTx_Mead() ); Assert.IsType(BlockPolicySource.ValidateNextBlockTxRaw(blockChain, actionTypeLoader, txEmpty)); - Transaction tx1 = + var tx1 = Transaction.Create( 0, adminPrivateKey, genesis.Hash, - actions: new ActionBase[] { action }.ToPlainValues() + new ActionBase[] { action, }.ToPlainValues() ); Assert.IsType(BlockPolicySource.ValidateNextBlockTxRaw(blockChain, actionTypeLoader, tx1)); - Transaction tx2 = + var tx2 = Transaction.Create( 1, adminPrivateKey, genesis.Hash, gasLimit: 1, maxGasPrice: new FungibleAssetValue(Currencies.Mead, 10, 10), - actions: new ActionBase[] { action }.ToPlainValues() + actions: new ActionBase[] { action, }.ToPlainValues() ); Assert.Null(BlockPolicySource.ValidateNextBlockTxRaw(blockChain, actionTypeLoader, tx2)); - Transaction tx3 = + var tx3 = Transaction.Create( 2, adminPrivateKey, genesis.Hash, gasLimit: 1, maxGasPrice: new FungibleAssetValue(Currencies.Mead, 0, 0), - actions: new ActionBase[] { action }.ToPlainValues() + actions: new ActionBase[] { action, }.ToPlainValues() ); Assert.Null(BlockPolicySource.ValidateNextBlockTxRaw(blockChain, actionTypeLoader, tx3)); } @@ -160,13 +160,13 @@ public void BlockCommitFromNonValidator() var nonValidator = new PrivateKey(); var blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy(null, null, null, null); + var policy = blockPolicySource.GetPolicy(null, null, null, null); IStagePolicy stagePolicy = new VolatileStagePolicy(); - Block genesis = MakeGenesisBlock( + var genesis = MakeGenesisBlock( adminAddress, ImmutableHashSet.Create(adminAddress), initialValidators: new Dictionary - { { adminPrivateKey.PublicKey, BigInteger.One } } + { { adminPrivateKey.PublicKey, BigInteger.One }, } ); using var store = new DefaultStore(null); using var stateStore = new TrieStateStore(new DefaultKeyValueStore(null)); @@ -178,12 +178,12 @@ public void BlockCommitFromNonValidator() genesis, new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ), - renderers: new[] { new BlockRenderer() } + new[] { new BlockRenderer(), } ); - Block block1 = blockChain.ProposeBlock(adminPrivateKey); + var block1 = blockChain.ProposeBlock(adminPrivateKey); Assert.Throws( () => blockChain.Append(block1, GenerateBlockCommit(block1, nonValidator))); } @@ -195,27 +195,27 @@ public void MustNotIncludeBlockActionAtTransaction() var adminAddress = adminPrivateKey.Address; var authorizedMinerPrivateKey = new PrivateKey(); - (ActivationKey ak, PendingActivationState ps) = ActivationKey.Create( + (var ak, var ps) = ActivationKey.Create( new PrivateKey(), - new byte[] { 0x00, 0x01 } + new byte[] { 0x00, 0x01, } ); var blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy( - maxTransactionsBytesPolicy: null, - minTransactionsPerBlockPolicy: null, - maxTransactionsPerBlockPolicy: null, - maxTransactionsPerSignerPerBlockPolicy: null); + var policy = blockPolicySource.GetPolicy( + null, + null, + null, + null); IStagePolicy stagePolicy = new VolatileStagePolicy(); - Block genesis = MakeGenesisBlock( + var genesis = MakeGenesisBlock( adminAddress, ImmutableHashSet.Create(adminAddress), new AuthorizedMinersState( - new[] { authorizedMinerPrivateKey.Address }, + new[] { authorizedMinerPrivateKey.Address, }, 5, 10 ), - pendingActivations: new[] { ps } + pendingActivations: new[] { ps, } ); using var store = new DefaultStore(null); using var stateStore = new TrieStateStore(new DefaultKeyValueStore(null)); @@ -228,14 +228,14 @@ public void MustNotIncludeBlockActionAtTransaction() genesis, new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: actionLoader + stateStore, + actionLoader ), - renderers: new[] { new BlockRenderer() } + new[] { new BlockRenderer(), } ); var unloadableAction = blockChain.MakeTransaction( - adminPrivateKey, new ActionBase[] { new RewardGold() }).Actions[0]; + adminPrivateKey, new ActionBase[] { new RewardGold(), }).Actions[0]; Assert.Throws(() => actionLoader.LoadAction(blockChain.Tip.Index, unloadableAction)); } @@ -247,28 +247,28 @@ public void EarnMiningGoldWhenSuccessMining() var adminAddress = adminPrivateKey.Address; var authorizedMinerPrivateKey = new PrivateKey(); - (ActivationKey ak, PendingActivationState ps) = ActivationKey.Create( + (var ak, var ps) = ActivationKey.Create( new PrivateKey(), - new byte[] { 0x00, 0x01 } + new byte[] { 0x00, 0x01, } ); var blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy( - maxTransactionsBytesPolicy: null, - minTransactionsPerBlockPolicy: null, - maxTransactionsPerBlockPolicy: null, - maxTransactionsPerSignerPerBlockPolicy: null); + var policy = blockPolicySource.GetPolicy( + null, + null, + null, + null); IStagePolicy stagePolicy = new VolatileStagePolicy(); - Block genesis = MakeGenesisBlock( + var genesis = MakeGenesisBlock( adminAddress, ImmutableHashSet.Create(adminAddress), new AuthorizedMinersState( - new[] { authorizedMinerPrivateKey.Address }, + new[] { authorizedMinerPrivateKey.Address, }, 5, 10 ), - new Dictionary { { adminPrivateKey.PublicKey, BigInteger.One } }, - pendingActivations: new[] { ps } + new Dictionary { { adminPrivateKey.PublicKey, BigInteger.One }, }, + pendingActivations: new[] { ps, } ); using var store = new DefaultStore(null); @@ -281,10 +281,10 @@ public void EarnMiningGoldWhenSuccessMining() genesis, new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ), - renderers: new[] { new BlockRenderer() } + new[] { new BlockRenderer(), } ); blockChain.MakeTransaction( @@ -292,12 +292,12 @@ public void EarnMiningGoldWhenSuccessMining() new ActionBase[] { new DailyReward(), } ); - Block block = blockChain.ProposeBlock(adminPrivateKey); + var block = blockChain.ProposeBlock(adminPrivateKey); blockChain.Append(block, GenerateBlockCommit(block, adminPrivateKey)); - FungibleAssetValue actualBalance = blockChain + var actualBalance = blockChain .GetNextWorldState() .GetBalance(adminAddress, _currency); - FungibleAssetValue expectedBalance = new FungibleAssetValue(_currency, 10, 0); + var expectedBalance = new FungibleAssetValue(_currency, 10, 0); Assert.True(expectedBalance.Equals(actualBalance)); } @@ -307,27 +307,27 @@ public void ValidateNextBlockWithManyTransactions() var adminPrivateKey = new PrivateKey(); var adminPublicKey = adminPrivateKey.PublicKey; var blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy( - maxTransactionsBytesPolicy: null, - minTransactionsPerBlockPolicy: null, - maxTransactionsPerBlockPolicy: MaxTransactionsPerBlockPolicy + var policy = blockPolicySource.GetPolicy( + null, + null, + MaxTransactionsPerBlockPolicy .Default .Add(new SpannedSubPolicy(0, null, null, 10)), - maxTransactionsPerSignerPerBlockPolicy: null); + null); IStagePolicy stagePolicy = new VolatileStagePolicy(); - Block genesis = + var genesis = MakeGenesisBlock( adminPublicKey.Address, ImmutableHashSet
.Empty, initialValidators: new Dictionary - { { adminPrivateKey.PublicKey, BigInteger.One } }); + { { adminPrivateKey.PublicKey, BigInteger.One }, }); using var store = new DefaultStore(null); var stateStore = new TrieStateStore(new MemoryKeyValueStore()); var actionEvaluator = new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ); var blockChain = BlockChain.Create( policy, @@ -338,11 +338,12 @@ public void ValidateNextBlockWithManyTransactions() actionEvaluator ); - int nonce = 0; + var nonce = 0; + List GenerateTransactions(int count) { var list = new List(); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { list.Add(Transaction.Create( nonce++, @@ -362,51 +363,51 @@ List GenerateTransactions(int count) var evs = new List(); var preEvalBlock1 = new BlockContent( new BlockMetadata( - index: 1, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: null, - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); + 1, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + null, + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); var stateRootHash = blockChain.DetermineNextBlockStateRootHash(blockChain.Tip, out _); - Block block1 = EvaluateAndSign(stateRootHash, preEvalBlock1, adminPrivateKey); + var block1 = EvaluateAndSign(stateRootHash, preEvalBlock1, adminPrivateKey); blockChain.Append(block1, GenerateBlockCommit(block1, adminPrivateKey)); Assert.Equal(2, blockChain.Count); Assert.True(blockChain.ContainsBlock(block1.Hash)); txs = GenerateTransactions(10).OrderBy(tx => tx.Id).ToList(); - PreEvaluationBlock preEvalBlock2 = new BlockContent( + var preEvalBlock2 = new BlockContent( new BlockMetadata( - index: 2, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: GenerateBlockCommit(blockChain.Tip, adminPrivateKey), - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); + 2, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + GenerateBlockCommit(blockChain.Tip, adminPrivateKey), + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); stateRootHash = blockChain.DetermineNextBlockStateRootHash(blockChain.Tip, out _); - Block block2 = EvaluateAndSign(stateRootHash, preEvalBlock2, adminPrivateKey); + var block2 = EvaluateAndSign(stateRootHash, preEvalBlock2, adminPrivateKey); blockChain.Append(block2, GenerateBlockCommit(block2, adminPrivateKey)); Assert.Equal(3, blockChain.Count); Assert.True(blockChain.ContainsBlock(block2.Hash)); txs = GenerateTransactions(11).OrderBy(tx => tx.Id).ToList(); - PreEvaluationBlock preEvalBlock3 = new BlockContent( + var preEvalBlock3 = new BlockContent( new BlockMetadata( - index: 3, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: GenerateBlockCommit(blockChain.Tip, adminPrivateKey), - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); + 3, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + GenerateBlockCommit(blockChain.Tip, adminPrivateKey), + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); stateRootHash = blockChain.DetermineNextBlockStateRootHash(blockChain.Tip, out _); - Block block3 = EvaluateAndSign(stateRootHash, preEvalBlock3, adminPrivateKey); + var block3 = EvaluateAndSign(stateRootHash, preEvalBlock3, adminPrivateKey); Assert.Throws( () => blockChain.Append(block3, GenerateBlockCommit(block3, adminPrivateKey))); Assert.Equal(3, blockChain.Count); @@ -419,29 +420,29 @@ public void ValidateNextBlockWithManyTransactionsPerSigner() var adminPrivateKey = new PrivateKey(); var adminPublicKey = adminPrivateKey.PublicKey; var blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy( - maxTransactionsBytesPolicy: null, - minTransactionsPerBlockPolicy: null, - maxTransactionsPerBlockPolicy: MaxTransactionsPerBlockPolicy + var policy = blockPolicySource.GetPolicy( + null, + null, + MaxTransactionsPerBlockPolicy .Default .Add(new SpannedSubPolicy(0, null, null, 10)), - maxTransactionsPerSignerPerBlockPolicy: MaxTransactionsPerSignerPerBlockPolicy + MaxTransactionsPerSignerPerBlockPolicy .Default .Add(new SpannedSubPolicy(2, null, null, 5))); IStagePolicy stagePolicy = new VolatileStagePolicy(); - Block genesis = + var genesis = MakeGenesisBlock( adminPublicKey.Address, ImmutableHashSet
.Empty, initialValidators: new Dictionary - { { adminPrivateKey.PublicKey, BigInteger.One } }); + { { adminPrivateKey.PublicKey, BigInteger.One }, }); using var store = new DefaultStore(null); var stateStore = new TrieStateStore(new MemoryKeyValueStore()); var actionEvaluator = new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ); var blockChain = BlockChain.Create( policy, @@ -452,11 +453,12 @@ public void ValidateNextBlockWithManyTransactionsPerSigner() actionEvaluator ); - int nonce = 0; + var nonce = 0; + List GenerateTransactions(int count) { var list = new List(); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { list.Add(Transaction.Create( nonce++, @@ -474,19 +476,19 @@ List GenerateTransactions(int count) Assert.Equal(1, blockChain.Count); var txs = GenerateTransactions(10).OrderBy(tx => tx.Id).ToList(); var evs = new List(); - PreEvaluationBlock preEvalBlock1 = new BlockContent( + var preEvalBlock1 = new BlockContent( new BlockMetadata( - index: 1, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: null, - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); + 1, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + null, + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); var stateRootHash = blockChain.DetermineNextBlockStateRootHash(blockChain.Tip, out _); - Block block1 = EvaluateAndSign(stateRootHash, preEvalBlock1, adminPrivateKey); + var block1 = EvaluateAndSign(stateRootHash, preEvalBlock1, adminPrivateKey); // Should be fine since policy hasn't kicked in yet. blockChain.Append(block1, GenerateBlockCommit(block1, adminPrivateKey)); @@ -494,19 +496,19 @@ List GenerateTransactions(int count) Assert.True(blockChain.ContainsBlock(block1.Hash)); txs = GenerateTransactions(10).OrderBy(tx => tx.Id).ToList(); - PreEvaluationBlock preEvalBlock2 = new BlockContent( + var preEvalBlock2 = new BlockContent( new BlockMetadata( - index: 2, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: GenerateBlockCommit(blockChain.Tip, adminPrivateKey), - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); + 2, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + GenerateBlockCommit(blockChain.Tip, adminPrivateKey), + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); stateRootHash = blockChain.DetermineNextBlockStateRootHash(blockChain.Tip, out _); - Block block2 = EvaluateAndSign(stateRootHash, preEvalBlock2, adminPrivateKey); + var block2 = EvaluateAndSign(stateRootHash, preEvalBlock2, adminPrivateKey); // Subpolicy kicks in. Assert.Throws( @@ -518,18 +520,18 @@ List GenerateTransactions(int count) // Limit should also pass. txs = GenerateTransactions(5).OrderBy(tx => tx.Id).ToList(); - PreEvaluationBlock preEvalBlock3 = new BlockContent( + var preEvalBlock3 = new BlockContent( new BlockMetadata( - index: 2, - timestamp: DateTimeOffset.MinValue, - publicKey: adminPublicKey, - previousHash: blockChain.Tip.Hash, - txHash: BlockContent.DeriveTxHash(txs), - lastCommit: GenerateBlockCommit(blockChain.Tip, adminPrivateKey), - evidenceHash: BlockContent.DeriveEvidenceHash(evs)), - transactions: txs, - evidence: evs).Propose(); - Block block3 = EvaluateAndSign(stateRootHash, preEvalBlock3, adminPrivateKey); + 2, + DateTimeOffset.MinValue, + adminPublicKey, + blockChain.Tip.Hash, + BlockContent.DeriveTxHash(txs), + GenerateBlockCommit(blockChain.Tip, adminPrivateKey), + BlockContent.DeriveEvidenceHash(evs)), + txs, + evs).Propose(); + var block3 = EvaluateAndSign(stateRootHash, preEvalBlock3, adminPrivateKey); blockChain.Append(block3, GenerateBlockCommit(block3, adminPrivateKey)); Assert.Equal(3, blockChain.Count); Assert.True(blockChain.ContainsBlock(block3.Hash)); @@ -537,7 +539,7 @@ List GenerateTransactions(int count) private BlockCommit GenerateBlockCommit(Block block, PrivateKey key) { - PrivateKey privateKey = key; + var privateKey = key; return block.Index != 0 ? new BlockCommit( block.Index, @@ -566,10 +568,10 @@ private Block MakeGenesisBlock( { if (pendingActivations is null) { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; - (ActivationKey activationKey, PendingActivationState pendingActivation) = + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; + (var activationKey, var pendingActivation) = ActivationKey.Create(_privateKey, nonce); - pendingActivations = new[] { pendingActivation }; + pendingActivations = new[] { pendingActivation, }; } var sheets = TableSheetsImporter.ImportSheets(); @@ -578,14 +580,14 @@ private Block MakeGenesisBlock( new GoldDistribution[0], pendingActivations, new AdminState(adminAddress, 1500000), - authorizedMinersState: authorizedMinersState, - activatedAccounts: activatedAddresses, - initialValidators: initialValidators, - isActivateAdminAddress: false, - credits: null, - privateKey: privateKey ?? _privateKey, - timestamp: timestamp ?? DateTimeOffset.MinValue, - actionBases: actionBases); + authorizedMinersState, + activatedAddresses, + initialValidators, + false, + null, + privateKey ?? _privateKey, + timestamp ?? DateTimeOffset.MinValue, + actionBases); } private Block EvaluateAndSign( diff --git a/.Lib9c.Tests/Policy/ConcreteSubPolicy.cs b/.Lib9c.Tests/Policy/ConcreteSubPolicy.cs index a527479814..1246af59e1 100644 --- a/.Lib9c.Tests/Policy/ConcreteSubPolicy.cs +++ b/.Lib9c.Tests/Policy/ConcreteSubPolicy.cs @@ -16,7 +16,9 @@ private ConcreteSubPolicy( { } - public static ConcreteSubPolicy Create(T defaultValue) => - new ConcreteSubPolicy(defaultValue); + public static ConcreteSubPolicy Create(T defaultValue) + { + return new ConcreteSubPolicy(defaultValue); + } } } diff --git a/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs b/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs index d2b13a5cc3..023194c9ef 100644 --- a/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs +++ b/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs @@ -17,13 +17,13 @@ public ConcreteSubPolicyTest() public void Constructor() { IVariableSubPolicy genericSubPolicy; - List indices = Enumerable.Range(0, 100).Select(i => (long)i).ToList(); + var indices = Enumerable.Range(0, 100).Select(i => (long)i).ToList(); - SpannedSubPolicy first = new SpannedSubPolicy(10, null, null, true); - SpannedSubPolicy badSecond = new SpannedSubPolicy(5, null, index => index % 2 == 0, true); - SpannedSubPolicy second = new SpannedSubPolicy(20, 50, index => index % 2 == 0, true); - SpannedSubPolicy third = new SpannedSubPolicy(30, 40, null, true); - SpannedSubPolicy fourth = new SpannedSubPolicy(50, 80, index => index % 5 == 0, true); + var first = new SpannedSubPolicy(10, null, null, true); + var badSecond = new SpannedSubPolicy(5, null, index => index % 2 == 0, true); + var second = new SpannedSubPolicy(20, 50, index => index % 2 == 0, true); + var third = new SpannedSubPolicy(30, 40, null, true); + var fourth = new SpannedSubPolicy(50, 80, index => index % 5 == 0, true); // Should be fine. genericSubPolicy = ConcreteSubPolicy @@ -71,10 +71,10 @@ public void Constructor() // Create using AddRange(). genericSubPolicy = ConcreteSubPolicy .Create(false) - .AddRange(new List>() { first, second, third, fourth }.ToImmutableList()); + .AddRange(new List>() { first, second, third, fourth, }.ToImmutableList()); Assert.Throws(() => ConcreteSubPolicy .Create(false) - .AddRange(new List>() { second, first }.ToImmutableList())); + .AddRange(new List>() { second, first, }.ToImmutableList())); // Type check Assert.IsType>(genericSubPolicy); diff --git a/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs b/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs index 860eb9383a..d544ec2d85 100644 --- a/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs +++ b/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs @@ -16,7 +16,7 @@ public SpannedSubPolicyTest() public void Constructor() { SpannedSubPolicy spannedSubPolicy; - List indices = Enumerable.Range(0, 100).Select(i => (long)i).ToList(); + var indices = Enumerable.Range(0, 100).Select(i => (long)i).ToList(); // Bad start index Assert.Throws(() => diff --git a/.Lib9c.Tests/SerializeKeysTest.cs b/.Lib9c.Tests/SerializeKeysTest.cs index 523486faf1..92afed63ad 100644 --- a/.Lib9c.Tests/SerializeKeysTest.cs +++ b/.Lib9c.Tests/SerializeKeysTest.cs @@ -11,16 +11,16 @@ public class SerializeKeysTest [Fact] public void Keys_Duplicate() { - Type type = typeof(SerializeKeys); - FieldInfo[] fields = type.GetFields(BindingFlags.Public - | BindingFlags.Static - | BindingFlags.FlattenHierarchy); - Dictionary keyMap = new Dictionary(); + var type = typeof(SerializeKeys); + var fields = type.GetFields(BindingFlags.Public + | BindingFlags.Static + | BindingFlags.FlattenHierarchy); + var keyMap = new Dictionary(); foreach (var info in fields.Where(fieldInfo => fieldInfo.IsLiteral && !fieldInfo.IsInitOnly)) { - string key = (string)info.GetValue(type); + var key = (string)info.GetValue(type); Assert.NotNull(key); - string value = info.Name; + var value = info.Name; if (keyMap.ContainsKey(key)) { throw new Exception($"`{info.Name}`s value `{key}` is already used in {keyMap[key]}."); diff --git a/.Lib9c.Tests/StagePolicyTest.cs b/.Lib9c.Tests/StagePolicyTest.cs index 0dca40d5ca..1a29af026d 100644 --- a/.Lib9c.Tests/StagePolicyTest.cs +++ b/.Lib9c.Tests/StagePolicyTest.cs @@ -50,8 +50,8 @@ public StagePolicyTest() [Fact] public void Stage() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); stagePolicy.Stage(chain, _txs[_accounts[0].Address][0]); stagePolicy.Stage(chain, _txs[_accounts[0].Address][1]); @@ -71,8 +71,8 @@ public void Stage() [Fact] public void StageOverQuota() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); stagePolicy.Stage(chain, _txs[_accounts[0].Address][0]); stagePolicy.Stage(chain, _txs[_accounts[0].Address][1]); @@ -90,8 +90,8 @@ public void StageOverQuota() [Fact] public void StageOverQuotaInverseOrder() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); stagePolicy.Stage(chain, _txs[_accounts[0].Address][3]); stagePolicy.Stage(chain, _txs[_accounts[0].Address][2]); @@ -109,8 +109,8 @@ public void StageOverQuotaInverseOrder() [Fact] public void StageOverQuotaOutOfOrder() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); stagePolicy.Stage(chain, _txs[_accounts[0].Address][2]); stagePolicy.Stage(chain, _txs[_accounts[0].Address][1]); @@ -128,8 +128,8 @@ public void StageOverQuotaOutOfOrder() [Fact] public void StageSameNonce() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); var txA = Transaction.Create(0, _accounts[0], default, new ActionBase[0].ToPlainValues()); var txB = Transaction.Create(0, _accounts[0], default, new ActionBase[0].ToPlainValues()); var txC = Transaction.Create(0, _accounts[0], default, new ActionBase[0].ToPlainValues()); @@ -144,16 +144,13 @@ public void StageSameNonce() [Fact] public async Task StateFromMultiThread() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); await Task.WhenAll( Enumerable .Range(0, 40) - .Select(i => Task.Run(() => - { - stagePolicy.Stage(chain, _txs[_accounts[i / 10].Address][i % 10]); - })) + .Select(i => Task.Run(() => { stagePolicy.Stage(chain, _txs[_accounts[i / 10].Address][i % 10]); })) ); AssertTxs( chain, @@ -172,8 +169,8 @@ await Task.WhenAll( [Fact] public void IterateAfterUnstage() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); stagePolicy.Stage(chain, _txs[_accounts[0].Address][0]); stagePolicy.Stage(chain, _txs[_accounts[0].Address][1]); @@ -200,10 +197,10 @@ public void IterateAfterUnstage() [Fact] public void CalculateNextTxNonceCorrectWhenTxOverQuota() { - NCStagePolicy stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); - BlockChain chain = MakeChainWithStagePolicy(stagePolicy); + var stagePolicy = new NCStagePolicy(TimeSpan.FromHours(1), 2); + var chain = MakeChainWithStagePolicy(stagePolicy); - long nextTxNonce = chain.GetNextTxNonce(_accounts[0].Address); + var nextTxNonce = chain.GetNextTxNonce(_accounts[0].Address); Assert.Equal(0, nextTxNonce); var txA = Transaction.Create(nextTxNonce, _accounts[0], default, new ActionBase[0].ToPlainValues()); stagePolicy.Stage(chain, txA); @@ -230,26 +227,26 @@ public void CalculateNextTxNonceCorrectWhenTxOverQuota() private void AssertTxs(BlockChain blockChain, NCStagePolicy policy, params Transaction[] txs) { - foreach (Transaction tx in txs) + foreach (var tx in txs) { - Assert.Equal(tx, policy.Get(blockChain, tx.Id, filtered: true)); + Assert.Equal(tx, policy.Get(blockChain, tx.Id, true)); } Assert.Equal( txs.ToHashSet(), - policy.Iterate(blockChain, filtered: true).ToHashSet() + policy.Iterate(blockChain, true).ToHashSet() ); } private BlockChain MakeChainWithStagePolicy(NCStagePolicy stagePolicy) { - BlockPolicySource blockPolicySource = new BlockPolicySource(); - IBlockPolicy policy = blockPolicySource.GetPolicy(); - BlockChain chain = + var blockPolicySource = new BlockPolicySource(); + var policy = blockPolicySource.GetPolicy(); + var chain = BlockChainHelper.MakeBlockChain( - blockRenderers: new[] { new BlockRenderer() }, - policy: policy, - stagePolicy: stagePolicy); + new[] { new BlockRenderer(), }, + policy, + stagePolicy); return chain; } } diff --git a/.Lib9c.Tests/TableData/CollectionSheetTest.cs b/.Lib9c.Tests/TableData/CollectionSheetTest.cs index 47576e7c21..d7350d0ff3 100644 --- a/.Lib9c.Tests/TableData/CollectionSheetTest.cs +++ b/.Lib9c.Tests/TableData/CollectionSheetTest.cs @@ -12,26 +12,26 @@ namespace Lib9c.Tests.TableData public class CollectionSheetTest { - private readonly TableSheets _tableSheets = - new TableSheets(TableSheetsImporter.ImportSheets()); + private readonly TableSheets _tableSheets = new (TableSheetsImporter.ImportSheets()); [Fact] public void Set() { - const string csv = @"id,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,option_count,skill,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value\n + const string csv = + @"id,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,skill,item_id,count,level,option_count,skill,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value,stat_type,modify_type,modify_value\n 1,1,2,3,,,,,,,,,,,,,,,,,,,,,,ATK,Add,1,,,,,,\n 2,2,3,4,,,,,,,,,,,,,,,,,,,,,,ATK,Percentage,1,,,,,,\n"; var sheet = new CollectionSheet(); sheet.Set(csv); - for (int i = 0; i < 1; i++) + for (var i = 0; i < 1; i++) { var id = i + 1; var row = sheet[id]; Assert.Equal(id, row.Id); Assert.Equal(id, row.Materials.Count); Assert.Equal(id, row.StatModifiers.Count); - for (int j = 0; j < id; j++) + for (var j = 0; j < id; j++) { var material = row.Materials[j]; Assert.Equal(id, material.ItemId); @@ -60,14 +60,14 @@ public void Validate_Equipment(bool skillContains, int skillCount, int buffSkill { var row = _tableSheets.ItemSheet.Values.First(r => r.ItemType == ItemType.Equipment); var item = (Equipment)ItemFactory.CreateItem(row, new TestRandom()); - for (int i = 0; i < skillCount; i++) + for (var i = 0; i < skillCount; i++) { var skillRow = _tableSheets.SkillSheet.Values.First(); var skill = SkillFactory.Get(skillRow, 0, 0, 0, StatType.NONE); item.Skills.Add(skill); } - for (int i = 0; i < buffSkillCount; i++) + for (var i = 0; i < buffSkillCount; i++) { var skillId = _tableSheets.SkillBuffSheet.Values.First().SkillId; var buffSkillRow = _tableSheets.SkillSheet[skillId]; @@ -108,7 +108,7 @@ public void GetMaterial() { var collectionMaterials = new List(); var materials = new List(); - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { var itemId = i + 1; var count = 3 - i; diff --git a/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftOptionSheetTest.cs b/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftOptionSheetTest.cs index 435d46ec8a..eb0ba1d143 100644 --- a/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftOptionSheetTest.cs +++ b/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftOptionSheetTest.cs @@ -22,7 +22,7 @@ public class CustomEquipmentCraftOptionSheetTest 100, new List { - new () { StatType = StatType.ATK, Ratio = 100 }, + new () { StatType = StatType.ATK, Ratio = 100, }, }, }; @@ -35,8 +35,8 @@ public class CustomEquipmentCraftOptionSheetTest 100, new List { - new () { StatType = StatType.ATK, Ratio = 50 }, - new () { StatType = StatType.HIT, Ratio = 50 }, + new () { StatType = StatType.ATK, Ratio = 50, }, + new () { StatType = StatType.HIT, Ratio = 50, }, }, }; @@ -49,7 +49,7 @@ public class CustomEquipmentCraftOptionSheetTest 100, new List { - new () { StatType = StatType.DEF, Ratio = 100 }, + new () { StatType = StatType.DEF, Ratio = 100, }, }, }; } diff --git a/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftRelationshipSheetTest.cs b/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftRelationshipSheetTest.cs index ceee9020bd..2832014415 100644 --- a/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftRelationshipSheetTest.cs +++ b/.Lib9c.Tests/TableData/CustomEquipmentCraft/CustomEquipmentCraftRelationshipSheetTest.cs @@ -20,7 +20,7 @@ public void Set() var row = sheet.Values.First(); - var minCpList = new[] { 100, 200, 300, 400, 500, 600, 700, 800, 900 }; + var minCpList = new[] { 100, 200, 300, 400, 500, 600, 700, 800, 900, }; Assert.Equal(100, row.Relationship); Assert.Equal(1, row.CostMultiplier); Assert.Equal(1, row.RequiredBlockMultiplier); diff --git a/.Lib9c.Tests/TableData/Event/EventDungeonStageSheetTest.cs b/.Lib9c.Tests/TableData/Event/EventDungeonStageSheetTest.cs index cab963fa39..fe564fb788 100644 --- a/.Lib9c.Tests/TableData/Event/EventDungeonStageSheetTest.cs +++ b/.Lib9c.Tests/TableData/Event/EventDungeonStageSheetTest.cs @@ -8,7 +8,8 @@ public class EventDungeonStageSheetTest [Fact] public void Set() { - const string csv = @"id,cost_ap,turn_limit,hp_option,atk_option,def_option,cri_option,hit_option,spd_option,background,bgm,item1,item1_ratio,item1_min,item1_max,item2,item2_ratio,item2_min,item2_max,item3,item3_ratio,item3_min,item3_max,item4,item4_ratio,item4_min,item4_max,item5,item5_ratio,item5_min,item5_max,item6,item6_ratio,item6_min,item6_max,item7,item7_ratio,item7_min,item7_max,item8,item8_ratio,item8_min,item8_max,item9,item9_ratio,item9_min,item9_max,item10,item10_ratio,item10_min,item10_max,min_drop,max_drop + const string csv = + @"id,cost_ap,turn_limit,hp_option,atk_option,def_option,cri_option,hit_option,spd_option,background,bgm,item1,item1_ratio,item1_min,item1_max,item2,item2_ratio,item2_min,item2_max,item3,item3_ratio,item3_min,item3_max,item4,item4_ratio,item4_min,item4_max,item5,item5_ratio,item5_min,item5_max,item6,item6_ratio,item6_min,item6_max,item7,item7_ratio,item7_min,item7_max,item8,item8_ratio,item8_min,item8_max,item9,item9_ratio,item9_min,item9_max,item10,item10_ratio,item10_min,item10_max,min_drop,max_drop 10010001,5,150,0,0,0,0,0,0,chapter_01_01,bgm_yggdrasil_01,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0,0"; var sheet = new EventDungeonStageSheet(); diff --git a/.Lib9c.Tests/TableData/Event/EventMaterialItemRecipeSheetTest.cs b/.Lib9c.Tests/TableData/Event/EventMaterialItemRecipeSheetTest.cs index 788b67bcd5..9eb68eaa65 100644 --- a/.Lib9c.Tests/TableData/Event/EventMaterialItemRecipeSheetTest.cs +++ b/.Lib9c.Tests/TableData/Event/EventMaterialItemRecipeSheetTest.cs @@ -10,7 +10,8 @@ public class EventMaterialItemRecipeSheetTest public void Set() { var sb = new StringBuilder(); - sb.AppendLine("id,result_consumable_item_id,result_consumable_item_count,material_item_count,material_item_id_1,material_item_id_2,material_item_id_3,material_item_id_4,material_item_id_5,material_item_id_6,material_item_id_7,material_item_id_8,material_item_id_9,material_item_id_10,material_item_id_11,material_item_id_12"); + sb.AppendLine( + "id,result_consumable_item_id,result_consumable_item_count,material_item_count,material_item_id_1,material_item_id_2,material_item_id_3,material_item_id_4,material_item_id_5,material_item_id_6,material_item_id_7,material_item_id_8,material_item_id_9,material_item_id_10,material_item_id_11,material_item_id_12"); sb.AppendLine("10020001,500000,3,15,700000,700001,700002,700102,700104,700106,700202,700204,,,,"); var csv = sb.ToString(); diff --git a/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs b/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs index 3472e6d6d7..8b0b89b8be 100644 --- a/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs +++ b/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs @@ -215,7 +215,7 @@ public void GetGarageCost() expect: i * 0.16m)) .ToArray(); var expect = favTuples.Select(t => t.expect).Sum() + - fungibleIdAndCountTuples.Select(t => t.expect).Sum(); + fungibleIdAndCountTuples.Select(t => t.expect).Sum(); var favArr = favTuples.Select(t => t.fav).ToArray(); var fungibleIdAndCountArr = fungibleIdAndCountTuples .Select(t => (t.fungibleId, t.count)).ToArray(); diff --git a/.Lib9c.Tests/TableData/Item/EquipmentItemRecipeSheetTest.cs b/.Lib9c.Tests/TableData/Item/EquipmentItemRecipeSheetTest.cs index da8dd7e5ce..9c3642c797 100644 --- a/.Lib9c.Tests/TableData/Item/EquipmentItemRecipeSheetTest.cs +++ b/.Lib9c.Tests/TableData/Item/EquipmentItemRecipeSheetTest.cs @@ -26,7 +26,7 @@ public void Set(string csv, int expected, ItemSubType? expectedItemSubType) Assert.Single(sheet); - EquipmentItemRecipeSheet.Row row = sheet.First!; + var row = sheet.First!; Assert.Equal(expected, row.CRYSTAL); Assert.Equal(expectedItemSubType, row.ItemSubType); diff --git a/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetTest.cs b/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetTest.cs index 5d9f3945e7..2ee11b30f3 100644 --- a/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetTest.cs +++ b/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetTest.cs @@ -5,7 +5,8 @@ public class EquipmentItemSubRecipeSheetTest { - private const string _csv = @"id,required_action_point,required_gold,required_block_index,material_id,material_count,material_2_id,material_2_count,material_3_id,material_3_count,option_id,option_ratio,option_2_id,option_2_ratio,option_3_id,option_3_ratio,option_4_id,option_4_ratio,max_option_limit + private const string _csv = + @"id,required_action_point,required_gold,required_block_index,material_id,material_count,material_2_id,material_2_count,material_3_id,material_3_count,option_id,option_ratio,option_2_id,option_2_ratio,option_3_id,option_3_ratio,option_4_id,option_4_ratio,max_option_limit 1,0,0,0,306040,1,306041,1,306023,1,1,0.74,2,0.2,3,0.06,,,1 2,0,150,0,306040,2,306041,1,306024,1,4,0.46,5,0.35,6,0.11,7,0.08,1"; diff --git a/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetV2Test.cs b/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetV2Test.cs index 06d38d9fe2..5a1140f066 100644 --- a/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetV2Test.cs +++ b/.Lib9c.Tests/TableData/Item/EquipmentItemSubRecipeSheetV2Test.cs @@ -5,7 +5,8 @@ public class EquipmentItemSubRecipeSheetV2Test { - private const string _csv = @"id,required_action_point,required_gold,required_block_index,material_id,material_count,material_2_id,material_2_count,material_3_id,material_3_count,option_id,option_ratio,option_1_required_block_index,option_2_id,option_2_ratio,option_2_required_block_index,option_3_id,option_3_ratio,option_3_required_block_index,option_4_id,option_4_ratio,option_4_required_block_index + private const string _csv = + @"id,required_action_point,required_gold,required_block_index,material_id,material_count,material_2_id,material_2_count,material_3_id,material_3_count,option_id,option_ratio,option_1_required_block_index,option_2_id,option_2_ratio,option_2_required_block_index,option_3_id,option_3_ratio,option_3_required_block_index,option_4_id,option_4_ratio,option_4_required_block_index 1,0,0,0,306040,1,306041,1,306023,1,1,1,0,2,2800,200,3,1800,300,7,1200,600 2,0,450,240,306056,15,306061,8,306068,6,8,1,0,9,3800,200,10,900,300,11,500,600"; diff --git a/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs b/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs index 7b176706a2..6be19aab92 100644 --- a/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs +++ b/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs @@ -18,7 +18,7 @@ public void Set(string csv, int expected) sheet.Set(csv); Assert.Single(sheet); - WorldUnlockSheet.Row row = sheet.First; + var row = sheet.First; Assert.Equal(expected, row!.CRYSTAL); } } diff --git a/.Lib9c.Tests/TableSheets.cs b/.Lib9c.Tests/TableSheets.cs index 14746290eb..4d8a7e38cf 100644 --- a/.Lib9c.Tests/TableSheets.cs +++ b/.Lib9c.Tests/TableSheets.cs @@ -163,11 +163,7 @@ public TableSheets(Dictionary sheets, bool ignoreFailedGetProper public CrystalEquipmentGrindingSheet CrystalEquipmentGrindingSheet { get; private set; } - public CrystalMonsterCollectionMultiplierSheet CrystalMonsterCollectionMultiplierSheet - { - get; - private set; - } + public CrystalMonsterCollectionMultiplierSheet CrystalMonsterCollectionMultiplierSheet { get; private set; } public CrystalMaterialCostSheet CrystalMaterialCostSheet { get; private set; } @@ -193,11 +189,7 @@ public CrystalMonsterCollectionMultiplierSheet CrystalMonsterCollectionMultiplie public EventMaterialItemRecipeSheet EventMaterialItemRecipeSheet { get; private set; } - public StakeActionPointCoefficientSheet StakeActionPointCoefficientSheet - { - get; - private set; - } + public StakeActionPointCoefficientSheet StakeActionPointCoefficientSheet { get; private set; } public WorldBossListSheet WorldBossListSheet { get; private set; } @@ -264,38 +256,22 @@ public StakeActionPointCoefficientSheet StakeActionPointCoefficientSheet public AdventureBossFloorWaveSheet AdventureBossFloorWaveSheet { get; private set; } - public AdventureBossNcgRewardRatioSheet AdventureBossNcgRewardRatioSheet - { - get; - private set; - } + public AdventureBossNcgRewardRatioSheet AdventureBossNcgRewardRatioSheet { get; private set; } - public AdventureBossFloorFirstRewardSheet AdventureBossFloorFirstRewardSheet - { - get; - private set; - } + public AdventureBossFloorFirstRewardSheet AdventureBossFloorFirstRewardSheet { get; private set; } /* Adventure Boss */ // Custom Craft public CustomEquipmentCraftRecipeSheet CustomEquipmentCraftRecipeSheet { get; private set; } - public CustomEquipmentCraftRelationshipSheet CustomEquipmentCraftRelationshipSheet - { - get; - private set; - } + public CustomEquipmentCraftRelationshipSheet CustomEquipmentCraftRelationshipSheet { get; private set; } public CustomEquipmentCraftIconSheet CustomEquipmentCraftIconSheet { get; private set; } public CustomEquipmentCraftOptionSheet CustomEquipmentCraftOptionSheet { get; private set; } - public CustomEquipmentCraftRecipeSkillSheet CustomEquipmentCraftRecipeSkillSheet - { - get; - private set; - } + public CustomEquipmentCraftRecipeSkillSheet CustomEquipmentCraftRecipeSkillSheet { get; private set; } /* Custom Craft */ diff --git a/.Lib9c.Tests/TableSheetsImporter.cs b/.Lib9c.Tests/TableSheetsImporter.cs index 2a3406b619..933e8ec891 100644 --- a/.Lib9c.Tests/TableSheetsImporter.cs +++ b/.Lib9c.Tests/TableSheetsImporter.cs @@ -47,10 +47,13 @@ public static bool TryGetCsv(string sheetName, out string csv) return false; } - private static string GetDefaultPath() => Path - .GetFullPath("../../") - .Replace( - Path.Combine(".Lib9c.Tests", "bin"), - Path.Combine("Lib9c", "TableCSV")); + private static string GetDefaultPath() + { + return Path + .GetFullPath("../../") + .Replace( + Path.Combine(".Lib9c.Tests", "bin"), + Path.Combine("Lib9c", "TableCSV")); + } } } diff --git a/.Lib9c.Tests/TestHelper/BencodexHelper.cs b/.Lib9c.Tests/TestHelper/BencodexHelper.cs index e8145da204..227afac5bb 100644 --- a/.Lib9c.Tests/TestHelper/BencodexHelper.cs +++ b/.Lib9c.Tests/TestHelper/BencodexHelper.cs @@ -10,28 +10,30 @@ namespace Lib9c.Tests.TestHelper public static class BencodexHelper { - public static void ShouldBe(this IValue actual, IValue expected) => + public static void ShouldBe(this IValue actual, IValue expected) + { AssertEquals(expected, actual); + } public static void AssertEquals(IValue expected, IValue actual) { - bool equal = (expected is null && actual is null) || - (expected is Null && actual is Null) || - (expected is Bencodex.Types.Boolean && actual is Bencodex.Types.Boolean && - expected.Equals(actual)) || - (expected is Integer && actual is Integer && expected.Equals(actual)) || - (expected is Binary && actual is Binary && expected.Equals(actual)) || - (expected is Text && actual is Text && expected.Equals(actual)) || - (expected is List && actual is List && expected.Equals(actual)) || - (expected is Dictionary && actual is Dictionary && expected.Equals(actual)); + var equal = (expected is null && actual is null) || + (expected is Null && actual is Null) || + (expected is Bencodex.Types.Boolean && actual is Bencodex.Types.Boolean && + expected.Equals(actual)) || + (expected is Integer && actual is Integer && expected.Equals(actual)) || + (expected is Binary && actual is Binary && expected.Equals(actual)) || + (expected is Text && actual is Text && expected.Equals(actual)) || + (expected is List && actual is List && expected.Equals(actual)) || + (expected is Dictionary && actual is Dictionary && expected.Equals(actual)); if (equal) { return; } - string expectedInspection = expected?.ToString() ?? "(null)"; - string actualInspection = actual?.ToString() ?? "(null)"; - DiffPaneModel diffModel = InlineDiffBuilder.Diff(expectedInspection, actualInspection); + var expectedInspection = expected?.ToString() ?? "(null)"; + var actualInspection = actual?.ToString() ?? "(null)"; + var diffModel = InlineDiffBuilder.Diff(expectedInspection, actualInspection); var prefixes = new Dictionary { [ChangeType.Deleted] = "-", @@ -39,10 +41,10 @@ public static void AssertEquals(IValue expected, IValue actual) [ChangeType.Unchanged] = " ", }; - string diff = string.Join( + var diff = string.Join( Environment.NewLine, diffModel.Lines.Select(line => - (prefixes.TryGetValue(line.Type, out string prefix) ? prefix : " ") + line.Text + (prefixes.TryGetValue(line.Type, out var prefix) ? prefix : " ") + line.Text ) ); throw new XunitException( diff --git a/.Lib9c.Tests/TestHelper/BlockChainHelper.cs b/.Lib9c.Tests/TestHelper/BlockChainHelper.cs index e119d8df0c..663d761e92 100644 --- a/.Lib9c.Tests/TestHelper/BlockChainHelper.cs +++ b/.Lib9c.Tests/TestHelper/BlockChainHelper.cs @@ -34,13 +34,13 @@ public static BlockChain MakeBlockChain( IStore store = null, IStateStore stateStore = null) { - PrivateKey adminPrivateKey = new PrivateKey(); + var adminPrivateKey = new PrivateKey(); policy ??= new BlockPolicy(); stagePolicy ??= new VolatileStagePolicy(); store ??= new DefaultStore(null); stateStore ??= new TrieStateStore(new DefaultKeyValueStore(null)); - Block genesis = MakeGenesisBlock(adminPrivateKey.Address, ImmutableHashSet
.Empty); + var genesis = MakeGenesisBlock(adminPrivateKey.Address, ImmutableHashSet
.Empty); return BlockChain.Create( policy, stagePolicy, @@ -49,10 +49,10 @@ public static BlockChain MakeBlockChain( genesis, new ActionEvaluator( policy.PolicyActionsRegistry, - stateStore: stateStore, - actionTypeLoader: new NCActionLoader() + stateStore, + new NCActionLoader() ), - renderers: blockRenderers); + blockRenderers); } public static Block MakeGenesisBlock( @@ -63,13 +63,13 @@ public static Block MakeGenesisBlock( PendingActivationState[] pendingActivations = null ) { - PrivateKey privateKey = new PrivateKey(); + var privateKey = new PrivateKey(); if (pendingActivations is null) { - var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; - (ActivationKey activationKey, PendingActivationState pendingActivation) = + var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; + (var activationKey, var pendingActivation) = ActivationKey.Create(privateKey, nonce); - pendingActivations = new[] { pendingActivation }; + pendingActivations = new[] { pendingActivation, }; } var sheets = TableSheetsImporter.ImportSheets(); @@ -145,7 +145,7 @@ public static MakeInitialStateResult MakeInitialState() .SetAvatarState(avatarAddress, avatarState) .SetLegacyState(Addresses.Shop, new ShopState().Serialize()) .MintAsset(context, GoldCurrencyState.Address, initCurrencyGold) - .TransferAsset(context, Addresses.GoldCurrency, agentAddress, agentCurrencyGold); + .TransferAsset(context, Addresses.GoldCurrency, agentAddress, agentCurrencyGold); var action = new CreateTestbed { diff --git a/.Lib9c.Tests/Types/BencodexTypesListTest.cs b/.Lib9c.Tests/Types/BencodexTypesListTest.cs index f5de250cb0..a688476d84 100644 --- a/.Lib9c.Tests/Types/BencodexTypesListTest.cs +++ b/.Lib9c.Tests/Types/BencodexTypesListTest.cs @@ -44,7 +44,7 @@ public BencodexTypesListTest() [InlineData(1)] private void DeterministicWhenSerializationWithInteger(int caseIndex) { - Bencodex.Types.List targetList = Bencodex.Types.List.Empty; + var targetList = Bencodex.Types.List.Empty; switch (caseIndex) { case 0: @@ -74,7 +74,7 @@ private void DeterministicWhenSerializationWithInteger(int caseIndex) [InlineData(1)] private void DeterministicWhenSerializationWithAddress(int caseIndex) { - Bencodex.Types.List targetList = Bencodex.Types.List.Empty; + var targetList = Bencodex.Types.List.Empty; switch (caseIndex) { case 0: diff --git a/.Lib9c.Tests/Util/CsvUtil.cs b/.Lib9c.Tests/Util/CsvUtil.cs index 587bb13e23..829236a5d7 100644 --- a/.Lib9c.Tests/Util/CsvUtil.cs +++ b/.Lib9c.Tests/Util/CsvUtil.cs @@ -8,7 +8,7 @@ public static class CsvUtil public static string CsvLinqWhere(string csv, Func where) { var after = csv - .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries) + .Split(new[] { "\r\n", "\r", "\n", }, StringSplitOptions.RemoveEmptyEntries) .Where(where); return string.Join('\n', after); } @@ -16,7 +16,7 @@ public static string CsvLinqWhere(string csv, Func where) public static string CsvLinqSelect(string csv, Func select) { var after = csv - .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries) + .Split(new[] { "\r\n", "\r", "\n", }, StringSplitOptions.RemoveEmptyEntries) .Select(select); return string.Join('\n', after); } diff --git a/.Lib9c.Tests/Util/InitializeUtil.cs b/.Lib9c.Tests/Util/InitializeUtil.cs index 9a53a27021..ef6f934e2c 100644 --- a/.Lib9c.Tests/Util/InitializeUtil.cs +++ b/.Lib9c.Tests/Util/InitializeUtil.cs @@ -1,198 +1,199 @@ -namespace Lib9c.Tests.Util; - -using System; -using System.Collections.Generic; -using System.IO; -using Lib9c.Tests.Action; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Libplanet.Mocks; -using Libplanet.Types.Assets; -using Nekoyume; -using Nekoyume.Action; -using Nekoyume.Model; -using Nekoyume.Model.State; -using Nekoyume.Module; -using Nekoyume.TableData; - -public static class InitializeUtil +namespace Lib9c.Tests.Util { - public static ( - TableSheets tableSheets, - Address agentAddr, - Address avatarAddr, - IWorld world) InitializeStates( - Address? adminAddr = null, - Address? agentAddr = null, - int avatarIndex = 0, - bool isDevEx = false, - Dictionary sheetsOverride = null) - { - adminAddr ??= new PrivateKey().Address; - var context = new ActionContext(); - var world = new World(MockUtil.MockModernWorldState) - .SetLegacyState( - Addresses.Admin, - new AdminState(adminAddr.Value, long.MaxValue).Serialize()); - - var goldCurrency = Currency.Legacy( - "NCG", - 2, - minters: default - ); - var goldCurrencyState = new GoldCurrencyState(goldCurrency); - world = world - .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) - .MintAsset(context, goldCurrencyState.address, goldCurrency * 1_000_000_000); - - var tuple = InitializeTableSheets(world, isDevEx, sheetsOverride); - world = tuple.states; - var tableSheets = new TableSheets(tuple.sheets, ignoreFailedGetProperty: true); - var gameConfigState = new GameConfigState(tuple.sheets[nameof(GameConfigSheet)]); - world = world.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); - - (world, var agentState) = AddAgent(world, agentAddr); - (world, var avatarState, _) = AddAvatar( - world, - tableSheets.GetAvatarSheets(), - agentState.address, - avatarIndex); - return ( - tableSheets, - agentState.address, - avatarState.address, - world); - } - - public static (IWorld world, TableSheets tableSheets) Initialize( - Address? adminAddr = null, - bool isDevEx = false, - Dictionary sheetsOverride = null) + using System; + using System.Collections.Generic; + using System.IO; + using Lib9c.Tests.Action; + using Libplanet.Action.State; + using Libplanet.Crypto; + using Libplanet.Mocks; + using Libplanet.Types.Assets; + using Nekoyume; + using Nekoyume.Action; + using Nekoyume.Model; + using Nekoyume.Model.State; + using Nekoyume.Module; + using Nekoyume.TableData; + + public static class InitializeUtil { - adminAddr ??= new PrivateKey().Address; - var world = new World(MockUtil.MockModernWorldState) - .SetLegacyState( - Addresses.Admin, - new AdminState(adminAddr.Value, long.MaxValue).Serialize()); - var goldCurrency = Currency.Legacy( - "NCG", - 2, - minters: default - ); - var goldCurrencyState = new GoldCurrencyState(goldCurrency); - var gold = goldCurrency * 1_000_000_000; - world = world - .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) - .MintAsset(new ActionContext(), goldCurrencyState.address, gold); - - (world, var sheets) = InitializeTableSheets(world, isDevEx, sheetsOverride); - var tableSheets = new TableSheets(sheets, ignoreFailedGetProperty: true); - var gameConfigState = new GameConfigState(sheets[nameof(GameConfigSheet)]); - world = world.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); - return (world, tableSheets); - } + public static ( + TableSheets tableSheets, + Address agentAddr, + Address avatarAddr, + IWorld world) InitializeStates( + Address? adminAddr = null, + Address? agentAddr = null, + int avatarIndex = 0, + bool isDevEx = false, + Dictionary sheetsOverride = null) + { + adminAddr ??= new PrivateKey().Address; + var context = new ActionContext(); + var world = new World(MockUtil.MockModernWorldState) + .SetLegacyState( + Addresses.Admin, + new AdminState(adminAddr.Value, long.MaxValue).Serialize()); + + var goldCurrency = Currency.Legacy( + "NCG", + 2, + minters: default + ); + var goldCurrencyState = new GoldCurrencyState(goldCurrency); + world = world + .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) + .MintAsset(context, goldCurrencyState.address, goldCurrency * 1_000_000_000); + + var tuple = InitializeTableSheets(world, isDevEx, sheetsOverride); + world = tuple.states; + var tableSheets = new TableSheets(tuple.sheets, true); + var gameConfigState = new GameConfigState(tuple.sheets[nameof(GameConfigSheet)]); + world = world.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); + + (world, var agentState) = AddAgent(world, agentAddr); + (world, var avatarState, _) = AddAvatar( + world, + tableSheets.GetAvatarSheets(), + agentState.address, + avatarIndex); + return ( + tableSheets, + agentState.address, + avatarState.address, + world); + } - public static (IWorld states, Dictionary sheets) - InitializeTableSheets( - IWorld states, + public static (IWorld world, TableSheets tableSheets) Initialize( + Address? adminAddr = null, bool isDevEx = false, Dictionary sheetsOverride = null) - { - var csvPath = isDevEx - ? Path.GetFullPath("../../").Replace( - Path.Combine(".Lib9c.DevExtensions.Tests", "bin"), - Path.Combine("Lib9c", "TableCSV")) - : null; - var sheets = TableSheetsImporter.ImportSheets(csvPath); - if (sheetsOverride != null) { - foreach (var (key, value) in sheetsOverride) - { - sheets[key] = value; - } + adminAddr ??= new PrivateKey().Address; + var world = new World(MockUtil.MockModernWorldState) + .SetLegacyState( + Addresses.Admin, + new AdminState(adminAddr.Value, long.MaxValue).Serialize()); + var goldCurrency = Currency.Legacy( + "NCG", + 2, + minters: default + ); + var goldCurrencyState = new GoldCurrencyState(goldCurrency); + var gold = goldCurrency * 1_000_000_000; + world = world + .SetLegacyState(goldCurrencyState.address, goldCurrencyState.Serialize()) + .MintAsset(new ActionContext(), goldCurrencyState.address, gold); + + (world, var sheets) = InitializeTableSheets(world, isDevEx, sheetsOverride); + var tableSheets = new TableSheets(sheets, true); + var gameConfigState = new GameConfigState(sheets[nameof(GameConfigSheet)]); + world = world.SetLegacyState(gameConfigState.address, gameConfigState.Serialize()); + return (world, tableSheets); } - foreach (var (key, value) in sheets) + public static (IWorld states, Dictionary sheets) + InitializeTableSheets( + IWorld states, + bool isDevEx = false, + Dictionary sheetsOverride = null) { - var address = Addresses.TableSheet.Derive(key); - states = states.SetLegacyState(address, value.Serialize()); - } + var csvPath = isDevEx + ? Path.GetFullPath("../../").Replace( + Path.Combine(".Lib9c.DevExtensions.Tests", "bin"), + Path.Combine("Lib9c", "TableCSV")) + : null; + var sheets = TableSheetsImporter.ImportSheets(csvPath); + if (sheetsOverride != null) + { + foreach (var (key, value) in sheetsOverride) + { + sheets[key] = value; + } + } - return (states, sheets); - } + foreach (var (key, value) in sheets) + { + var address = Addresses.TableSheet.Derive(key); + states = states.SetLegacyState(address, value.Serialize()); + } - public static (IWorld world, AgentState agentState) AddAgent( - IWorld world, - Address? agentAddr = null) - { - agentAddr ??= new PrivateKey().Address; - var agentState = new AgentState(agentAddr.Value); - return (world.SetAgentState(agentAddr.Value, agentState), agentState); - } + return (states, sheets); + } - public static (IWorld world, AvatarState avatarState, int index) AddAvatar( - IWorld world, - AvatarSheets avatarSheets, - Address? agentAddr = null, - int? index = 0, - string name = null, - int? level = 1, - int? clearedStageId = 0) - { - agentAddr ??= new PrivateKey().Address; - var agentState = world.GetAgentState(agentAddr.Value); - if (agentState is null) + public static (IWorld world, AgentState agentState) AddAgent( + IWorld world, + Address? agentAddr = null) { - (world, agentState) = AddAgent(world, agentAddr.Value); + agentAddr ??= new PrivateKey().Address; + var agentState = new AgentState(agentAddr.Value); + return (world.SetAgentState(agentAddr.Value, agentState), agentState); } - if (index is null) + public static (IWorld world, AvatarState avatarState, int index) AddAvatar( + IWorld world, + AvatarSheets avatarSheets, + Address? agentAddr = null, + int? index = 0, + string name = null, + int? level = 1, + int? clearedStageId = 0) { - for (var i = 0; i < GameConfig.SlotCount; i++) + agentAddr ??= new PrivateKey().Address; + var agentState = world.GetAgentState(agentAddr.Value); + if (agentState is null) + { + (world, agentState) = AddAgent(world, agentAddr.Value); + } + + if (index is null) { - if (agentState.avatarAddresses.ContainsKey(i)) + for (var i = 0; i < GameConfig.SlotCount; i++) { - continue; + if (agentState.avatarAddresses.ContainsKey(i)) + { + continue; + } + + index = i; + break; } - index = i; - break; + if (index is null) + { + throw new InvalidOperationException("No available avatar slot."); + } + } + else if (agentState.avatarAddresses.ContainsKey(index.Value)) + { + throw new ArgumentException($"Avatar index {index.Value} is already in use."); } - if (index is null) + var avatarAddr = Addresses.GetAvatarAddress(agentAddr.Value, index.Value); + var avatarState = AvatarState.Create( + avatarAddr, + agentAddr.Value, + 0, + avatarSheets, + avatarAddr.Derive("ranking_map"), + name ?? $"Avatar_{index:D2}"); + avatarState.level = level ?? 1; + if (clearedStageId is not null) { - throw new InvalidOperationException("No available avatar slot."); + var worldSheet = world.GetSheet(); + avatarState.worldInformation = new WorldInformation( + 0, + worldSheet, + GameConfig.RequireClearedStageLevel.ActionsInRankingBoard); } - } - else if (agentState.avatarAddresses.ContainsKey(index.Value)) - { - throw new ArgumentException($"Avatar index {index.Value} is already in use."); + + agentState.avatarAddresses.Add(index.Value, avatarAddr); + return (world.SetAvatarState(avatarAddr, avatarState), avatarState, index.Value); } - var avatarAddr = Addresses.GetAvatarAddress(agentAddr.Value, index.Value); - var avatarState = AvatarState.Create( - avatarAddr, - agentAddr.Value, - 0, - avatarSheets, - avatarAddr.Derive("ranking_map"), - name ?? $"Avatar_{index:D2}"); - avatarState.level = level ?? 1; - if (clearedStageId is not null) + public static IWorld MainAsset(IWorld world, Address recipient, FungibleAssetValue asset) { - var worldSheet = world.GetSheet(); - avatarState.worldInformation = new WorldInformation( - 0, - worldSheet, - GameConfig.RequireClearedStageLevel.ActionsInRankingBoard); + return world.MintAsset(new ActionContext(), recipient, asset); } - - agentState.avatarAddresses.Add(index.Value, avatarAddr); - return (world.SetAvatarState(avatarAddr, avatarState), avatarState, index.Value); - } - - public static IWorld MainAsset(IWorld world, Address recipient, FungibleAssetValue asset) - { - return world.MintAsset(new ActionContext(), recipient, asset); } } From bbf4ec8b210619a046ef1cf888fc30d897c1c5c0 Mon Sep 17 00:00:00 2001 From: eugene-hong <58686228+eugene-doobu@users.noreply.github.com> Date: Tue, 22 Oct 2024 11:21:18 +0900 Subject: [PATCH 2/3] apply code sweep --- .../Action/AccountStateDeltaExtensionsTest.cs | 6 +- .../Action/ActionContextExtensionsTest.cs | 31 +- .Lib9c.Tests/Action/ActionEvaluationTest.cs | 10 +- .Lib9c.Tests/Action/ActivateCollectionTest.cs | 47 +- .Lib9c.Tests/Action/AddRedeemCodeTest.cs | 75 +-- .../ClaimAdventureBossRewardTest.cs | 346 +++++++------- .../AdventureBoss/ExploreAdventureBossTest.cs | 77 ++-- .../AdventureBoss/SweepAdventureBossTest.cs | 65 +-- .../Action/AdventureBoss/UnlockFloorTest.cs | 73 +-- .../Action/AdventureBoss/WantedTest.cs | 221 ++++----- .Lib9c.Tests/Action/ApprovePledgeTest.cs | 35 +- .Lib9c.Tests/Action/BattleArenaTest.cs | 392 +++++++++------- .Lib9c.Tests/Action/BurnAssetTest.cs | 73 +-- .Lib9c.Tests/Action/BuyMultipleTest.cs | 224 ++++----- .Lib9c.Tests/Action/BuyProductTest.cs | 15 +- .Lib9c.Tests/Action/BuyTest.cs | 138 +++--- .../Action/CancelProductRegistrationTest.cs | 31 +- .Lib9c.Tests/Action/ChargeActionPointTest.cs | 28 +- .Lib9c.Tests/Action/ClaimItemsTest.cs | 151 ++++--- .Lib9c.Tests/Action/ClaimRaidRewardTest.cs | 32 +- .Lib9c.Tests/Action/ClaimStakeRewardTest.cs | 174 +++---- .../Action/ClaimWorldBossKillRewardTest.cs | 41 +- .../Action/CombinationConsumableTest.cs | 15 +- .../Action/CombinationEquipmentTest.cs | 77 ++-- .Lib9c.Tests/Action/Common/Doomfist.cs | 36 +- .Lib9c.Tests/Action/Coupons/CouponsFixture.cs | 17 +- .../Action/Coupons/IssueCouponsTest.cs | 132 +++--- .../Action/Coupons/RedeemCouponTest.cs | 3 +- .../Action/Coupons/TransferCouponsTest.cs | 193 ++++---- .Lib9c.Tests/Action/CreateAvatarTest.cs | 86 ++-- .../Action/CreatePendingActivationTest.cs | 26 +- .../Action/CreatePendingActivationsTest.cs | 32 +- .../CustomEquipmentCraftTest.cs | 85 ++-- .Lib9c.Tests/Action/DailyRewardTest.cs | 24 +- .Lib9c.Tests/Action/EndPledgeTest.cs | 24 +- .../Action/EventConsumableItemCraftsTest.cs | 29 +- .Lib9c.Tests/Action/EventDungeonBattleTest.cs | 250 +++++----- .../Action/EventMaterialItemCraftsTest.cs | 44 +- .../Factory/ClaimStakeRewardFactoryTest.cs | 12 +- .../Garages/BulkUnloadFromGaragesTest.cs | 61 +-- .../Garages/DeliverToOthersGaragesTest.cs | 164 +++---- .../Action/Garages/LoadIntoMyGaragesTest.cs | 279 ++++++------ .../Action/Garages/UnloadFromMyGaragesTest.cs | 186 ++++---- .Lib9c.Tests/Action/GoldDistributionTest.cs | 11 +- .Lib9c.Tests/Action/GrindingTest.cs | 44 +- .../Guild/AcceptGuildApplicationTest.cs | 64 +-- .Lib9c.Tests/Action/Guild/ApplyGuildTest.cs | 23 +- .../Action/Guild/BanGuildMemberTest.cs | 116 +++-- .../Guild/CancelGuildApplicationTest.cs | 31 +- .Lib9c.Tests/Action/Guild/MakeGuildTest.cs | 23 +- .../Guild/Migration/GuildMigrationCtrlTest.cs | 45 +- .../Migration/MigratePledgeToGuildTest.cs | 124 ++--- .Lib9c.Tests/Action/Guild/QuitGuildTest.cs | 35 +- .../Guild/RejectGuildApplicationTest.cs | 64 +-- .Lib9c.Tests/Action/Guild/RemoveGuildTest.cs | 46 +- .../Action/Guild/UnbanGuildMemberTest.cs | 35 +- .../Action/HackAndSlashRandomBuffTest.cs | 43 +- .Lib9c.Tests/Action/HackAndSlashSweepTest.cs | 236 +++++----- .Lib9c.Tests/Action/HackAndSlashTest.cs | 427 ++++++++++-------- .Lib9c.Tests/Action/InitializeStatesTest.cs | 113 ++--- .../InvalidTransferSiginerExceptionTest.cs | 45 +- .Lib9c.Tests/Action/IssueTokenTest.cs | 28 +- .../Action/IssueTokensFromGarageTest.cs | 34 +- .Lib9c.Tests/Action/ItemEnhancementTest.cs | 71 +-- .Lib9c.Tests/Action/JoinArena1Test.cs | 164 ++++--- .Lib9c.Tests/Action/JoinArena3Test.cs | 197 ++++---- .Lib9c.Tests/Action/JoinArenaTest.cs | 207 +++++---- .Lib9c.Tests/Action/MigrateFeeTest.cs | 31 +- .../Action/MigrateMonsterCollectionTest.cs | 70 +-- .../MigrationActivatedAccountsStateTest.cs | 13 +- .Lib9c.Tests/Action/MintAssetsTest.cs | 62 +-- .Lib9c.Tests/Action/PatchTableSheetTest.cs | 68 +-- ...ingActivationDoesNotExistsExceptionTest.cs | 15 +- .Lib9c.Tests/Action/PetEnhancement0Test.cs | 175 +++---- .../Action/PrepareRewardAssetsTest.cs | 28 +- .Lib9c.Tests/Action/RaidTest.cs | 62 +-- .Lib9c.Tests/Action/RankingBattleTest.cs | 16 +- .Lib9c.Tests/Action/RapidCombinationTest.cs | 151 ++++--- .Lib9c.Tests/Action/ReRegisterProductTest.cs | 30 +- .Lib9c.Tests/Action/RedeemCodeTest.cs | 56 +-- .Lib9c.Tests/Action/RegisterProduct0Test.cs | 46 +- .Lib9c.Tests/Action/RegisterProductTest.cs | 62 +-- .Lib9c.Tests/Action/RenewAdminStateTest.cs | 89 ++-- .Lib9c.Tests/Action/RequestPledgeTest.cs | 23 +- .../Action/RetrieveAvatarAssetsTest.cs | 46 +- .Lib9c.Tests/Action/RewardGoldTest.cs | 14 +- .Lib9c.Tests/Action/RuneEnhancementTest.cs | 90 ++-- .../Action/Scenario/ArenaScenarioTest.cs | 33 +- .../Action/Scenario/AuraScenarioTest.cs | 101 +++-- .../Action/Scenario/CollectionScenarioTest.cs | 92 ++-- .../Action/Scenario/GrimoireScenarioTest.cs | 101 +++-- .Lib9c.Tests/Action/Scenario/ItemCraftTest.cs | 69 +-- .../Action/Scenario/MarketScenarioTest.cs | 283 ++++++------ .../Action/Scenario/MeadScenarioTest.cs | 11 +- .../AdditionalOptionRateByFixedValueTest.cs | 3 +- .../Action/Scenario/Pet/CommonTest.cs | 32 +- .../Pet/DiscountMaterialCostCrystalTest.cs | 15 +- .../Pet/IncreaseBlockPerHourglassTest.cs | 35 +- .../Scenario/Pet/ReduceRequiredBlockTest.cs | 15 +- .../Action/Scenario/RuneScenarioTest.cs | 63 +-- .../SellAndCancellationAndSellTest.cs | 79 ++-- .../Scenario/StakeAndClaimScenarioTest.cs | 39 +- .../Scenario/WorldUnlockScenarioTest.cs | 48 +- .Lib9c.Tests/Action/SecureMiningRewardTest.cs | 17 +- .Lib9c.Tests/Action/Stake2Test.cs | 199 ++++---- .Lib9c.Tests/Action/StakeTest.cs | 165 +++---- .Lib9c.Tests/Action/Summon/AuraSummonTest.cs | 24 +- .Lib9c.Tests/Action/Summon/RuneSummonTest.cs | 19 +- .Lib9c.Tests/Action/TransferAssetTest.cs | 232 +++++----- .Lib9c.Tests/Action/TransferAssetsTest.cs | 263 ++++++----- .../Action/UnlockEquipmentRecipeTest.cs | 32 +- .Lib9c.Tests/Action/UnlockRuneSlotTest.cs | 72 +-- .Lib9c.Tests/Action/UnlockWorldTest.cs | 42 +- .../Action/ValidatorSetOperateTest.cs | 86 ++-- .Lib9c.Tests/CrystalCalculatorTest.cs | 7 +- .Lib9c.Tests/CurrenciesTest.cs | 12 +- .../Extensions/BencodexTypesExtensionsTest.cs | 5 +- .../Extensions/EquipmentExtensionsTest.cs | 9 +- .../Extensions/EventDungeonExtensionsTest.cs | 5 +- .../Extensions/EventScheduleExtensionsTest.cs | 108 ++--- .../Extensions/SheetsExtensionsTest.cs | 9 +- .../Helper/AdventureBossHelperTest.cs | 15 +- .../Helper/InventoryExtensionsTest.cs | 8 +- .Lib9c.Tests/Helper/PetHelperTest.cs | 53 ++- .Lib9c.Tests/JsonStatesLoaderTest.cs | 9 +- .Lib9c.Tests/Model/ActivationKeyTest.cs | 2 +- .../AdventureBossSimulatorTest.cs | 5 +- .Lib9c.Tests/Model/ArenaSimulatorTest.cs | 29 +- .../Model/Event/EventDungeonInfoTest.cs | 41 +- .../Model/Garages/FungibleItemGarageTest.cs | 45 +- .Lib9c.Tests/Model/Item/ArmorTest.cs | 5 +- .Lib9c.Tests/Model/Item/BeltTest.cs | 5 +- .Lib9c.Tests/Model/Item/EquipmentTest.cs | 3 +- .Lib9c.Tests/Model/Item/NecklaceTest.cs | 5 +- .Lib9c.Tests/Model/Item/ShopItemTest.cs | 15 +- .../Model/Mail/CustomCraftMailTest.cs | 5 +- .../UnloadFromMyGaragesRecipientMailTest.cs | 23 +- .Lib9c.Tests/Model/Order/OrderBaseTest.cs | 4 +- .Lib9c.Tests/Model/Order/OrderFactoryTest.cs | 5 +- .Lib9c.Tests/Model/PlayerTest.cs | 46 +- .Lib9c.Tests/Model/QuestListTest.cs | 30 +- .Lib9c.Tests/Model/QuestRewardTest.cs | 11 +- .Lib9c.Tests/Model/SimulatorTest.cs | 76 ++-- .../Skill/Adventure/ShatterStrikeTest.cs | 22 +- .../Model/Skill/Arena/ArenaCombatTest.cs | 20 +- .../Skill/Arena/ArenaNormalAttackTest.cs | 10 +- .Lib9c.Tests/Model/StageSimulatorTest.cs | 7 +- .Lib9c.Tests/Model/Stake/ContractTest.cs | 22 +- .../Model/Stake/StakeStateUtilsTest.cs | 5 +- .Lib9c.Tests/Model/Stake/StakeStateV2Test.cs | 10 +- .Lib9c.Tests/Model/State/AvatarStateTest.cs | 5 +- .Lib9c.Tests/Model/State/PetStateTest.cs | 5 +- .Lib9c.Tests/Model/State/RankingState1Test.cs | 34 +- .Lib9c.Tests/Model/State/RankingStateTest.cs | 34 +- .Lib9c.Tests/Model/State/ShopStateTest.cs | 71 +-- .Lib9c.Tests/Model/State/StakeStateTest.cs | 30 +- .../Model/State/WeeklyArenaStateTest.cs | 16 +- .Lib9c.Tests/Policy/BlockPolicyTest.cs | 65 +-- .Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs | 25 +- .Lib9c.Tests/Policy/SpannedSubPolicyTest.cs | 51 ++- .../Tx/Begin/AutoJoinGuildTest.cs | 70 +-- .Lib9c.Tests/SerializeKeysTest.cs | 3 +- ...dventureBossContributionRewardSheetTest.cs | 12 +- .../AdventureBossWantedRewardSheetTest.cs | 12 +- .Lib9c.Tests/TableData/ArenaSheetTest.cs | 10 +- .../Crystal/CrystalMaterialCostSheetTest.cs | 3 +- .../Crystal/CrystalRandomBuffSheetTest.cs | 3 +- .../Crystal/CrystalStageBuffGachaSheetTest.cs | 3 +- .../Garages/LoadIntoMyGaragesCostSheetTest.cs | 18 +- .../TableData/Stake/StakePolicySheetTest.cs | 5 +- .../WorldAndStage/WorldUnlockSheetTest.cs | 6 +- .../TableData/WorldBossListSheetTest.cs | 5 +- .Lib9c.Tests/TestHelper/BencodexHelper.cs | 5 +- .Lib9c.Tests/TestHelper/BlockChainHelper.cs | 15 +- .Lib9c.Tests/Types/BencodexTypesListTest.cs | 26 +- 175 files changed, 6030 insertions(+), 4796 deletions(-) diff --git a/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs b/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs index 567526bf55..c7b501a204 100644 --- a/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs +++ b/.Lib9c.Tests/Action/AccountStateDeltaExtensionsTest.cs @@ -67,11 +67,13 @@ public void SetWorldBossKillReward(int level, int expectedRune, int expectedCrys ); var bossId = bossState.Id; var runeWeightSheet = new RuneWeightSheet(); - runeWeightSheet.Set($@"id,boss_id,rank,rune_id,weight + runeWeightSheet.Set( + $@"id,boss_id,rank,rune_id,weight 1,{bossId},0,10001,100 "); var killRewardSheet = new WorldBossKillRewardSheet(); - killRewardSheet.Set($@"id,boss_id,rank,rune_min,rune_max,crystal,circle + killRewardSheet.Set( + $@"id,boss_id,rank,rune_min,rune_max,crystal,circle 1,{bossId},0,1,1,100,0 "); diff --git a/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs b/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs index 0808e021e5..cd2c558186 100644 --- a/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs +++ b/.Lib9c.Tests/Action/ActionContextExtensionsTest.cs @@ -156,20 +156,23 @@ public void IsMainNet(GoldCurrencyState goldCurrencyState, bool expected) [Fact] public void Since() { - Assert.True(new ActionContext - { - BlockIndex = 1001, - }.Since(1000)); - - Assert.True(new ActionContext - { - BlockIndex = 0, - }.Since(0)); - - Assert.False(new ActionContext - { - BlockIndex = 0, - }.Since(1)); + Assert.True( + new ActionContext + { + BlockIndex = 1001, + }.Since(1000)); + + Assert.True( + new ActionContext + { + BlockIndex = 0, + }.Since(0)); + + Assert.False( + new ActionContext + { + BlockIndex = 0, + }.Since(1)); } } } diff --git a/.Lib9c.Tests/Action/ActionEvaluationTest.cs b/.Lib9c.Tests/Action/ActionEvaluationTest.cs index ad019ed82b..8d48facb8b 100644 --- a/.Lib9c.Tests/Action/ActionEvaluationTest.cs +++ b/.Lib9c.Tests/Action/ActionEvaluationTest.cs @@ -440,10 +440,12 @@ private ActionBase GetAction(Type type) AgentAddresses = new[] { (new PrivateKey().Address, new PrivateKey().Address), }, Mead = 4, }, - TransferAssets _ => new TransferAssets(_sender, new List<(Address, FungibleAssetValue)> - { - (_signer, 1 * _currency), - }), + TransferAssets _ => new TransferAssets( + _sender, + new List<(Address, FungibleAssetValue)> + { + (_signer, 1 * _currency), + }), RuneSummon _ => new RuneSummon { AvatarAddress = _sender, diff --git a/.Lib9c.Tests/Action/ActivateCollectionTest.cs b/.Lib9c.Tests/Action/ActivateCollectionTest.cs index 54ce33e927..73daf26892 100644 --- a/.Lib9c.Tests/Action/ActivateCollectionTest.cs +++ b/.Lib9c.Tests/Action/ActivateCollectionTest.cs @@ -77,11 +77,12 @@ public void Execute() { var item = ItemFactory.CreateItem(itemRow, random); avatarState.inventory.AddItem(item, material.Count); - materials.Add(new FungibleCollectionMaterial - { - ItemId = item.Id, - ItemCount = material.Count, - }); + materials.Add( + new FungibleCollectionMaterial + { + ItemId = item.Id, + ItemCount = material.Count, + }); } else { @@ -92,23 +93,25 @@ public void Execute() avatarState.inventory.AddItem(item); if (item.ItemType != ItemType.Consumable) { - materials.Add(new NonFungibleCollectionMaterial - { - ItemId = item.Id, - NonFungibleId = nonFungibleId, - SkillContains = material.SkillContains, - }); + materials.Add( + new NonFungibleCollectionMaterial + { + ItemId = item.Id, + NonFungibleId = nonFungibleId, + SkillContains = material.SkillContains, + }); } else { // Add consumable material only one. if (i == 0) { - materials.Add(new FungibleCollectionMaterial - { - ItemId = item.Id, - ItemCount = material.Count, - }); + materials.Add( + new FungibleCollectionMaterial + { + ItemId = item.Id, + ItemCount = material.Count, + }); } } } @@ -137,11 +140,13 @@ public void Execute() var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.Empty(nextAvatarState.inventory.Items); - Assert.Throws(() => activateCollection.Execute(new ActionContext - { - PreviousState = nextState, - Signer = _agentAddress, - })); + Assert.Throws( + () => activateCollection.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = _agentAddress, + })); } } } diff --git a/.Lib9c.Tests/Action/AddRedeemCodeTest.cs b/.Lib9c.Tests/Action/AddRedeemCodeTest.cs index 4487362445..b8cdf34347 100644 --- a/.Lib9c.Tests/Action/AddRedeemCodeTest.cs +++ b/.Lib9c.Tests/Action/AddRedeemCodeTest.cs @@ -24,30 +24,32 @@ public void CheckPermission() redeemCsv = "New Value", }; - var exc1 = Assert.Throws(() => - { - action.Execute( - new ActionContext - { - BlockIndex = 101, - PreviousState = state, - Signer = adminAddress, - } - ); - }); + var exc1 = Assert.Throws( + () => + { + action.Execute( + new ActionContext + { + BlockIndex = 101, + PreviousState = state, + Signer = adminAddress, + } + ); + }); Assert.Equal(101, exc1.BlockIndex); - var exc2 = Assert.Throws(() => - { - action.Execute( - new ActionContext - { - BlockIndex = 5, - PreviousState = state, - Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), - } - ); - }); + var exc2 = Assert.Throws( + () => + { + action.Execute( + new ActionContext + { + BlockIndex = 5, + PreviousState = state, + Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), + } + ); + }); Assert.Equal(new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), exc2.Signer); } @@ -64,14 +66,15 @@ public void Execute() redeemCsv = csv, }; - var nextState = action.Execute(new ActionContext - { - Signer = adminAddress, - BlockIndex = 0, - PreviousState = new World(MockUtil.MockModernWorldState) - .SetLegacyState(Addresses.Admin, adminState.Serialize()) - .SetLegacyState(Addresses.RedeemCode, new RedeemCodeState(new RedeemCodeListSheet()).Serialize()), - }); + var nextState = action.Execute( + new ActionContext + { + Signer = adminAddress, + BlockIndex = 0, + PreviousState = new World(MockUtil.MockModernWorldState) + .SetLegacyState(Addresses.Admin, adminState.Serialize()) + .SetLegacyState(Addresses.RedeemCode, new RedeemCodeState(new RedeemCodeListSheet()).Serialize()), + }); var sheet = new RedeemCodeListSheet(); sheet.Set(csv); @@ -98,11 +101,13 @@ public void ExecuteThrowSheetRowValidateException() redeemCsv = csv, }; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = 0, - PreviousState = state, - }) + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = 0, + PreviousState = state, + }) ); } } diff --git a/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs b/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs index 04ae818cb6..9e2786f007 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/ClaimAdventureBossRewardTest.cs @@ -394,13 +394,14 @@ AdventureBossGameData.ClaimableReward expectedReward Season = 1, AvatarAddress = TesterAvatarAddress, Bounty = bounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 0L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 0L, + RandomSeed = seed, + }); if (anotherWanted) { @@ -410,13 +411,14 @@ AdventureBossGameData.ClaimableReward expectedReward Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = anotherBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = 1L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = 1L, + RandomSeed = seed, + }); } // Burn all remaining NCG to make test easier @@ -430,16 +432,18 @@ AdventureBossGameData.ClaimableReward expectedReward var resultState = new ClaimAdventureBossReward { AvatarAddress = TesterAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex + 1, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex + 1, + RandomSeed = seed, + }); - Assert.True(resultState.GetBountyBoard(1).Investors - .First(inv => inv.AvatarAddress == TesterAvatarAddress).Claimed); + Assert.True( + resultState.GetBountyBoard(1).Investors + .First(inv => inv.AvatarAddress == TesterAvatarAddress).Claimed); Test(resultState, expectedReward); } @@ -480,37 +484,40 @@ public void WantedMultipleSeason() Season = 1, AvatarAddress = TesterAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); state = new Wanted { Season = 2, AvatarAddress = WantedAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); state = new Wanted { Season = 3, AvatarAddress = TesterAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); // Burn remaining NCG state = state.BurnAsset( @@ -523,13 +530,14 @@ public void WantedMultipleSeason() var resultState = new ClaimAdventureBossReward { AvatarAddress = TesterAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed + 3, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed + 3, + }); for (var szn = 3; szn > 0; szn--) { @@ -572,13 +580,14 @@ FungibleAssetValue expectedRemainingNcg Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = bounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = 0L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = 0L, + RandomSeed = seed, + }); // Explore : just add data to avoid explore reward // Manipulate point to calculate reward above zero @@ -612,13 +621,14 @@ FungibleAssetValue expectedRemainingNcg Equipments = new List(), Foods = new List(), RuneInfos = new List(), - }.Execute(new ActionContext - { - PreviousState = state, - Signer = ExplorerAddress, - BlockIndex = 1L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = ExplorerAddress, + BlockIndex = 1L, + RandomSeed = seed, + }); board = state.GetExploreBoard(1); board.UsedApPotion += 99; @@ -645,13 +655,14 @@ FungibleAssetValue expectedRemainingNcg var resultState = new ClaimAdventureBossReward { AvatarAddress = TesterAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed, + }); // Test var exploreBoard = resultState.GetExploreBoard(1); @@ -681,13 +692,14 @@ FungibleAssetValue expectedRemainingNcg resultState = new ClaimAdventureBossReward { AvatarAddress = ExplorerAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = resultState, - Signer = ExplorerAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex + 1, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = resultState, + Signer = ExplorerAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex + 1, + RandomSeed = seed, + }); Assert.Equal( 0 * NCG, @@ -747,13 +759,14 @@ public void ExploreMultipleSeason() Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); // Manipulate point to calculate reward above zero var board = state.GetExploreBoard(1); @@ -775,26 +788,28 @@ public void ExploreMultipleSeason() AvatarAddress = ExplorerAvatarAddress, // To avoid wanted for two seasons in a row error Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = ExplorerAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = ExplorerAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); state = new Wanted { Season = 3, AvatarAddress = WantedAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); // Manipulate point to calculate reward above zero board = state.GetExploreBoard(3); @@ -819,13 +834,14 @@ public void ExploreMultipleSeason() var resultState = new ClaimAdventureBossReward { AvatarAddress = TesterAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed + 3, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed + 3, + }); for (var szn = 3; szn > 0; szn--) { @@ -873,13 +889,14 @@ public void AllReward() Season = 1, AvatarAddress = TesterAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 0L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 0L, + RandomSeed = seed, + }); // Explore : just add data to avoid explore reward // Manipulate point to calculate reward above zero @@ -906,13 +923,14 @@ public void AllReward() var resultState = new ClaimAdventureBossReward { AvatarAddress = TesterAvatarAddress, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed, + }); Test(resultState, expectedReward); } @@ -944,13 +962,14 @@ Type exc Season = 1, AvatarAddress = wanted ? TesterAvatarAddress : WantedAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = wanted ? TesterAddress : WantedAddress, - BlockIndex = 0L, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = wanted ? TesterAddress : WantedAddress, + BlockIndex = 0L, + RandomSeed = seed, + }); // Explore : just add data to avoid explore reward // Manipulate point to calculate reward above zero @@ -958,12 +977,15 @@ Type exc var lst = state.GetExplorerList(1); board.TotalPoint += 100; board.UsedApPotion += 100; - lst.Explorers.Add(explore - ? (TesterAvatarAddress, TesterAvatarState.name) - : (ExplorerAvatarAddress, ExplorerAvatarState.name)); + lst.Explorers.Add( + explore + ? (TesterAvatarAddress, TesterAvatarState.name) + : (ExplorerAvatarAddress, ExplorerAvatarState.name)); var exp = state.TryGetExplorer( - 1, explore ? TesterAvatarAddress : ExplorerAvatarAddress, out var e + 1, + explore ? TesterAvatarAddress : ExplorerAvatarAddress, + out var e ) ? e : new Explorer( @@ -981,13 +1003,14 @@ Type exc Season = 2, AvatarAddress = ExplorerAvatarAddress, Bounty = 100 * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = ExplorerAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - RandomSeed = seed, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = ExplorerAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + RandomSeed = seed, + }); // Burn state = state.BurnAsset( @@ -1003,24 +1026,28 @@ Type exc }; if (exc is null) { - var resultState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed + 2, - }); + var resultState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed + 2, + }); Test(resultState, expectedReward); } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, - RandomSeed = seed + 2, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = state.GetLatestAdventureBossSeason().EndBlockIndex, + RandomSeed = seed + 2, + })); } } @@ -1032,12 +1059,13 @@ public void StressTest() private IWorld Stake(IWorld world, Address agentAddress) { var action = new Stake(new BigInteger(500_000)); - var state = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - BlockIndex = 0L, - }); + var state = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + BlockIndex = 0L, + }); _runeSheet = state.GetSheet(); return state; } diff --git a/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs b/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs index 6508ade694..c742acc4fd 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/ExploreAdventureBossTest.cs @@ -170,11 +170,12 @@ Type exc ); state = Stake(state, WantedAddress); - var sheets = state.GetSheets(new[] - { - typeof(MaterialItemSheet), - typeof(RuneSheet), - }); + var sheets = state.GetSheets( + new[] + { + typeof(MaterialItemSheet), + typeof(RuneSheet), + }); var materialSheet = sheets.GetSheet(); var materialRow = materialSheet.OrderedList.First(row => row.ItemSubType == ItemSubType.ApStone); @@ -193,13 +194,14 @@ Type exc Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = gameConfigState.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = 0L, - RandomSeed = 1, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = 0L, + RandomSeed = 1, + }); var exp = new Explorer(TesterAvatarAddress, TesterAvatarState.name) { MaxFloor = maxFloor, @@ -226,8 +228,9 @@ Type exc var expectedItemRewards = new List<(int, int)>(); var expectedFavRewards = new List<(int, int)>(); var firstRewardSheet = TableSheets.AdventureBossFloorFirstRewardSheet; - foreach (var row in firstRewardSheet.Values.Where(r => - r.FloorId > floor && r.FloorId <= expectedFloor)) + foreach (var row in firstRewardSheet.Values.Where( + r => + r.FloorId > floor && r.FloorId <= expectedFloor)) { foreach (var reward in row.Rewards) { @@ -258,22 +261,26 @@ Type exc if (exc is not null) { - Assert.Throws(exc, () => action.Execute(new ActionContext + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 1L, + } + )); + } + else + { + state = action.Execute( + new ActionContext { PreviousState = state, Signer = TesterAddress, BlockIndex = 1L, - } - )); - } - else - { - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 1L, - }); + }); var potion = state.GetInventoryV2(TesterAvatarAddress).Items .FirstOrDefault(i => i.item.ItemSubType == ItemSubType.ApStone); @@ -305,7 +312,10 @@ Type exc { var itemCount = inventory.TryGetTradableFungibleItems( - circleRow.ItemId, null, 1L, out var items + circleRow.ItemId, + null, + 1L, + out var items ) ? items.Sum(item => item.count) : 0; @@ -337,12 +347,13 @@ Type exc private IWorld Stake(IWorld world, Address agentAddress) { var action = new Stake(new BigInteger(500_000)); - var state = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - BlockIndex = 0L, - }); + var state = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + BlockIndex = 0L, + }); return state; } } diff --git a/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs b/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs index 80b6f3e82d..3021ca8bf8 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/SweepAdventureBossTest.cs @@ -131,10 +131,11 @@ public void Execute( } state = Stake(state, WantedAddress); - var sheets = state.GetSheets(new[] - { - typeof(MaterialItemSheet), - }); + var sheets = state.GetSheets( + new[] + { + typeof(MaterialItemSheet), + }); var materialSheet = sheets.GetSheet(); var materialRow = materialSheet.OrderedList.First(row => row.ItemSubType == ItemSubType.ApStone); @@ -150,13 +151,14 @@ public void Execute( Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = gameConfigState.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = 0L, - RandomSeed = 1, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = 0L, + RandomSeed = 1, + }); var exp = new Explorer(TesterAvatarAddress, TesterAvatarState.name) { MaxFloor = 5 * Math.Max(floor / 5, 1), @@ -176,22 +178,26 @@ public void Execute( if (exc is not null) { - Assert.Throws(exc, () => action.Execute(new ActionContext + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 1L, + } + )); + } + else + { + state = action.Execute( + new ActionContext { PreviousState = state, Signer = TesterAddress, BlockIndex = 1L, - } - )); - } - else - { - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 1L, - }); + }); var potion = state.GetInventoryV2(TesterAvatarAddress).Items .FirstOrDefault(i => i.item.ItemSubType == ItemSubType.ApStone); @@ -242,12 +248,13 @@ public void Execute( private IWorld Stake(IWorld world, Address agentAddress) { var action = new Stake(new BigInteger(500_000)); - var state = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - BlockIndex = 0L, - }); + var state = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + BlockIndex = 0L, + }); return state; } } diff --git a/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs b/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs index 675da8368a..7725b5b4ff 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/UnlockFloorTest.cs @@ -96,7 +96,11 @@ public class UnlockFloorTest [InlineData(false, true, 5, 5, typeof(NotEnoughMaterialException))] [InlineData(true, true, 5, 5, typeof(InsufficientBalanceException))] public void Execute( - bool useNcg, bool notEnough, int startFloor, int expectedFloor, Type exc + bool useNcg, + bool notEnough, + int startFloor, + int expectedFloor, + Type exc ) { // Settings @@ -139,13 +143,14 @@ public void Execute( Season = 1, AvatarAddress = WantedAvatarAddress, Bounty = gameConfigState.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = WantedAddress, - BlockIndex = 0L, - RandomSeed = 1, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = WantedAddress, + BlockIndex = 0L, + RandomSeed = 1, + }); // Explore state = new ExploreAdventureBoss @@ -156,12 +161,13 @@ public void Execute( Equipments = new List(), Foods = new List(), RuneInfos = new List(), - }.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 1L, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 1L, + }); // Make all floors cleared var explorer = state.GetExplorer(1, TesterAvatarAddress); @@ -181,22 +187,24 @@ public void Execute( { Assert.Throws( exc, - () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 2L, - }) + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 2L, + }) ); } else { - var resultState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = TesterAddress, - BlockIndex = 2L, - }); + var resultState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = TesterAddress, + BlockIndex = 2L, + }); Assert.Equal(0 * NCG, resultState.GetBalance(TesterAddress, NCG)); if (!useNcg) @@ -215,12 +223,13 @@ public void Execute( private IWorld Stake(IWorld world, Address agentAddress) { var action = new Stake(new BigInteger(500_000)); - var state = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - BlockIndex = 0L, - }); + var state = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + BlockIndex = 0L, + }); return state; } } diff --git a/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs b/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs index 82a78d5e86..3dce3cbebe 100644 --- a/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs +++ b/.Lib9c.Tests/Action/AdventureBoss/WantedTest.cs @@ -92,13 +92,14 @@ public void Execute() AvatarAddress = AvatarAddress, Bounty = minBounty * NCG, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 0L, - RandomSeed = 1, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 0L, + RandomSeed = 1, + }); // Test var season = nextState.GetSeasonInfo(1); @@ -129,13 +130,14 @@ public void Execute() // Add new bounty action.AvatarAddress = AvatarAddress2; - nextState = action.Execute(new ActionContext - { - PreviousState = nextState, - Signer = AgentAddress, - BlockIndex = 1L, - RandomSeed = 1, - }); + nextState = action.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = AgentAddress, + BlockIndex = 1L, + RandomSeed = 1, + }); Assert.Equal( startBalance - minBounty * 2 * NCG, @@ -167,12 +169,13 @@ public void Execute() // Add additional bounty action.AvatarAddress = AvatarAddress; - nextState = action.Execute(new ActionContext - { - PreviousState = nextState, - Signer = AgentAddress, - BlockIndex = 2L, - }); + nextState = action.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = AgentAddress, + BlockIndex = 2L, + }); Assert.Equal( startBalance - minBounty * 3 * NCG, @@ -210,13 +213,14 @@ public void CreateNewSeason() AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 0L, - RandomSeed = 1, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 0L, + RandomSeed = 1, + }); // Validate new season latestSeasonInfo = nextState.GetLatestAdventureBossSeason(); @@ -265,14 +269,15 @@ public void SeasonAlreadyInProgress() AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, }; - Assert.Throws(() => action.Execute( - new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 100L, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 100L, + } + )); } [Theory] @@ -303,14 +308,16 @@ public void CannotCreatePastSeason(int currentSeason, int targetSeason) Bounty = gameConfig.AdventureBossMinBounty * NCG, }; - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 0L, - } - ) + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 0L, + } + ) ); } @@ -339,13 +346,15 @@ public void CannotCreateFutureSeason(int latestSeason, int targetSeason) AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, }; - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, - }) + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = state.GetLatestAdventureBossSeason().NextStartBlockIndex, + }) ); } @@ -377,23 +386,25 @@ public void InsufficientStaking(int staking, bool err) if (err) { - Assert.Throws(() => action.Execute( + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 100L, + } + )); + } + else + { + action.Execute( new ActionContext { PreviousState = state, Signer = AgentAddress, BlockIndex = 100L, - } - )); - } - else - { - action.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 100L, - }); + }); } } @@ -417,14 +428,15 @@ public void InsufficientBalance() AvatarAddress = AvatarAddress, Bounty = minBounty * NCG, }; - Assert.Throws(() => action.Execute( - new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 100L, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 100L, + } + )); } [Fact] @@ -439,14 +451,15 @@ public void InvalidBounty() AvatarAddress = AvatarAddress, Bounty = bounty * NCG, }; - Assert.Throws(() => action.Execute( - new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 100L, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 100L, + } + )); } [Fact] @@ -460,12 +473,13 @@ public void WantedForMultipleSeasons() Season = 1, AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = 0L, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = 0L, + }); var prevSeason = state.GetSeasonInfo(1); state = new Wanted @@ -473,12 +487,13 @@ public void WantedForMultipleSeasons() Season = 2, AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = prevSeason.NextStartBlockIndex, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = prevSeason.NextStartBlockIndex, + }); var requiredStakingLevel = state.GetGameConfigState().AdventureBossWantedRequiredStakingLevel; @@ -537,12 +552,13 @@ public void PrevSeason(int[] prevBossId, int[] candidate) Season = 3, AvatarAddress = AvatarAddress, Bounty = gameConfig.AdventureBossMinBounty * NCG, - }.Execute(new ActionContext - { - PreviousState = state, - Signer = AgentAddress, - BlockIndex = prevSeason.NextStartBlockIndex, - }); + }.Execute( + new ActionContext + { + PreviousState = state, + Signer = AgentAddress, + BlockIndex = prevSeason.NextStartBlockIndex, + }); var latestSeason = state.GetLatestAdventureBossSeason(); Assert.Contains(latestSeason.BossId, candidate); @@ -575,12 +591,13 @@ private IWorld Stake(IWorld world, long amount = 0) } var action = new Stake(new BigInteger(amount)); - return action.Execute(new ActionContext - { - PreviousState = world, - Signer = AgentAddress, - BlockIndex = 0L, - }); + return action.Execute( + new ActionContext + { + PreviousState = world, + Signer = AgentAddress, + BlockIndex = 0L, + }); } } } diff --git a/.Lib9c.Tests/Action/ApprovePledgeTest.cs b/.Lib9c.Tests/Action/ApprovePledgeTest.cs index e93d530af8..54909bbc14 100644 --- a/.Lib9c.Tests/Action/ApprovePledgeTest.cs +++ b/.Lib9c.Tests/Action/ApprovePledgeTest.cs @@ -35,11 +35,12 @@ public void Execute(int mead) { PatronAddress = patron, }; - var nextState = action.Execute(new ActionContext - { - Signer = address, - PreviousState = states, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = address, + PreviousState = states, + }); var contract = Assert.IsType(nextState.GetLegacyState(contractAddress)); Assert.Equal(patron, contract[0].ToAddress()); @@ -68,11 +69,12 @@ public void Execute_JoinGuild(int mead) { PatronAddress = patron, }; - var nextState = action.Execute(new ActionContext - { - Signer = address, - PreviousState = states, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = address, + PreviousState = states, + }); var contract = Assert.IsType(nextState.GetLegacyState(contractAddress)); Assert.Equal(patron, contract[0].ToAddress()); @@ -109,11 +111,14 @@ public void Execute_Throw_Exception(bool invalidPatron, bool alreadyContract, Ty { PatronAddress = patron, }; - Assert.Throws(exc, () => action.Execute(new ActionContext - { - Signer = address, - PreviousState = states, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + Signer = address, + PreviousState = states, + })); } } } diff --git a/.Lib9c.Tests/Action/BattleArenaTest.cs b/.Lib9c.Tests/Action/BattleArenaTest.cs index 48b4eaf0b9..d427263f8e 100644 --- a/.Lib9c.Tests/Action/BattleArenaTest.cs +++ b/.Lib9c.Tests/Action/BattleArenaTest.cs @@ -192,12 +192,14 @@ public void Execute_InvalidAddressException() runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -210,7 +212,9 @@ public void Execute_MedalIdNotFoundException() Signer = _agent1Address, RandomSeed = 0, }; - prevState = prevState.SetLegacyState(Addresses.TableSheet.Derive("ArenaSheet"), @"id,round,arena_type,start_block_index,end_block_index,required_medal_count,entrance_fee,ticket_price,additional_ticket_price,max_purchase_count,max_purchase_count_during_interval,medal_id + prevState = prevState.SetLegacyState( + Addresses.TableSheet.Derive("ArenaSheet"), + @"id,round,arena_type,start_block_index,end_block_index,required_medal_count,entrance_fee,ticket_price,additional_ticket_price,max_purchase_count,max_purchase_count_during_interval,medal_id 1,1,Season,1,100,0,0,5,2,80,79".Serialize()); prevState = JoinArena( context, @@ -242,13 +246,15 @@ public void Execute_MedalIdNotFoundException() equipments = new List(), runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = prevState, - Signer = _agent1Address, - RandomSeed = 0, - BlockIndex = 10, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = prevState, + Signer = _agent1Address, + RandomSeed = 0, + BlockIndex = 10, + })); } [Fact] @@ -266,12 +272,14 @@ public void Execute_FailedLoadStateException() runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -289,12 +297,14 @@ public void Execute_SheetRowNotFoundException() runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -312,13 +322,15 @@ public void Execute_ThisArenaIsClosedException() runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialStates, - Signer = _agent1Address, - RandomSeed = 0, - BlockIndex = 4480001, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialStates, + Signer = _agent1Address, + RandomSeed = 0, + BlockIndex = 4480001, + })); } [Fact] @@ -336,13 +348,15 @@ public void Execute_ArenaParticipantsNotFoundException() runeInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialStates, - Signer = _agent1Address, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialStates, + Signer = _agent1Address, + RandomSeed = 0, + BlockIndex = 1, + })); } [Theory] @@ -354,9 +368,10 @@ public void Execute_AddressNotFoundInArenaParticipantsException(bool excludeMe) const int round = 1; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -397,14 +412,16 @@ public void Execute_AddressNotFoundInArenaParticipantsException(bool excludeMe) runeInfos = new List(), }; - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + BlockIndex = 1, + })); } [Theory] @@ -416,9 +433,10 @@ public void Execute_ValidateScoreDifferenceException(bool isSigner) const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -449,7 +467,8 @@ public void Execute_ValidateScoreDifferenceException(bool isSigner) var arenaScoreAdr = ArenaScore.DeriveAddress( isSigner ? _avatar1Address - : _avatar2Address, roundData.ChampionshipId, + : _avatar2Address, + roundData.ChampionshipId, roundData.Round); previousStates.TryGetArenaScore(arenaScoreAdr, out var arenaScore); arenaScore.AddScore(900); @@ -468,13 +487,15 @@ public void Execute_ValidateScoreDifferenceException(bool isSigner) }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -484,9 +505,10 @@ public void Execute_InsufficientBalanceException() const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -537,13 +559,15 @@ public void Execute_InsufficientBalanceException() }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -553,9 +577,10 @@ public void Execute_ExceedPlayCountException() const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -603,13 +628,15 @@ public void Execute_ExceedPlayCountException() }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -619,9 +646,10 @@ public void Execute_ExceedTicketPurchaseLimitException() const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -683,13 +711,15 @@ public void Execute_ExceedTicketPurchaseLimitException() }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -699,9 +729,10 @@ public void Execute_ExceedTicketPurchaseLimitDuringIntervalException() const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -768,13 +799,15 @@ public void Execute_ExceedTicketPurchaseLimitDuringIntervalException() }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Fact] @@ -784,9 +817,10 @@ public void Execute_CoolDownBlockException() const int round = 2; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -848,21 +882,24 @@ public void Execute_CoolDownBlockException() var blockIndex = roundData.StartBlockIndex + 1; - var nextStates = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - }); + var nextStates = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + }); - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex + 1, - PreviousState = nextStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex + 1, + PreviousState = nextStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Theory] @@ -879,9 +916,10 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(_initialStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + _initialStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -925,13 +963,14 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 SlotIndex = 1, }; - previousStates = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - }); + previousStates = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + }); var action = new BattleArena { @@ -967,10 +1006,11 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 throw new ArenaScoreNotFoundException($"enemyScoreAdr : {enemyScoreAdr}"); } - Assert.True(previousStates.TryGetAvatarState( - _agent1Address, - _avatar1Address, - out var previousMyAvatarState)); + Assert.True( + previousStates.TryGetAvatarState( + _agent1Address, + _avatar1Address, + out var previousMyAvatarState)); Assert.Empty(previousMyAvatarState.inventory.Materials); var gameConfigState = SetArenaInterval(arenaInterval); @@ -978,13 +1018,16 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 var blockIndex = roundData.StartBlockIndex + nextBlockIndex; - Assert.Throws(exception, () => action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = random.Seed, - BlockIndex = blockIndex, - })); + Assert.Throws( + exception, + () => action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = random.Seed, + BlockIndex = blockIndex, + })); } [Fact] @@ -994,9 +1037,10 @@ public void Execute_ValidateDuplicateTicketPurchaseException() const int round = 1; var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(previousStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + previousStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -1064,13 +1108,15 @@ public void Execute_ValidateDuplicateTicketPurchaseException() }; var blockIndex = roundData.StartBlockIndex + 1; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - Signer = _agent1Address, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + Signer = _agent1Address, + RandomSeed = 0, + })); } [Theory] @@ -1144,9 +1190,10 @@ private void Execute( { var context = new ActionContext(); var previousStates = _initialStates; - Assert.True(_initialStates.GetSheet().TryGetValue( - championshipId, - out var row)); + Assert.True( + _initialStates.GetSheet().TryGetValue( + championshipId, + out var row)); if (!row.TryGetRound(round, out var roundData)) { @@ -1226,10 +1273,11 @@ private void Execute( throw new ArenaScoreNotFoundException($"enemyScoreAdr : {enemyScoreAdr}"); } - Assert.True(previousStates.TryGetAvatarState( - myAgentAddress, - myAvatarAddress, - out var previousMyAvatarState)); + Assert.True( + previousStates.TryGetAvatarState( + myAgentAddress, + myAvatarAddress, + out var previousMyAvatarState)); Assert.Empty(previousMyAvatarState.inventory.Materials); var gameConfigState = SetArenaInterval(arenaInterval); @@ -1238,13 +1286,14 @@ private void Execute( var blockIndex = roundData.StartBlockIndex < arenaInterval ? roundData.StartBlockIndex : roundData.StartBlockIndex + arenaInterval; - var nextStates = action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = myAgentAddress, - RandomSeed = random.Seed, - BlockIndex = blockIndex, - }); + var nextStates = action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = myAgentAddress, + RandomSeed = random.Seed, + BlockIndex = blockIndex, + }); if (!nextStates.TryGetArenaScore(myScoreAdr, out var myScoreNext)) { @@ -1367,13 +1416,14 @@ private IWorld JoinArena( runeInfos = new List(), }; - states = action.Execute(new ActionContext - { - PreviousState = states, - Signer = signer, - RandomSeed = random.Seed, - BlockIndex = blockIndex, - }); + states = action.Execute( + new ActionContext + { + PreviousState = states, + Signer = signer, + RandomSeed = random.Seed, + BlockIndex = blockIndex, + }); return states; } diff --git a/.Lib9c.Tests/Action/BurnAssetTest.cs b/.Lib9c.Tests/Action/BurnAssetTest.cs index 3e028313b8..fae51948b6 100644 --- a/.Lib9c.Tests/Action/BurnAssetTest.cs +++ b/.Lib9c.Tests/Action/BurnAssetTest.cs @@ -24,10 +24,11 @@ public BurnAssetTest() MockWorldState.CreateModern() .SetBalance(_signer, Currencies.Crystal * 100) .SetBalance( - _signer.Derive(string.Format( - CultureInfo.InvariantCulture, - CreateAvatar.DeriveFormat, - 1)), + _signer.Derive( + string.Format( + CultureInfo.InvariantCulture, + CreateAvatar.DeriveFormat, + 1)), Currencies.DailyRewardRune * 20)); } @@ -55,10 +56,12 @@ public void PlainValue() new KeyValuePair[] { new ( - (Text)"type_id", (Text)"burn_asset" + (Text)"type_id", + (Text)"burn_asset" ), new ( - (Text)"values", new List( + (Text)"values", + new List( _signer.Bencoded, (Currencies.Crystal * 100).Serialize(), (Text)"memo" @@ -77,10 +80,12 @@ public void LoadPlainValue() new KeyValuePair[] { new ( - (Text)"type_id", (Text)"burn_asset" + (Text)"type_id", + (Text)"burn_asset" ), new ( - (Text)"values", new List( + (Text)"values", + new List( _signer.Bencoded, (Currencies.Crystal * 100).Serialize(), (Text)"memo" @@ -102,10 +107,12 @@ public void LoadPlainValue_Throws_MemoLengthOverflowException() new KeyValuePair[] { new ( - (Text)"type_id", (Text)"burn_asset" + (Text)"type_id", + (Text)"burn_asset" ), new ( - (Text)"values", new List( + (Text)"values", + new List( _signer.Bencoded, (Currencies.Crystal * 100).Serialize(), (Text)"very long memo".PadRight(100, ' ') @@ -186,17 +193,18 @@ public void Execute_Throws_InsufficientBalanceException() Currencies.Crystal * 1000, "1000" ); - Assert.Throws(() => - { - action.Execute( - new ActionContext() - { - PreviousState = prevState, - Signer = _signer, - BlockIndex = 1, - } - ); - }); + Assert.Throws( + () => + { + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _signer, + BlockIndex = 1, + } + ); + }); } [Fact] @@ -209,17 +217,18 @@ public void Execute_Throws_InvalidActionFieldException() Currencies.Crystal * 1000, "42" ); - Assert.Throws(() => - { - action.Execute( - new ActionContext() - { - PreviousState = prevState, - Signer = _signer, - BlockIndex = 1, - } - ); - }); + Assert.Throws( + () => + { + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _signer, + BlockIndex = 1, + } + ); + }); } } } diff --git a/.Lib9c.Tests/Action/BuyMultipleTest.cs b/.Lib9c.Tests/Action/BuyMultipleTest.cs index 4638dd5f66..fb546b13c4 100644 --- a/.Lib9c.Tests/Action/BuyMultipleTest.cs +++ b/.Lib9c.Tests/Action/BuyMultipleTest.cs @@ -312,31 +312,34 @@ public void Execute(params ShopItemData[] productDatas) var buyerGold = previousStates.GetBalance(_buyerAgentAddress, goldCurrency); var priceSumData = productDatas .Where(i => i.Buy) - .Aggregate(priceData, (priceSum, next) => - { - var price = new FungibleAssetValue(goldCurrency, next.Price, 0); - var tax = price.DivRem(100, out _) * Buy.TaxRate; - var taxedPrice = price - tax; - priceData.TaxSum += tax; - - var prevSum = priceData.TaxedPriceSum[next.SellerAgentAddress]; - priceData.TaxedPriceSum[next.SellerAgentAddress] = prevSum + taxedPrice; - priceData.PriceSum += price; - return priceData; - }); + .Aggregate( + priceData, + (priceSum, next) => + { + var price = new FungibleAssetValue(goldCurrency, next.Price, 0); + var tax = price.DivRem(100, out _) * Buy.TaxRate; + var taxedPrice = price - tax; + priceData.TaxSum += tax; + + var prevSum = priceData.TaxedPriceSum[next.SellerAgentAddress]; + priceData.TaxedPriceSum[next.SellerAgentAddress] = prevSum + taxedPrice; + priceData.PriceSum += price; + return priceData; + }); var buyMultipleAction = new BuyMultiple { buyerAvatarAddress = _buyerAvatarAddress, purchaseInfos = itemsToBuy, }; - var nextState = buyMultipleAction.Execute(new ActionContext() - { - BlockIndex = 1, - PreviousState = previousStates, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + var nextState = buyMultipleAction.Execute( + new ActionContext() + { + BlockIndex = 1, + PreviousState = previousStates, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var nextShopState = nextState.GetShopState(); Assert.Equal(productDatas.Length - buyCount, nextShopState.Products.Count); @@ -377,23 +380,25 @@ public void ExecuteThrowInvalidAddressException() var costume = ItemFactory.CreateCostume( _tableSheets.CostumeItemSheet.First, Guid.NewGuid()); - shopState.Register(new ShopItem( - _buyerAgentAddress, - _buyerAvatarAddress, - Guid.NewGuid(), - new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), - 100, - costume)); + shopState.Register( + new ShopItem( + _buyerAgentAddress, + _buyerAvatarAddress, + Guid.NewGuid(), + new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), + 100, + costume)); _initialState = _initialState .SetLegacyState(Addresses.Shop, shopState.Serialize()); shopState = _initialState.GetShopState(); var products = shopState.Products.Values - .Select(p => new BuyMultiple.PurchaseInfo( - p.ProductId, - p.SellerAgentAddress, - p.SellerAvatarAddress)) + .Select( + p => new BuyMultiple.PurchaseInfo( + p.ProductId, + p.SellerAgentAddress, + p.SellerAvatarAddress)) .ToList(); Assert.NotEmpty(products); @@ -403,13 +408,15 @@ public void ExecuteThrowInvalidAddressException() purchaseInfos = products, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = new World(MockUtil.MockModernWorldState), - RandomSeed = 0, - Signer = _buyerAgentAddress, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = new World(MockUtil.MockModernWorldState), + RandomSeed = 0, + Signer = _buyerAgentAddress, + }) ); } @@ -422,13 +429,15 @@ public void ExecuteThrowFailedLoadStateException() purchaseInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = new World(MockUtil.MockModernWorldState), - RandomSeed = 0, - Signer = _buyerAgentAddress, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = new World(MockUtil.MockModernWorldState), + RandomSeed = 0, + Signer = _buyerAgentAddress, + }) ); } @@ -451,13 +460,15 @@ public void ExecuteThrowNotEnoughClearedStageLevelException() purchaseInfos = new List(), }; - Assert.Throws(() => action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }) ); } @@ -469,13 +480,14 @@ public void ExecuteThrowItemDoesNotExistErrorByEmptyCollection() buyerAvatarAddress = _buyerAvatarAddress, purchaseInfos = new List(), }; - action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var nextBuyerAvatarState = _initialState.GetAvatarState(_buyerAvatarAddress); foreach (var result in action.buyerResult.purchaseResults) @@ -497,24 +509,26 @@ public void ExecuteInsufficientBalanceError() _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 1); - shopState.Register(new ShopItem( - sellerAgentAddress, - sellerAvatarAddress, - Guid.NewGuid(), - new FungibleAssetValue(_goldCurrencyState.Currency, 1, 0), - 100, - (ITradableItem)equipment)); + shopState.Register( + new ShopItem( + sellerAgentAddress, + sellerAvatarAddress, + Guid.NewGuid(), + new FungibleAssetValue(_goldCurrencyState.Currency, 1, 0), + 100, + (ITradableItem)equipment)); var costume = ItemFactory.CreateCostume( _tableSheets.CostumeItemSheet.First, Guid.NewGuid()); - shopState.Register(new ShopItem( - sellerAgentAddress, - sellerAvatarAddress, - Guid.NewGuid(), - new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), - 100, - costume)); + shopState.Register( + new ShopItem( + sellerAgentAddress, + sellerAvatarAddress, + Guid.NewGuid(), + new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), + 100, + costume)); var context = new ActionContext(); _initialState = _initialState @@ -523,10 +537,11 @@ public void ExecuteInsufficientBalanceError() Assert.NotEmpty(shopState.Products); var products = shopState.Products.Values - .Select(p => new BuyMultiple.PurchaseInfo( - p.ProductId, - p.SellerAgentAddress, - p.SellerAvatarAddress)) + .Select( + p => new BuyMultiple.PurchaseInfo( + p.ProductId, + p.SellerAgentAddress, + p.SellerAvatarAddress)) .ToList(); Assert.NotEmpty(products); @@ -539,13 +554,14 @@ public void ExecuteInsufficientBalanceError() purchaseInfos = products, }; - action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var results = action.buyerResult.purchaseResults; var isAllFailed = results.Any(r => r.errorCode == BuyMultiple.ERROR_CODE_INSUFFICIENT_BALANCE); @@ -567,13 +583,14 @@ public void ExecuteThrowShopItemExpiredError() _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 10); - shopState.Register(new ShopItem( - sellerAgentAddress, - sellerAvatarAddress, - productId, - new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), - 10, - (ITradableItem)equipment)); + shopState.Register( + new ShopItem( + sellerAgentAddress, + sellerAvatarAddress, + productId, + new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), + 10, + (ITradableItem)equipment)); previousStates = previousStates .SetLegacyState(Addresses.Shop, shopState.Serialize()); @@ -581,10 +598,11 @@ public void ExecuteThrowShopItemExpiredError() Assert.True(shopState.Products.ContainsKey(productId)); var products = shopState.Products.Values - .Select(p => new BuyMultiple.PurchaseInfo( - p.ProductId, - p.SellerAgentAddress, - p.SellerAvatarAddress)) + .Select( + p => new BuyMultiple.PurchaseInfo( + p.ProductId, + p.SellerAgentAddress, + p.SellerAvatarAddress)) .ToList(); var action = new BuyMultiple @@ -593,13 +611,14 @@ public void ExecuteThrowShopItemExpiredError() purchaseInfos = products, }; - action.Execute(new ActionContext() - { - BlockIndex = 11, - PreviousState = previousStates, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + action.Execute( + new ActionContext() + { + BlockIndex = 11, + PreviousState = previousStates, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var results = action.buyerResult.purchaseResults; var isAllFailed = results.Any(r => r.errorCode == BuyMultiple.ERROR_CODE_SHOPITEM_EXPIRED); @@ -607,7 +626,8 @@ public void ExecuteThrowShopItemExpiredError() } private (AvatarState AvatarState, AgentState AgentState) CreateAvatarState( - Address agentAddress, Address avatarAddress) + Address agentAddress, + Address avatarAddress) { var agentState = new AgentState(agentAddress); var rankingMapAddress = new PrivateKey().Address; diff --git a/.Lib9c.Tests/Action/BuyProductTest.cs b/.Lib9c.Tests/Action/BuyProductTest.cs index 0233c55c64..3437b3d169 100644 --- a/.Lib9c.Tests/Action/BuyProductTest.cs +++ b/.Lib9c.Tests/Action/BuyProductTest.cs @@ -300,12 +300,15 @@ public void Execute_Throw_Exception(params ExecuteMember[] validateMembers) AvatarAddress = BuyerAvatarAddress, ProductInfos = new[] { productInfo, }, }; - Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext - { - PreviousState = previousState, - RandomSeed = 0, - Signer = BuyerAgentAddress, - })); + Assert.Throws( + validateMember.Exc, + () => action.Execute( + new ActionContext + { + PreviousState = previousState, + RandomSeed = 0, + Signer = BuyerAgentAddress, + })); } } } diff --git a/.Lib9c.Tests/Action/BuyTest.cs b/.Lib9c.Tests/Action/BuyTest.cs index e4f686f4a7..036d50fb77 100644 --- a/.Lib9c.Tests/Action/BuyTest.cs +++ b/.Lib9c.Tests/Action/BuyTest.cs @@ -225,7 +225,7 @@ public void Execute(params OrderData[] orderDataList) var legacyShopState = _initialState.GetShopState(); foreach (var orderData in orderDataList) { - (var sellerAvatarState, var sellerAgentState) = CreateAvatarState( + var (sellerAvatarState, sellerAgentState) = CreateAvatarState( orderData.SellerAgentAddress, orderData.SellerAvatarAddress ); @@ -341,26 +341,28 @@ public void Execute(params OrderData[] orderDataList) buyerAvatarAddress = _buyerAvatarAddress, purchaseInfos = purchaseInfos, }; - var expectedState = buyAction.Execute(new ActionContext() - { - BlockIndex = 100, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + var expectedState = buyAction.Execute( + new ActionContext() + { + BlockIndex = 100, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var buyProductAction = new BuyProduct { AvatarAddress = _buyerAvatarAddress, ProductInfos = productInfos, }; - var actualState = buyProductAction.Execute(new ActionContext - { - BlockIndex = 100, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + var actualState = buyProductAction.Execute( + new ActionContext + { + BlockIndex = 100, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); Assert.Empty(buyAction.errors); @@ -484,13 +486,16 @@ public void Execute_Throw_Exception(bool equalAvatarAddress, bool clearStage, Ty purchaseInfos = new[] { purchaseInfo, }, }; - Assert.Throws(exc, () => action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }) + Assert.Throws( + exc, + () => action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }) ); } @@ -513,7 +518,8 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) } var item = ItemFactory.CreateItem( - _tableSheets.ConsumableItemSheet.Values.First(r => r.ItemSubType == ItemSubType.Food), new TestRandom()); + _tableSheets.ConsumableItemSheet.Values.First(r => r.ItemSubType == ItemSubType.Food), + new TestRandom()); var orderTradableId = ((ITradableItem)item).TradableId; var tradableId = errorCodeMember.EqualTradableId ? orderTradableId : Guid.NewGuid(); var price = errorCodeMember.EqualPrice ? orderPrice : default; @@ -614,13 +620,14 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) purchaseInfos = new[] { purchaseInfo, }, }; - var nextState = action.Execute(new ActionContext() - { - BlockIndex = blockIndex, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + var nextState = action.Execute( + new ActionContext() + { + BlockIndex = blockIndex, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); Assert.Contains( errorCodeMember.ErrorCode, @@ -648,13 +655,16 @@ public void Execute_ErrorCode(ErrorCodeMember errorCodeMember) _ => throw new ArgumentNullException(), }; - Assert.Throws(exc, () => buyProductAction.Execute(new ActionContext() - { - BlockIndex = blockIndex, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - })); + Assert.Throws( + exc, + () => buyProductAction.Execute( + new ActionContext() + { + BlockIndex = blockIndex, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + })); foreach (var address in new[] { agentAddress, sellerAgentAddress, GoldCurrencyState.Address, }) { @@ -767,13 +777,14 @@ public void Execute_ReconfigureFungibleItem(params OrderData[] orderDataList) buyerAvatarAddress = _buyerAvatarAddress, purchaseInfos = purchaseInfos, }; - var nextState = buyAction.Execute(new ActionContext() - { - BlockIndex = 100, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _buyerAgentAddress, - }); + var nextState = buyAction.Execute( + new ActionContext() + { + BlockIndex = 100, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _buyerAgentAddress, + }); var nextBuyerAvatarState = nextState.GetAvatarState(_buyerAvatarAddress); @@ -874,13 +885,14 @@ public void Execute_With_Testbed() purchaseInfos = purchaseInfos, }; - nextState = buyAction.Execute(new ActionContext() - { - BlockIndex = 100, - PreviousState = nextState, - RandomSeed = 0, - Signer = result.GetAgentState().address, - }); + nextState = buyAction.Execute( + new ActionContext() + { + BlockIndex = 100, + PreviousState = nextState, + RandomSeed = 0, + Signer = result.GetAgentState().address, + }); var totalTax = 0 * _goldCurrencyState.Currency; var totalPrice = 0 * _goldCurrencyState.Currency; @@ -904,10 +916,18 @@ public void Execute_With_Testbed() var nextSellerAvatarState = nextState.GetAvatarState(purchaseInfo.SellerAvatarAddress); - Assert.True(nextBuyerAvatarState.inventory.TryGetTradableItem( - tradableId, 100, itemCount, out var _)); - Assert.False(nextSellerAvatarState.inventory.TryGetTradableItem( - tradableId, 100, itemCount, out var _)); + Assert.True( + nextBuyerAvatarState.inventory.TryGetTradableItem( + tradableId, + 100, + itemCount, + out var _)); + Assert.False( + nextSellerAvatarState.inventory.TryGetTradableItem( + tradableId, + 100, + itemCount, + out var _)); Assert.Empty(nextSellerAvatarState.mailBox.OfType()); var orderReceipt = new OrderReceipt((Dictionary)nextState.GetLegacyState(OrderReceipt.DeriveAddress(order.OrderId))); @@ -929,8 +949,9 @@ public void Execute_With_Testbed() agentRevenue.Add(order.SellerAgentAddress, revenue); } - var mailCount = purchaseInfos.Count(x => - x.SellerAvatarAddress.Equals(purchaseInfo.SellerAvatarAddress)); + var mailCount = purchaseInfos.Count( + x => + x.SellerAvatarAddress.Equals(purchaseInfo.SellerAvatarAddress)); Assert.Equal(mailCount, nextSellerAvatarState.mailBox.OfType().Count()); Assert.Empty(nextSellerAvatarState.mailBox.OfType()); } @@ -958,7 +979,8 @@ public void Execute_With_Testbed() } private (AvatarState AvatarState, AgentState AgentState) CreateAvatarState( - Address agentAddress, Address avatarAddress) + Address agentAddress, + Address avatarAddress) { var agentState = new AgentState(agentAddress); var rankingMapAddress = new PrivateKey().Address; diff --git a/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs b/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs index 3bccfb3319..b5bf95f033 100644 --- a/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs +++ b/.Lib9c.Tests/Action/CancelProductRegistrationTest.cs @@ -146,13 +146,14 @@ public void Execute_Throw_ProductNotFoundException() }, }, }; - var nexState = registerProduct.Execute(new ActionContext - { - PreviousState = prevState, - BlockIndex = 1L, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nexState = registerProduct.Execute( + new ActionContext + { + PreviousState = prevState, + BlockIndex = 1L, + Signer = _agentAddress, + RandomSeed = 0, + }); Assert.Equal( 0 * RuneHelper.StakeRune, nexState.GetBalance(_avatarAddress, RuneHelper.StakeRune) @@ -186,13 +187,15 @@ public void Execute_Throw_ProductNotFoundException() }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = nexState, - BlockIndex = 2L, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = nexState, + BlockIndex = 2L, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Fact] diff --git a/.Lib9c.Tests/Action/ChargeActionPointTest.cs b/.Lib9c.Tests/Action/ChargeActionPointTest.cs index 3979247a9e..fb8931de42 100644 --- a/.Lib9c.Tests/Action/ChargeActionPointTest.cs +++ b/.Lib9c.Tests/Action/ChargeActionPointTest.cs @@ -86,12 +86,13 @@ public void Execute(bool useTradable) avatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); Assert.True(nextState.TryGetActionPoint(_avatarAddress, out var nextActionPoint)); Assert.Equal(DailyReward.ActionPointMax, nextActionPoint); @@ -139,12 +140,15 @@ public void Execute_Throw_Exception(bool useAvatarAddress, bool useTradable, boo avatarAddress = avatarAddress, }; - Assert.Throws(exc, () => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }) + Assert.Throws( + exc, + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }) ); } } diff --git a/.Lib9c.Tests/Action/ClaimItemsTest.cs b/.Lib9c.Tests/Action/ClaimItemsTest.cs index 9c7bf221f6..ac52d31a4b 100644 --- a/.Lib9c.Tests/Action/ClaimItemsTest.cs +++ b/.Lib9c.Tests/Action/ClaimItemsTest.cs @@ -97,8 +97,9 @@ public void Serialize(bool memoExist) foreach (var i in Enumerable.Range(0, 2)) { Assert.Equal(action.ClaimData[i].address, deserialized.ClaimData[i].address); - Assert.True(action.ClaimData[i].fungibleAssetValues - .SequenceEqual(deserialized.ClaimData[i].fungibleAssetValues)); + Assert.True( + action.ClaimData[i].fungibleAssetValues + .SequenceEqual(deserialized.ClaimData[i].fungibleAssetValues)); } Assert.Equal(action.Memo, deserialized.Memo); @@ -110,18 +111,21 @@ public void Execute_Throws_ArgumentException_TickerInvalid() var state = GenerateAvatar(_initialState, out var recipientAvatarAddress, out _); var currency = Currencies.Crystal; - var action = new ClaimItems(new List<(Address, IReadOnlyList)> - { - (recipientAvatarAddress, new List { currency * 1, }), - }); - Assert.Throws(() => - action.Execute(new ActionContext + var action = new ClaimItems( + new List<(Address, IReadOnlyList)> { - PreviousState = state, - Signer = _signerAddress, - BlockIndex = 100, - RandomSeed = 0, - })); + (recipientAvatarAddress, new List { currency * 1, }), + }); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signerAddress, + BlockIndex = 100, + RandomSeed = 0, + })); } [Fact] @@ -130,18 +134,21 @@ public void Execute_Throws_WhenNotEnoughBalance() var state = GenerateAvatar(_initialState, out var recipientAvatarAddress, out _); var currency = _itemCurrencies.First(); - var action = new ClaimItems(new List<(Address, IReadOnlyList)> - { - (recipientAvatarAddress, new List { currency * 6, }), - }); - Assert.Throws(() => - action.Execute(new ActionContext + var action = new ClaimItems( + new List<(Address, IReadOnlyList)> { - PreviousState = state, - Signer = _signerAddress, - BlockIndex = 100, - RandomSeed = 0, - })); + (recipientAvatarAddress, new List { currency * 6, }), + }); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signerAddress, + BlockIndex = 100, + RandomSeed = 0, + })); } [Theory] @@ -174,13 +181,14 @@ public void Execute(string memo) }, memo ); - var states = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signerAddress, - BlockIndex = 0, - RandomSeed = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signerAddress, + BlockIndex = 0, + RandomSeed = 0, + }); var avatarState = states.GetAvatarState(recipientAvatarAddress, getQuestList: false, getWorldInformation: false); Assert.Null(avatarState.questList); @@ -238,19 +246,21 @@ public void Execute_WithMultipleRecipients() }; var fungibleAssetValues = _itemCurrencies.Select(currency => currency * 1).ToList(); - var action = new ClaimItems(new List<(Address, IReadOnlyList)> - { - (recipientAvatarAddress1, fungibleAssetValues.Take(2).ToList()), - (recipientAvatarAddress2, fungibleAssetValues), - }); + var action = new ClaimItems( + new List<(Address, IReadOnlyList)> + { + (recipientAvatarAddress1, fungibleAssetValues.Take(2).ToList()), + (recipientAvatarAddress2, fungibleAssetValues), + }); - var states = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signerAddress, - BlockIndex = 0, - RandomSeed = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signerAddress, + BlockIndex = 0, + RandomSeed = 0, + }); Assert.Equal(states.GetBalance(_signerAddress, _itemCurrencies[0]), _itemCurrencies[0] * 3); Assert.Equal(states.GetBalance(_signerAddress, _itemCurrencies[1]), _itemCurrencies[1] * 3); @@ -285,18 +295,20 @@ public void Execute_WithNonFungibleItem() _signerAddress, currency * itemCount); - var action = new ClaimItems(new List<(Address, IReadOnlyList)> - { - (recipientAvatarAddress1, new List { currency * itemCount, }), - }); + var action = new ClaimItems( + new List<(Address, IReadOnlyList)> + { + (recipientAvatarAddress1, new List { currency * itemCount, }), + }); - var states = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signerAddress, - BlockIndex = 0, - RandomSeed = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signerAddress, + BlockIndex = 0, + RandomSeed = 0, + }); Assert.Equal(states.GetBalance(_signerAddress, currency), currency * 0); @@ -309,19 +321,24 @@ public void Execute_WithIncorrectClaimData() { var fungibleAssetValues = _itemCurrencies.Select(currency => currency * 1).ToList(); - var action = new ClaimItems(Enumerable.Repeat(0, 101) - .Select(_ => (new PrivateKey().Address, - (IReadOnlyList)fungibleAssetValues)) - .ToImmutableList()); - - Assert.Throws("ClaimData", () => - action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _signerAddress, - BlockIndex = 0, - RandomSeed = 0, - })); + var action = new ClaimItems( + Enumerable.Repeat(0, 101) + .Select( + _ => (new PrivateKey().Address, + (IReadOnlyList)fungibleAssetValues)) + .ToImmutableList()); + + Assert.Throws( + "ClaimData", + () => + action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _signerAddress, + BlockIndex = 0, + RandomSeed = 0, + })); } private IWorld GenerateAvatar(IWorld state, out Address avatarAddress, out Address agentAddress) diff --git a/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs b/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs index 6a81399e64..909db0c67e 100644 --- a/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimRaidRewardTest.cs @@ -100,13 +100,14 @@ public void Execute(Type exc, int rank, int latestRank) var action = new ClaimRaidReward(avatarAddress); if (exc is null) { - var nextState = action.Execute(new ActionContext - { - Signer = agentAddress, - BlockIndex = blockIndex, - RandomSeed = randomSeed, - PreviousState = state, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = agentAddress, + BlockIndex = blockIndex, + RandomSeed = randomSeed, + PreviousState = state, + }); var crystalCurrency = CrystalCalculator.CRYSTAL; Assert.Equal( @@ -134,13 +135,16 @@ public void Execute(Type exc, int rank, int latestRank) } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - Signer = default, - BlockIndex = 5055201L, - RandomSeed = randomSeed, - PreviousState = state, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + Signer = default, + BlockIndex = 5055201L, + RandomSeed = randomSeed, + PreviousState = state, + })); } } } diff --git a/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs b/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs index dfe841117e..b01ebfd9ac 100644 --- a/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimStakeRewardTest.cs @@ -354,21 +354,23 @@ public void Serde() [Fact] public void Execute_Throw_FailedLoadStateException_When_Staking_State_Null() { - Assert.Throws(() => - Execute( - _initialState, - AgentAddr, - AvatarAddr, - 0)); + Assert.Throws( + () => + Execute( + _initialState, + AgentAddr, + AvatarAddr, + 0)); var stakeAddr = StakeStateV2.DeriveAddress(AgentAddr); var previousState = _initialState.RemoveLegacyState(stakeAddr); - Assert.Throws(() => - Execute( - previousState, - AgentAddr, - AvatarAddr, - 0)); + Assert.Throws( + () => + Execute( + previousState, + AgentAddr, + AvatarAddr, + 0)); } [Theory] @@ -395,12 +397,13 @@ public void Execute_Throw_RequiredBlockIndexException_With_StakeState( // NOTE: minimum required_gold of StakeRegularRewardSheetFixtures.V2 is 50. .MintAsset(new ActionContext(), stakeAddr, _ncg * 50) .SetLegacyState(stakeAddr, stakeState.Serialize()); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Theory] @@ -426,12 +429,13 @@ public void Execute_Throw_RequiredBlockIndexException_With_StakeStateV2( // NOTE: minimum required_gold of StakeRegularRewardSheetFixtures.V2 is 50. .MintAsset(new ActionContext(), stakeAddr, _ncg * 50) .SetLegacyState(stakeAddr, stakeStateV2.Serialize()); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Fact] @@ -448,12 +452,13 @@ public void Execute_Throw_FailedLoadStateException_When_Sheet_Null() var sheetAddr = Addresses.GetSheetAddress( stakeStateV2.Contract.StakeRegularFixedRewardSheetTableName); prevState = prevState.RemoveLegacyState(sheetAddr); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); prevState = _initialState // NOTE: minimum required_gold of StakeRegularRewardSheetFixtures.V2 is 50. @@ -463,12 +468,13 @@ public void Execute_Throw_FailedLoadStateException_When_Sheet_Null() sheetAddr = Addresses.GetSheetAddress( stakeStateV2.Contract.StakeRegularRewardSheetTableName); prevState = prevState.RemoveLegacyState(sheetAddr); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Theory] @@ -487,12 +493,13 @@ public void Execute_Throw_InsufficientBalanceException(long stakedBalance) stakeAddr, _ncg * stakedBalance) : previousState; - Assert.Throws(() => - Execute( - previousState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + previousState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Fact] @@ -510,18 +517,25 @@ public void Execute_Throw_ArgumentNullException_When_Reward_CurrencyTicker_Null( var sheetAddr = Addresses.GetSheetAddress( stakeStateV2.Contract.StakeRegularRewardSheetTableName); var sheetValue = prevState.GetSheetCsv(sheetAddr); - sheetValue = string.Join('\n', sheetValue.Split('\n') - .Select(line => string.Join(',', line.Split(',') - .Select((column, index) => index == 5 - ? string.Empty - : column)))); + sheetValue = string.Join( + '\n', + sheetValue.Split('\n') + .Select( + line => string.Join( + ',', + line.Split(',') + .Select( + (column, index) => index == 5 + ? string.Empty + : column)))); prevState = prevState.SetLegacyState(sheetAddr, sheetValue.Serialize()); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Fact] @@ -540,24 +554,31 @@ public void var sheetAddr = Addresses.GetSheetAddress( stakeStateV2.Contract.StakeRegularRewardSheetTableName); var sheetValue = prevState.GetSheetCsv(sheetAddr); - sheetValue = string.Join('\n', sheetValue.Split('\n') - .Select(line => string.Join(',', line.Split(',') - .Select((column, index) => - { - return index switch - { - 5 => "NEW_TICKER", - 6 => string.Empty, - _ => column, - }; - })))); + sheetValue = string.Join( + '\n', + sheetValue.Split('\n') + .Select( + line => string.Join( + ',', + line.Split(',') + .Select( + (column, index) => + { + return index switch + { + 5 => "NEW_TICKER", + 6 => string.Empty, + _ => column, + }; + })))); prevState = prevState.SetLegacyState(sheetAddr, sheetValue.Serialize()); - Assert.Throws(() => - Execute( - prevState, - AgentAddr, - AvatarAddr, - blockIndex)); + Assert.Throws( + () => + Execute( + prevState, + AgentAddr, + AvatarAddr, + blockIndex)); } [Theory] @@ -707,12 +728,13 @@ private static IWorld Execute( var prevBalance = prevState.GetBalance(agentAddr, ncg); var prevStakedBalance = prevState.GetBalance(stakeAddr, ncg); var action = new ClaimStakeReward(avatarAddr); - var nextState = action.Execute(new ActionContext - { - PreviousState = prevState, - Signer = agentAddr, - BlockIndex = blockIndex, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = prevState, + Signer = agentAddr, + BlockIndex = blockIndex, + }); var nextBalance = nextState.GetBalance(agentAddr, ncg); Assert.Equal(prevBalance, nextBalance); var nextStakedBalance = nextState.GetBalance(stakeAddr, ncg); diff --git a/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs b/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs index d1fff158a5..a402cac245 100644 --- a/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs +++ b/.Lib9c.Tests/Action/ClaimWorldBossKillRewardTest.cs @@ -30,15 +30,18 @@ public void Execute(long blockIndex, Type exc) IWorld state = new World(MockUtil.MockModernWorldState); var runeWeightSheet = new RuneWeightSheet(); - runeWeightSheet.Set(@"id,boss_id,rank,rune_id,weight + runeWeightSheet.Set( + @"id,boss_id,rank,rune_id,weight 1,900001,0,10001,100 "); var killRewardSheet = new WorldBossKillRewardSheet(); - killRewardSheet.Set(@"id,boss_id,rank,rune_min,rune_max,crystal + killRewardSheet.Set( + @"id,boss_id,rank,rune_min,rune_max,crystal 1,900001,0,1,1,100 "); var worldBossListSheet = new WorldBossListSheet(); - worldBossListSheet.Set(@"id,boss_id,started_block_index,ended_block_index,fee,ticket_price,additional_ticket_price,max_purchase_count + worldBossListSheet.Set( + @"id,boss_id,started_block_index,ended_block_index,fee,ticket_price,additional_ticket_price,max_purchase_count 1,900001,0,100,300,200,100,10 "); var worldBossKillRewardRecordAddress = Addresses.GetWorldBossKillRewardRecordAddress(avatarAddress, 1); @@ -84,13 +87,14 @@ public void Execute(long blockIndex, Type exc) if (exc is null) { var randomSeed = 0; - var nextState = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - Signer = agentAddress, - PreviousState = state, - RandomSeed = randomSeed, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + Signer = agentAddress, + PreviousState = state, + RandomSeed = randomSeed, + }); var runeCurrency = RuneHelper.ToCurrency(tableSheets.RuneSheet[10001]); Assert.Equal(1 * runeCurrency, nextState.GetBalance(avatarAddress, runeCurrency)); @@ -131,13 +135,16 @@ public void Execute(long blockIndex, Type exc) } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - BlockIndex = blockIndex, - Signer = default, - PreviousState = state, - RandomSeed = 0, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + Signer = default, + PreviousState = state, + RandomSeed = 0, + })); } } } diff --git a/.Lib9c.Tests/Action/CombinationConsumableTest.cs b/.Lib9c.Tests/Action/CombinationConsumableTest.cs index f9a85c961e..2b12a573e8 100644 --- a/.Lib9c.Tests/Action/CombinationConsumableTest.cs +++ b/.Lib9c.Tests/Action/CombinationConsumableTest.cs @@ -103,13 +103,14 @@ public void Execute() slotIndex = 0, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = previousState, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = previousState, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + }); var allCombinationSlotState = nextState.GetAllCombinationSlotState(_avatarAddress); var slotState = allCombinationSlotState.GetSlot(0); diff --git a/.Lib9c.Tests/Action/CombinationEquipmentTest.cs b/.Lib9c.Tests/Action/CombinationEquipmentTest.cs index 7dab7b969e..12309e293b 100644 --- a/.Lib9c.Tests/Action/CombinationEquipmentTest.cs +++ b/.Lib9c.Tests/Action/CombinationEquipmentTest.cs @@ -177,7 +177,8 @@ bool previousCostStateExist foreach (var materialInfo in subRow.Materials) { var subMaterial = ItemFactory.CreateItem( - _tableSheets.MaterialItemSheet[materialInfo.Id], _random); + _tableSheets.MaterialItemSheet[materialInfo.Id], + _random); _avatarState.inventory.AddItem(subMaterial, materialInfo.Count); } @@ -246,8 +247,9 @@ bool previousCostStateExist var dailyCostAddress = Addresses.GetDailyCrystalCostAddress((int)(blockIndex / CrystalCostState.DailyIntervalIndex)); - var weeklyInterval = _tableSheets.CrystalFluctuationSheet.Values.First(r => - r.Type == CrystalFluctuationSheet.ServiceType.Combination).BlockInterval; + var weeklyInterval = _tableSheets.CrystalFluctuationSheet.Values.First( + r => + r.Type == CrystalFluctuationSheet.ServiceType.Combination).BlockInterval; var weeklyCostAddress = Addresses.GetWeeklyCrystalCostAddress((int)(blockIndex / weeklyInterval)); Assert.Null(state.GetLegacyState(dailyCostAddress)); @@ -265,13 +267,14 @@ bool previousCostStateExist if (exc is null) { - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = blockIndex, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = blockIndex, + RandomSeed = _random.Seed, + }); var currency = nextState.GetGoldCurrency(); Assert.Equal(0 * currency, nextState.GetBalance(_agentAddress, currency)); @@ -330,13 +333,16 @@ bool previousCostStateExist } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = blockIndex, - RandomSeed = _random.Seed, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = blockIndex, + RandomSeed = _random.Seed, + })); } } @@ -377,7 +383,8 @@ public void ExecuteWithCheckingHammerPointState( foreach (var materialInfo in subRow.Materials) { var subMaterial = ItemFactory.CreateItem( - _tableSheets.MaterialItemSheet[materialInfo.Id], _random); + _tableSheets.MaterialItemSheet[materialInfo.Id], + _random); _avatarState.inventory.AddItem(subMaterial, materialInfo.Count); } @@ -428,13 +435,14 @@ public void ExecuteWithCheckingHammerPointState( }; if (exc is null) { - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + }); Assert.True(nextState.TryGetLegacyState(hammerPointAddress, out List serialized)); var hammerPointState = new HammerPointState(hammerPointAddress, serialized); @@ -454,16 +462,19 @@ public void ExecuteWithCheckingHammerPointState( } else { - Assert.Throws(exc, () => - { - action.Execute(new ActionContext + Assert.Throws( + exc, + () => { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + }); }); - }); } } diff --git a/.Lib9c.Tests/Action/Common/Doomfist.cs b/.Lib9c.Tests/Action/Common/Doomfist.cs index 84aee1d7a0..8c379df006 100644 --- a/.Lib9c.Tests/Action/Common/Doomfist.cs +++ b/.Lib9c.Tests/Action/Common/Doomfist.cs @@ -47,23 +47,25 @@ public static Equipment GetOne( var requirementSheet = tableSheets.ItemRequirementSheet; var row = tableSheets.EquipmentItemSheet.OrderedList - .Where(e => - e.ItemSubType == itemSubType && - (!elementalType.HasValue || e.ElementalType == elementalType.Value) && - requirementSheet.TryGetValue(e.Id, out var requirementRow) && - avatarLevel >= requirementRow.Level) - .Aggregate((row1, row2) => - { - var row1Value = row1.Stat.StatType == statType - ? row1.Stat.BaseValueAsLong - : 0; - var row2Value = row2.Stat.StatType == statType - ? row2.Stat.BaseValueAsLong - : 0; - return row1Value > row2Value - ? row1 - : row2; - }); + .Where( + e => + e.ItemSubType == itemSubType && + (!elementalType.HasValue || e.ElementalType == elementalType.Value) && + requirementSheet.TryGetValue(e.Id, out var requirementRow) && + avatarLevel >= requirementRow.Level) + .Aggregate( + (row1, row2) => + { + var row1Value = row1.Stat.StatType == statType + ? row1.Stat.BaseValueAsLong + : 0; + var row2Value = row2.Stat.StatType == statType + ? row2.Stat.BaseValueAsLong + : 0; + return row1Value > row2Value + ? row1 + : row2; + }); Assert.NotNull(row); return (Equipment)ItemFactory.CreateItemUsable(row, Guid.NewGuid(), 0, 10); } diff --git a/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs b/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs index ab96945f3d..a1acbb3447 100644 --- a/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs +++ b/.Lib9c.Tests/Action/Coupons/CouponsFixture.cs @@ -14,17 +14,20 @@ public static class CouponsFixture public static Address AgentAddress3 { get; } = new ("0000000000000000000000000000000000000002"); public static RewardSet RewardSet1 { get; } = - new (ImmutableDictionary.Empty - .Add(302001, 1)); + new ( + ImmutableDictionary.Empty + .Add(302001, 1)); public static RewardSet RewardSet2 { get; } = - new (ImmutableDictionary.Empty - .Add(302001, 1) - .Add(302002, 2)); + new ( + ImmutableDictionary.Empty + .Add(302001, 1) + .Add(302002, 2)); public static RewardSet RewardSet3 { get; } = - new (ImmutableDictionary.Empty - .Add(302002, 2)); + new ( + ImmutableDictionary.Empty + .Add(302002, 2)); public static Guid Guid1 { get; } = new ("9CB96C65-3D47-4BAD-8BE6-18D97042B6C9"); diff --git a/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs b/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs index 971be47f51..512ab1f4a9 100644 --- a/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs +++ b/.Lib9c.Tests/Action/Coupons/IssueCouponsTest.cs @@ -27,31 +27,33 @@ public void Execute() .Serialize()); IRandom random = new TestRandom(); - Assert.Throws(() => - new IssueCoupons( - ImmutableDictionary.Empty, - CouponsFixture.AgentAddress1) - .Execute( - new ActionContext - { - PreviousState = state, - RandomSeed = random.Seed, - BlockIndex = long.MaxValue, - Signer = CouponsFixture.AgentAddress1, - })); + Assert.Throws( + () => + new IssueCoupons( + ImmutableDictionary.Empty, + CouponsFixture.AgentAddress1) + .Execute( + new ActionContext + { + PreviousState = state, + RandomSeed = random.Seed, + BlockIndex = long.MaxValue, + Signer = CouponsFixture.AgentAddress1, + })); - Assert.Throws(() => - new IssueCoupons( - ImmutableDictionary.Empty, - CouponsFixture.AgentAddress1) - .Execute( - new ActionContext - { - PreviousState = state, - RandomSeed = random.Seed, - BlockIndex = 0, - Signer = CouponsFixture.AgentAddress2, - })); + Assert.Throws( + () => + new IssueCoupons( + ImmutableDictionary.Empty, + CouponsFixture.AgentAddress1) + .Execute( + new ActionContext + { + PreviousState = state, + RandomSeed = random.Seed, + BlockIndex = 0, + Signer = CouponsFixture.AgentAddress2, + })); Assert.Equal( ImmutableDictionary.Empty, @@ -99,20 +101,32 @@ public void Execute() var agent2CouponWallet = state.GetCouponWallet(CouponsFixture.AgentAddress2); Assert.Equal(3, agent1CouponWallet.Count); - Assert.Equal(1, agent1CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet1))); - Assert.Equal(2, agent1CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet2))); - Assert.Equal(0, agent1CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet3))); + Assert.Equal( + 1, + agent1CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet1))); + Assert.Equal( + 2, + agent1CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet2))); + Assert.Equal( + 0, + agent1CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet3))); Assert.Equal(3, agent1CouponWallet.Count); - Assert.Equal(0, agent2CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet1))); - Assert.Equal(0, agent2CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet2))); - Assert.Equal(3, agent2CouponWallet.Count( - item => item.Value.Rewards.Equals(CouponsFixture.RewardSet3))); + Assert.Equal( + 0, + agent2CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet1))); + Assert.Equal( + 0, + agent2CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet2))); + Assert.Equal( + 3, + agent2CouponWallet.Count( + item => item.Value.Rewards.Equals(CouponsFixture.RewardSet3))); } [Fact] @@ -131,12 +145,14 @@ public void PlainValue() .Add( "rewards", Bencodex.Types.List.Empty - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) - .Add("quantity", 2)) - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) - .Add("quantity", 1))) + .Add( + Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) + .Add("quantity", 2)) + .Add( + Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) + .Add("quantity", 1))) .Select(kv => new KeyValuePair((Text)kv.Key, kv.Value))), ((Dictionary)((Dictionary)action.PlainValue)["values"]).Remove((Text)"id")); } @@ -155,20 +171,24 @@ public void LoadPlainValue() actual.LoadPlainValue( Dictionary.Empty .Add("type_id", "issue_coupons") - .Add("values", new Bencodex.Types.Dictionary( - ImmutableDictionary.Empty - .Add("recipient", new Binary(CouponsFixture.AgentAddress1.ByteArray)) - .Add( - "rewards", - Bencodex.Types.List.Empty - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) - .Add("quantity", 2)) - .Add(Bencodex.Types.Dictionary.Empty - .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) - .Add("quantity", 1))) - .Select(kv => new KeyValuePair((Text)kv.Key, kv.Value))) - .SetItem("id", new Guid("6E69DC55-A0D0-435A-A787-C62356CBE517").Serialize()))); + .Add( + "values", + new Bencodex.Types.Dictionary( + ImmutableDictionary.Empty + .Add("recipient", new Binary(CouponsFixture.AgentAddress1.ByteArray)) + .Add( + "rewards", + Bencodex.Types.List.Empty + .Add( + Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet1.Serialize()) + .Add("quantity", 2)) + .Add( + Bencodex.Types.Dictionary.Empty + .Add("rewardSet", CouponsFixture.RewardSet2.Serialize()) + .Add("quantity", 1))) + .Select(kv => new KeyValuePair((Text)kv.Key, kv.Value))) + .SetItem("id", new Guid("6E69DC55-A0D0-435A-A787-C62356CBE517").Serialize()))); Assert.Equal(expected.Rewards, actual.Rewards); Assert.Equal(expected.Recipient, actual.Recipient); diff --git a/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs b/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs index bb5d2fc6b4..7a8c36de54 100644 --- a/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs +++ b/.Lib9c.Tests/Action/Coupons/RedeemCouponTest.cs @@ -273,7 +273,8 @@ public void Execute() }); actual = state.GetAvatarState(agent1Avatar0Address); var aggregateRewardSet = CouponsFixture.RewardSet1.Aggregate( - CouponsFixture.RewardSet2, (rewardSet, kv) => + CouponsFixture.RewardSet2, + (rewardSet, kv) => { if (rewardSet.TryGetValue(kv.Key, out var val)) { diff --git a/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs b/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs index d851fa2f14..44e806c739 100644 --- a/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs +++ b/.Lib9c.Tests/Action/Coupons/TransferCouponsTest.cs @@ -35,49 +35,62 @@ public void Execute() .Add(CouponsFixture.Guid3, coupon3)); // can't transfer a nonexistent coupon - Assert.Throws(() => new TransferCoupons( - ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty.Add( - new Guid("97529656-CB7F-45C6-8466-A072DD2DBFBD")))) - .Execute( - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - })); + Assert.Throws( + () => new TransferCoupons( + ImmutableDictionary>.Empty + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty.Add( + new Guid("97529656-CB7F-45C6-8466-A072DD2DBFBD")))) + .Execute( + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + })); // can't transfer coupon that's not mine - Assert.Throws(() => new TransferCoupons( - ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress1, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1))) - .Execute( - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress2, - })); + Assert.Throws( + () => new TransferCoupons( + ImmutableDictionary>.Empty + .Add( + CouponsFixture.AgentAddress1, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1))) + .Execute( + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress2, + })); // can't transfer a coupon to two different people - Assert.Throws(() => new TransferCoupons( - ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1)) - .Add(CouponsFixture.AgentAddress3, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1))) - .Execute( - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - })); + Assert.Throws( + () => new TransferCoupons( + ImmutableDictionary>.Empty + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1)) + .Add( + CouponsFixture.AgentAddress3, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1))) + .Execute( + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + })); // transfer to self var expected = state.GetCouponWallet(CouponsFixture.AgentAddress1); state = new TransferCoupons( ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress1, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1))) + .Add( + CouponsFixture.AgentAddress1, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1))) .Execute( new ActionContext { @@ -102,8 +115,10 @@ public void Execute() expected = state.GetCouponWallet(CouponsFixture.AgentAddress1); state = new TransferCoupons( ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1))) + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1))) .Execute( new ActionContext { @@ -119,16 +134,19 @@ public void Execute() state.GetCouponWallet(CouponsFixture.AgentAddress2)); // can't transfer a coupon twice - Assert.Throws(() => new TransferCoupons( - ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1))) - .Execute( - new ActionContext - { - PreviousState = state, - Signer = CouponsFixture.AgentAddress1, - })); + Assert.Throws( + () => new TransferCoupons( + ImmutableDictionary>.Empty + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1))) + .Execute( + new ActionContext + { + PreviousState = state, + Signer = CouponsFixture.AgentAddress1, + })); // multiple transfer state = state @@ -147,11 +165,15 @@ public void Execute() state = new TransferCoupons( ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1) - .Add(CouponsFixture.Guid2)) - .Add(CouponsFixture.AgentAddress3, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid3))) + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1) + .Add(CouponsFixture.Guid2)) + .Add( + CouponsFixture.AgentAddress3, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid3))) .Execute( new ActionContext { @@ -177,11 +199,15 @@ public void PlainValue() { var action = new TransferCoupons( ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress1, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1)) - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid3) - .Add(CouponsFixture.Guid2)) + .Add( + CouponsFixture.AgentAddress1, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1)) + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid3) + .Add(CouponsFixture.Guid2)) .Add(CouponsFixture.AgentAddress3, ImmutableHashSet.Empty)); var expected = new Bencodex.Types.Dictionary( @@ -212,36 +238,43 @@ public void LoadPlainValue() { var expected = new TransferCoupons( ImmutableDictionary>.Empty - .Add(CouponsFixture.AgentAddress1, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid1)) - .Add(CouponsFixture.AgentAddress2, ImmutableHashSet.Empty - .Add(CouponsFixture.Guid3) - .Add(CouponsFixture.Guid2)) + .Add( + CouponsFixture.AgentAddress1, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid1)) + .Add( + CouponsFixture.AgentAddress2, + ImmutableHashSet.Empty + .Add(CouponsFixture.Guid3) + .Add(CouponsFixture.Guid2)) .Add(CouponsFixture.AgentAddress3, ImmutableHashSet.Empty)); var actual = new TransferCoupons(ImmutableDictionary>.Empty); - actual.LoadPlainValue(Dictionary.Empty - .Add("type_id", "transfer_coupons") - .Add("values", new Bencodex.Types.Dictionary( - ImmutableDictionary.Empty - .Add( - "couponsPerRecipient", - Bencodex.Types.Dictionary.Empty - .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress1.ByteArray, - Bencodex.Types.List.Empty - .Add(CouponsFixture.Guid1.ToByteArray())) - .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress2.ByteArray, - Bencodex.Types.List.Empty - .Add(CouponsFixture.Guid2.ToByteArray()) - .Add(CouponsFixture.Guid3.ToByteArray())) + actual.LoadPlainValue( + Dictionary.Empty + .Add("type_id", "transfer_coupons") + .Add( + "values", + new Bencodex.Types.Dictionary( + ImmutableDictionary.Empty .Add( - (Bencodex.Types.Binary)CouponsFixture.AgentAddress3.ByteArray, - Bencodex.Types.List.Empty))) - .SetItem("id", new Guid("AE3FA099-B97C-480F-9E3A-4E1FEF1EA783").Serialize()))); + "couponsPerRecipient", + Bencodex.Types.Dictionary.Empty + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress1.ByteArray, + Bencodex.Types.List.Empty + .Add(CouponsFixture.Guid1.ToByteArray())) + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress2.ByteArray, + Bencodex.Types.List.Empty + .Add(CouponsFixture.Guid2.ToByteArray()) + .Add(CouponsFixture.Guid3.ToByteArray())) + .Add( + (Bencodex.Types.Binary)CouponsFixture.AgentAddress3.ByteArray, + Bencodex.Types.List.Empty))) + .SetItem("id", new Guid("AE3FA099-B97C-480F-9E3A-4E1FEF1EA783").Serialize()))); Assert.Equal(expected.CouponsPerRecipient, actual.CouponsPerRecipient); } } diff --git a/.Lib9c.Tests/Action/CreateAvatarTest.cs b/.Lib9c.Tests/Action/CreateAvatarTest.cs index ac6edaede0..997645c1ea 100644 --- a/.Lib9c.Tests/Action/CreateAvatarTest.cs +++ b/.Lib9c.Tests/Action/CreateAvatarTest.cs @@ -60,13 +60,14 @@ public void Execute(long blockIndex) Assert.Equal(0 * CrystalCalculator.CRYSTAL, state.GetBalance(_agentAddress, CrystalCalculator.CRYSTAL)); - var nextState = action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = blockIndex, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = blockIndex, + RandomSeed = 0, + }); var avatarAddress = _agentAddress.Derive( string.Format( @@ -75,10 +76,11 @@ public void Execute(long blockIndex) 0 ) ); - Assert.True(nextState.TryGetAvatarState( - default, - avatarAddress, - out var nextAvatarState) + Assert.True( + nextState.TryGetAvatarState( + default, + avatarAddress, + out var nextAvatarState) ); var agentState = nextState.GetAgentState(default); Assert.NotNull(agentState); @@ -123,12 +125,14 @@ public void ExecuteThrowInvalidNamePatterException(string nickName) var state = new World(MockUtil.MockModernWorldState); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - BlockIndex = 0, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + BlockIndex = 0, + }) ); } @@ -163,12 +167,14 @@ public void ExecuteThrowInvalidAddressException() var state = new World(MockUtil.MockModernWorldState).SetAvatarState(avatarAddress, avatarState); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 0, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 0, + }) ); } @@ -189,12 +195,14 @@ public void ExecuteThrowAvatarIndexOutOfRangeException(int index) name = "test", }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 0, - }) + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 0, + }) ); } @@ -225,12 +233,14 @@ public void ExecuteThrowAvatarIndexAlreadyUsedException(int index) name = "test", }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 0, - }) + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 0, + }) ); } @@ -239,7 +249,8 @@ public void AddItem() { var itemSheet = _tableSheets.ItemSheet; var createAvatarItemSheet = new CreateAvatarItemSheet(); - createAvatarItemSheet.Set(@"item_id,count + createAvatarItemSheet.Set( + @"item_id,count 10112000,2 10512000,2 600201,2 @@ -263,7 +274,8 @@ public void AddItem() public void MintAsset() { var createAvatarFavSheet = new CreateAvatarFavSheet(); - createAvatarFavSheet.Set(@"currency,quantity,target + createAvatarFavSheet.Set( + @"currency,quantity,target CRYSTAL,200000,Agent RUNE_GOLDENLEAF,200000,Avatar "); diff --git a/.Lib9c.Tests/Action/CreatePendingActivationTest.cs b/.Lib9c.Tests/Action/CreatePendingActivationTest.cs index 4bb7cec032..756f786298 100644 --- a/.Lib9c.Tests/Action/CreatePendingActivationTest.cs +++ b/.Lib9c.Tests/Action/CreatePendingActivationTest.cs @@ -53,21 +53,23 @@ public void CheckPermission() .SetLegacyState(AdminState.Address, adminState.Serialize()); Assert.Throws( - () => action.Execute(new ActionContext() - { - BlockIndex = 101, - PreviousState = state, - Signer = adminAddress, - }) + () => action.Execute( + new ActionContext() + { + BlockIndex = 101, + PreviousState = state, + Signer = adminAddress, + }) ); Assert.Throws( - () => action.Execute(new ActionContext() - { - BlockIndex = 1, - PreviousState = state, - Signer = default, - }) + () => action.Execute( + new ActionContext() + { + BlockIndex = 1, + PreviousState = state, + Signer = default, + }) ); } } diff --git a/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs b/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs index 373441032a..002c4f2831 100644 --- a/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs +++ b/.Lib9c.Tests/Action/CreatePendingActivationsTest.cs @@ -58,8 +58,10 @@ public void PlainValue() var address = PendingActivationState.DeriveAddress(nonce, pubKey); var plainValue = Dictionary.Empty .Add("type_id", "create_pending_activations") - .Add("values", new List() - .Add(new List(address.Serialize(), (Binary)nonce, pubKey.Serialize()))); + .Add( + "values", + new List() + .Add(new List(address.Serialize(), (Binary)nonce, pubKey.Serialize()))); var action = new CreatePendingActivations(); action.LoadPlainValue(plainValue); @@ -84,21 +86,23 @@ public void CheckPermission() .SetLegacyState(AdminState.Address, adminState.Serialize()); Assert.Throws( - () => action.Execute(new ActionContext() - { - BlockIndex = 101, - PreviousState = state, - Signer = adminAddress, - }) + () => action.Execute( + new ActionContext() + { + BlockIndex = 101, + PreviousState = state, + Signer = adminAddress, + }) ); Assert.Throws( - () => action.Execute(new ActionContext() - { - BlockIndex = 1, - PreviousState = state, - Signer = default, - }) + () => action.Execute( + new ActionContext() + { + BlockIndex = 1, + PreviousState = state, + Signer = default, + }) ); } } diff --git a/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs b/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs index 8a9ad03710..44f2a03ee0 100644 --- a/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs +++ b/.Lib9c.Tests/Action/CustomEquipmentCraft/CustomEquipmentCraftTest.cs @@ -39,11 +39,12 @@ public class CustomEquipmentCraftTest public CustomEquipmentCraftTest() { _agentAddress = new PrivateKey().Address; - _avatarAddress = _agentAddress.Derive(string.Format( - CultureInfo.InvariantCulture, - CreateAvatar.DeriveFormat, - 0 - )); + _avatarAddress = _agentAddress.Derive( + string.Format( + CultureInfo.InvariantCulture, + CreateAvatar.DeriveFormat, + 0 + )); var sheets = TableSheetsImporter.ImportSheets(); _tableSheets = new TableSheets(sheets); _agentState = new AgentState(_agentAddress) @@ -55,7 +56,11 @@ public CustomEquipmentCraftTest() }; _avatarState = AvatarState.Create( - _avatarAddress, _agentAddress, 0, _tableSheets.GetAvatarSheets(), default + _avatarAddress, + _agentAddress, + 0, + _tableSheets.GetAvatarSheets(), + default ); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 @@ -74,11 +79,12 @@ public CustomEquipmentCraftTest() for (var i = 0; i < 4; i++) { - var slotAddress = _avatarAddress.Derive(string.Format( - CultureInfo.InvariantCulture, - CombinationSlotState.DeriveFormat, - i - )); + var slotAddress = _avatarAddress.Derive( + string.Format( + CultureInfo.InvariantCulture, + CombinationSlotState.DeriveFormat, + i + )); var combinationSlotState = new CombinationSlotState(slotAddress, 0); _initialState = _initialState .SetLegacyState(slotAddress, combinationSlotState.Serialize()); @@ -398,8 +404,9 @@ public void Execute( _avatarState.inventory.AddItem(circle, (int)Math.Floor(circleAmount)); - var nextRow = relationshipSheet.Values.FirstOrDefault(row => - row.Relationship == initialRelationship + 1); + var nextRow = relationshipSheet.Values.FirstOrDefault( + row => + row.Relationship == initialRelationship + 1); if (nextRow is not null) { if (nextRow.GoldAmount > 0) @@ -429,16 +436,19 @@ public void Execute( if (slotOccupied) { // Lock slot. - var slotAddress = _avatarAddress.Derive(string.Format( - CultureInfo.InvariantCulture, - CombinationSlotState.DeriveFormat, - 0 - )); + var slotAddress = _avatarAddress.Derive( + string.Format( + CultureInfo.InvariantCulture, + CombinationSlotState.DeriveFormat, + 0 + )); state = state.SetLegacyState( slotAddress, new CombinationSlotState( ((Dictionary)new CombinationSlotState(slotAddress, 0).Serialize()) - .SetItem("unlockBlockIndex", 10.Serialize() + .SetItem( + "unlockBlockIndex", + 10.Serialize() ) ) .Serialize() @@ -453,23 +463,27 @@ public void Execute( if (exc is not null) { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - PreviousState = state, - BlockIndex = currentBlockIndex, - Signer = _agentAddress, - RandomSeed = seed, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + BlockIndex = currentBlockIndex, + Signer = _agentAddress, + RandomSeed = seed, + })); } else { - var resultState = action.Execute(new ActionContext - { - PreviousState = state, - BlockIndex = currentBlockIndex, - Signer = _agentAddress, - RandomSeed = seed, - }); + var resultState = action.Execute( + new ActionContext + { + PreviousState = state, + BlockIndex = currentBlockIndex, + Signer = _agentAddress, + RandomSeed = seed, + }); // Test var gold = resultState.GetGoldCurrency(); @@ -504,8 +518,9 @@ public void Execute( _tableSheets.CustomEquipmentCraftRelationshipSheet.OrderedList! .Last(row => row.Relationship <= initialRelationship) .GetItemId(itemSubType); - var equipment = inventory.Equipments.First(e => - e.ItemId == slotState.Result.itemUsable.ItemId); + var equipment = inventory.Equipments.First( + e => + e.ItemId == slotState.Result.itemUsable.ItemId); Assert.Equal(expectedEquipmentId, equipment.Id); Assert.True(equipment.ByCustomCraft); diff --git a/.Lib9c.Tests/Action/DailyRewardTest.cs b/.Lib9c.Tests/Action/DailyRewardTest.cs index 1a580d9318..0fdf35fe99 100644 --- a/.Lib9c.Tests/Action/DailyRewardTest.cs +++ b/.Lib9c.Tests/Action/DailyRewardTest.cs @@ -89,10 +89,11 @@ public void Execute_Throw_RequiredBlockIndexException( [Fact] public void Execute_Throw_InvalidAddressException() { - Assert.Throws(() => - ExecuteInternal( - new World(MockUtil.MockModernWorldState), - new PrivateKey().Address)); + Assert.Throws( + () => + ExecuteInternal( + new World(MockUtil.MockModernWorldState), + new PrivateKey().Address)); } private IWorld ExecuteInternal(IWorld previousStates, Address avatarAddress, long blockIndex = 0) @@ -102,13 +103,14 @@ private IWorld ExecuteInternal(IWorld previousStates, Address avatarAddress, lon avatarAddress = avatarAddress, }; - return dailyRewardAction.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousStates, - RandomSeed = 0, - Signer = _agentAddress, - }); + return dailyRewardAction.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousStates, + RandomSeed = 0, + Signer = _agentAddress, + }); } } } diff --git a/.Lib9c.Tests/Action/EndPledgeTest.cs b/.Lib9c.Tests/Action/EndPledgeTest.cs index 578b08ea56..e2dd816ecb 100644 --- a/.Lib9c.Tests/Action/EndPledgeTest.cs +++ b/.Lib9c.Tests/Action/EndPledgeTest.cs @@ -32,11 +32,12 @@ public void Execute(int balance) { AgentAddress = agent, }; - var nextState = action.Execute(new ActionContext - { - Signer = patron, - PreviousState = states, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = patron, + PreviousState = states, + }); Assert.Null(nextState.GetLegacyState(agent.GetPledgeAddress())); Assert.Equal(mead * 0, nextState.GetBalance(agent, mead)); if (balance > 0) @@ -60,11 +61,14 @@ public void Execute_Throw_Exception(bool invalidSigner, bool invalidAgent, Type AgentAddress = invalidAgent ? new PrivateKey().Address : agent, }; - Assert.Throws(exc, () => action.Execute(new ActionContext - { - Signer = invalidSigner ? new PrivateKey().Address : patron, - PreviousState = states, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + Signer = invalidSigner ? new PrivateKey().Address : patron, + PreviousState = states, + })); } } } diff --git a/.Lib9c.Tests/Action/EventConsumableItemCraftsTest.cs b/.Lib9c.Tests/Action/EventConsumableItemCraftsTest.cs index 1372340386..38256f55d9 100644 --- a/.Lib9c.Tests/Action/EventConsumableItemCraftsTest.cs +++ b/.Lib9c.Tests/Action/EventConsumableItemCraftsTest.cs @@ -99,15 +99,17 @@ private void Execute( var previousAvatarState = previousStates.GetAvatarState(_avatarAddress); var recipeSheet = previousStates.GetSheet(); - Assert.True(recipeSheet.TryGetValue( - eventConsumableItemRecipeId, - out var recipeRow)); + Assert.True( + recipeSheet.TryGetValue( + eventConsumableItemRecipeId, + out var recipeRow)); var materialItemSheet = previousStates.GetSheet(); foreach (var materialInfo in recipeRow.Materials) { - Assert.True(materialItemSheet.TryGetValue( - materialInfo.Id, - out var materialRow)); + Assert.True( + materialItemSheet.TryGetValue( + materialInfo.Id, + out var materialRow)); var material = ItemFactory.CreateItem(materialRow, new TestRandom()); previousAvatarState.inventory.AddItem(material, materialInfo.Count); @@ -136,13 +138,14 @@ private void Execute( SlotIndex = slotIndex, }; - var nextStates = action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - }); + var nextStates = action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + }); var allCombinationSlotState = nextStates.GetAllCombinationSlotState(_avatarAddress); var slotState = allCombinationSlotState.GetSlot(slotIndex); diff --git a/.Lib9c.Tests/Action/EventDungeonBattleTest.cs b/.Lib9c.Tests/Action/EventDungeonBattleTest.cs index 098f3f08f2..dd9b35f6d7 100644 --- a/.Lib9c.Tests/Action/EventDungeonBattleTest.cs +++ b/.Lib9c.Tests/Action/EventDungeonBattleTest.cs @@ -79,8 +79,9 @@ public void Execute_Success_Within_Event_Period( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); var contextBlockIndex = scheduleRow.StartBlockIndex; var nextStates = Execute( _initialStates, @@ -153,8 +154,9 @@ public void Execute_Success_With_Ticket_Purchase( eventDungeonInfoAddr, eventDungeonInfo.Serialize()); - Assert.True(previousStates.GetSheet() - .TryGetValue(eventScheduleId, out var newScheduleRow)); + Assert.True( + previousStates.GetSheet() + .TryGetValue(eventScheduleId, out var newScheduleRow)); var ncgHas = newScheduleRow.GetDungeonTicketCost( numberOfTicketPurchases, _ncgCurrency); @@ -193,12 +195,13 @@ public void Execute_Throw_InvalidActionFieldException_By_EventScheduleId( int eventDungeonId, int eventDungeonStageId) { - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId)); } [Theory] @@ -208,24 +211,27 @@ public void Execute_Throw_InvalidActionFieldException_By_ContextBlockIndex( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); var contextBlockIndex = scheduleRow.StartBlockIndex - 1; - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: contextBlockIndex)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: contextBlockIndex)); contextBlockIndex = scheduleRow.DungeonEndBlockIndex + 1; - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: contextBlockIndex)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: contextBlockIndex)); } [Theory] @@ -236,15 +242,17 @@ public void Execute_Throw_InvalidActionFieldException_By_EventDungeonId( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: scheduleRow.StartBlockIndex)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: scheduleRow.StartBlockIndex)); } [Theory] @@ -255,15 +263,17 @@ public void Execute_Throw_InvalidActionFieldException_By_EventDungeonStageId( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: scheduleRow.StartBlockIndex)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: scheduleRow.StartBlockIndex)); } [Theory] @@ -279,15 +289,17 @@ public void Execute_Throw_NotEnoughEventDungeonTicketsException( var eventDungeonInfo = new EventDungeonInfo(); previousStates = previousStates .SetLegacyState(eventDungeonInfoAddr, eventDungeonInfo.Serialize()); - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); - Assert.Throws(() => - Execute( - previousStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: scheduleRow.StartBlockIndex)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.Throws( + () => + Execute( + previousStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: scheduleRow.StartBlockIndex)); } [Theory] @@ -309,8 +321,9 @@ public void Execute_Throw_InsufficientBalanceException( previousStates = previousStates .SetLegacyState(eventDungeonInfoAddr, eventDungeonInfo.Serialize()); - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); var ncgHas = scheduleRow.GetDungeonTicketCost( numberOfTicketPurchases, _ncgCurrency) - 1 * _ncgCurrency; @@ -319,14 +332,15 @@ public void Execute_Throw_InsufficientBalanceException( previousStates = previousStates.MintAsset(context, _agentAddress, ncgHas); } - Assert.Throws(() => - Execute( - previousStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - true, - scheduleRow.StartBlockIndex)); + Assert.Throws( + () => + Execute( + previousStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + true, + scheduleRow.StartBlockIndex)); } [Theory] @@ -336,15 +350,17 @@ public void Execute_Throw_StageNotClearedException( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); - Assert.Throws(() => - Execute( - _initialStates, - eventScheduleId, - eventDungeonId, - eventDungeonStageId, - blockIndex: scheduleRow.StartBlockIndex)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.Throws( + () => + Execute( + _initialStates, + eventScheduleId, + eventDungeonId, + eventDungeonStageId, + blockIndex: scheduleRow.StartBlockIndex)); } [Theory] @@ -352,8 +368,9 @@ public void Execute_Throw_StageNotClearedException( [InlineData(1, 10002, 1, 30001, typeof(DuplicatedRuneSlotIndexException))] public void Execute_DuplicatedException(int slotIndex, int runeId, int slotIndex2, int runeId2, Type exception) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(1001, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(1001, out var scheduleRow)); var context = new ActionContext(); _initialStates = _initialStates.MintAsset(context, _agentAddress, 99999 * _ncgCurrency); @@ -364,26 +381,29 @@ public void Execute_DuplicatedException(int slotIndex, int runeId, int slotIndex SlotIndex = 1, }; - _initialStates = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = _initialStates, - Signer = _agentAddress, - RandomSeed = 0, - }); - - Assert.Throws(exception, () => - Execute( - _initialStates, - 1001, - 10010001, - 10010001, - false, - scheduleRow.StartBlockIndex, - slotIndex, - runeId, - slotIndex2, - runeId2)); + _initialStates = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = _initialStates, + Signer = _agentAddress, + RandomSeed = 0, + }); + + Assert.Throws( + exception, + () => + Execute( + _initialStates, + 1001, + 10010001, + 10010001, + false, + scheduleRow.StartBlockIndex, + slotIndex, + runeId, + slotIndex2, + runeId2)); } [Fact] @@ -437,8 +457,9 @@ public void CheckRewardItems( int eventDungeonId, int eventDungeonStageId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); var contextBlockIndex = scheduleRow.StartBlockIndex; var avatarState = _initialStates.GetAvatarState(_avatarAddress); @@ -464,13 +485,14 @@ public void CheckRewardItems( BuyTicketIfNeeded = false, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = contextBlockIndex, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = contextBlockIndex, + }); var nextAvatar = nextState.GetAvatarState(_avatarAddress); var stageSheet = nextState.GetSheet(); @@ -528,17 +550,19 @@ private IWorld Execute( BuyTicketIfNeeded = buyTicketIfNeeded, }; - var nextStates = action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - }); + var nextStates = action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + }); - Assert.True(nextStates.GetSheet().TryGetValue( - eventScheduleId, - out var scheduleRow)); + Assert.True( + nextStates.GetSheet().TryGetValue( + eventScheduleId, + out var scheduleRow)); var nextAvatarState = nextStates.GetAvatarState(_avatarAddress); var expectExp = scheduleRow.GetStageExp( eventDungeonStageId.ToEventDungeonStageNumber()); diff --git a/.Lib9c.Tests/Action/EventMaterialItemCraftsTest.cs b/.Lib9c.Tests/Action/EventMaterialItemCraftsTest.cs index 48745fa44d..3e922c72f7 100644 --- a/.Lib9c.Tests/Action/EventMaterialItemCraftsTest.cs +++ b/.Lib9c.Tests/Action/EventMaterialItemCraftsTest.cs @@ -134,8 +134,9 @@ public void Execute_Success( int eventScheduleId, int eventMaterialItemRecipeId) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(eventScheduleId, out var scheduleRow)); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(eventScheduleId, out var scheduleRow)); var materialsToUse = new Dictionary(); var totalCount = 0; var row = _tableSheets.EventMaterialItemRecipeSheet[eventMaterialItemRecipeId]; @@ -176,17 +177,19 @@ public void Execute_InvalidMaterialCountException( int eventMaterialItemRecipeId, Dictionary materialsToUse) { - Assert.True(_tableSheets.EventScheduleSheet - .TryGetValue(1002, out var scheduleRow)); - Assert.Throws(() => - { - Execute( - _initialStates, - eventScheduleId, - eventMaterialItemRecipeId, - materialsToUse, - scheduleRow.StartBlockIndex); - }); + Assert.True( + _tableSheets.EventScheduleSheet + .TryGetValue(1002, out var scheduleRow)); + Assert.Throws( + () => + { + Execute( + _initialStates, + eventScheduleId, + eventMaterialItemRecipeId, + materialsToUse, + scheduleRow.StartBlockIndex); + }); } private void Execute( @@ -232,13 +235,14 @@ private void Execute( MaterialsToUse = materialsToUse, }; - var nextStates = action.Execute(new ActionContext - { - PreviousState = previousStates, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - }); + var nextStates = action.Execute( + new ActionContext + { + PreviousState = previousStates, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + }); var nextAvatarState = nextStates.GetAvatarState(_avatarAddress); diff --git a/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs b/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs index c559d7844f..0ec3c9e726 100644 --- a/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs +++ b/.Lib9c.Tests/Action/Factory/ClaimStakeRewardFactoryTest.cs @@ -19,11 +19,13 @@ public class ClaimStakeRewardFactoryTest public static IEnumerable GetAllClaimStakeRewardV1() { var arr = Assembly.GetAssembly(typeof(ClaimRaidReward))?.GetTypes() - .Where(type => - type.IsClass && - typeof(IClaimStakeRewardV1).IsAssignableFrom(type)) - .Select(type => - type.GetCustomAttribute()?.TypeIdentifier) + .Where( + type => + type.IsClass && + typeof(IClaimStakeRewardV1).IsAssignableFrom(type)) + .Select( + type => + type.GetCustomAttribute()?.TypeIdentifier) .OfType() .ToArray() ?? Array.Empty(); diff --git a/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs b/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs index 07cd4221ff..f1bd35ae67 100644 --- a/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs @@ -97,12 +97,14 @@ public void Serialize( actionData.recipientAvatarAddress, deserializedData.recipientAvatarAddress); Assert.True( - actionData.fungibleAssetValues?.SequenceEqual(deserializedData - .fungibleAssetValues!) + actionData.fungibleAssetValues?.SequenceEqual( + deserializedData + .fungibleAssetValues!) ?? deserializedData.fungibleAssetValues is null); Assert.True( - actionData.fungibleIdAndCounts?.SequenceEqual(deserializedData - .fungibleIdAndCounts!) + actionData.fungibleIdAndCounts?.SequenceEqual( + deserializedData + .fungibleIdAndCounts!) ?? deserializedData.fungibleIdAndCounts is null); Assert.Equal(actionData.memo, deserializedData.memo); } @@ -115,13 +117,14 @@ public void Execute_Success() const long blockIndex = 0L; var (states, unloadDataEnumerable) = RegisterPlainValue(_previousStates); var action = new BulkUnloadFromGarages(new[] { unloadDataEnumerable, }); - states = action.Execute(new ActionContext - { - Signer = AgentAddress, - BlockIndex = blockIndex, - PreviousState = states, - RandomSeed = new TestRandom().Seed, - }); + states = action.Execute( + new ActionContext + { + Signer = AgentAddress, + BlockIndex = blockIndex, + PreviousState = states, + RandomSeed = new TestRandom().Seed, + }); // Test fungibleAssetValues var unloadData = action.UnloadData.ToArray(); @@ -158,9 +161,11 @@ public void Execute_Success() var mail = Assert.IsType(mailBox.First()); Assert.Equal(blockIndex, mail.blockIndex); Assert.Equal(blockIndex, mail.requiredBlockIndex); - Assert.True(action.UnloadData[0].fungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? + Assert.True( + action.UnloadData[0].fungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? mail.FungibleAssetValues is null); - Assert.True(action.UnloadData[0].fungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? + Assert.True( + action.UnloadData[0].fungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? mail.FungibleIdAndCounts is null); Assert.Equal(action.UnloadData[0].memo, mail.Memo); } @@ -173,11 +178,12 @@ private static (Address balanceAddr, FungibleAssetValue value)[] return CurrenciesTest.GetSampleCurrencies() .Select(objects => (FungibleAssetValue)objects[0]) .Where(fav => fav.Sign > 0) - .Select(fav => - { - var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); - return (recipient, fav); - }) + .Select( + fav => + { + var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); + return (recipient, fav); + }) .ToArray(); } @@ -195,15 +201,16 @@ private static (Address balanceAddr, FungibleAssetValue value)[] var fungibleItemAndCounts = _tableSheets.MaterialItemSheet.OrderedList! .Take(3) .Select(ItemFactory.CreateMaterial) - .Select((material, index) => - { - var garageAddress = - Addresses.GetGarageAddress(AgentAddress, material.FungibleId); - var count = index + 1; - var garage = new FungibleItemGarage(material, count); - states = states.SetLegacyState(garageAddress, garage.Serialize()); - return (FungibleItem: (IFungibleItem)material, count); - }) + .Select( + (material, index) => + { + var garageAddress = + Addresses.GetGarageAddress(AgentAddress, material.FungibleId); + var count = index + 1; + var garage = new FungibleItemGarage(material, count); + states = states.SetLegacyState(garageAddress, garage.Serialize()); + return (FungibleItem: (IFungibleItem)material, count); + }) .ToArray(); var fungibleItemIdAndCounts = fungibleItemAndCounts .Select(tuple => (fungibleId: tuple.FungibleItem.FungibleId, tuple.count)) diff --git a/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs b/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs index 6fcd064689..f48272aae9 100644 --- a/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/DeliverToOthersGaragesTest.cs @@ -101,9 +101,11 @@ public void Serialize( var des = new DeliverToOthersGarages(); des.LoadPlainValue(ser); Assert.Equal(action.RecipientAgentAddr, des.RecipientAgentAddr); - Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? + Assert.True( + action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? des.FungibleAssetValues is null); - Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? + Assert.True( + action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); Assert.Equal(ser, des.PlainValue); @@ -177,38 +179,42 @@ public void Execute_Success() public void Execute_Throws_InvalidActionFieldException() { // FungibleAssetValues and FungibleIdAndCounts are null. - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAgentAddr, - null, - null)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAgentAddr, + null, + null)); // FungibleAssetValues contains negative value. var negativeFungibleAssetValues = _fungibleAssetValues.Select(fav => fav * -1); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAgentAddr, - negativeFungibleAssetValues, - null)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAgentAddr, + negativeFungibleAssetValues, + null)); // Count of fungible id is negative. - var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select(tuple => ( - tuple.fungibleId, - tuple.count * -1)); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAgentAddr, - null, - negativeFungibleIdAndCounts)); + var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select( + tuple => ( + tuple.fungibleId, + tuple.count * -1)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAgentAddr, + null, + negativeFungibleIdAndCounts)); } [Fact] @@ -227,14 +233,15 @@ public void Execute_Throws_Exception() vaf); } - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - previousStatesWithEmptyBalances, - new TestRandom(), - _recipientAgentAddr, - _fungibleAssetValues, - null)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + previousStatesWithEmptyBalances, + new TestRandom(), + _recipientAgentAddr, + _fungibleAssetValues, + null)); // Sender's fungible item Garage state is null. foreach (var (fungibleId, _) in _fungibleIdAndCounts) @@ -244,14 +251,15 @@ public void Execute_Throws_Exception() fungibleId); var previousStatesWithNullGarageState = _previousStates.RemoveLegacyState(garageAddr); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - previousStatesWithNullGarageState, - new TestRandom(), - _recipientAgentAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + previousStatesWithNullGarageState, + new TestRandom(), + _recipientAgentAddr, + null, + _fungibleIdAndCounts)); } // Mismatch fungible id between sender's and recipient's fungible item Garage. @@ -263,14 +271,15 @@ public void Execute_Throws_Exception() var garage = new FungibleItemGarage(_fungibleItems[nextIndex], 1); var previousStatesWithInvalidGarageState = _previousStates.SetLegacyState(addr, garage.Serialize()); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - previousStatesWithInvalidGarageState, - new TestRandom(), - _recipientAgentAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + previousStatesWithInvalidGarageState, + new TestRandom(), + _recipientAgentAddr, + null, + _fungibleIdAndCounts)); } // Sender's fungible item Garage does not contain enough items. @@ -285,14 +294,15 @@ public void Execute_Throws_Exception() var previousStatesWithNotEnoughCountOfGarageState = _previousStates.SetLegacyState(garageAddr, garage.Serialize()); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - previousStatesWithNotEnoughCountOfGarageState, - new TestRandom(), - _recipientAgentAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + previousStatesWithNotEnoughCountOfGarageState, + new TestRandom(), + _recipientAgentAddr, + null, + _fungibleIdAndCounts)); } // Recipient's fungible item Garages can be overflowed. @@ -303,14 +313,15 @@ public void Execute_Throws_Exception() var garage = new FungibleItemGarage(_fungibleItems[i], int.MaxValue); var previousStatesWithInvalidGarageState = _previousStates.SetLegacyState(addr, garage.Serialize()); - Assert.Throws(() => Execute( - SenderAgentAddr, - 0, - previousStatesWithInvalidGarageState, - new TestRandom(), - _recipientAgentAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + SenderAgentAddr, + 0, + previousStatesWithInvalidGarageState, + new TestRandom(), + _recipientAgentAddr, + null, + _fungibleIdAndCounts)); } } @@ -331,13 +342,14 @@ private static (DeliverToOthersGarages action, IWorld nextStates) Execute( memo); return ( action, - action.Execute(new ActionContext - { - Signer = signer, - BlockIndex = blockIndex, - PreviousState = previousState, - RandomSeed = random.Seed, - })); + action.Execute( + new ActionContext + { + Signer = signer, + BlockIndex = blockIndex, + PreviousState = previousState, + RandomSeed = random.Seed, + })); } private static FungibleAssetValue[] GetFungibleAssetValues() diff --git a/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs b/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs index 6b74266889..e5e753cb16 100644 --- a/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/LoadIntoMyGaragesTest.cs @@ -111,10 +111,12 @@ public void Serialize( var ser = action.PlainValue; var des = new LoadIntoMyGarages(); des.LoadPlainValue(ser); - Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? + Assert.True( + action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? des.FungibleAssetValues is null); Assert.Equal(action.AvatarAddr, des.AvatarAddr); - Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? + Assert.True( + action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); Assert.Equal(ser, des.PlainValue); @@ -175,10 +177,11 @@ public void Execute_Success() var inventory = avatarState.inventory; foreach (var (fungibleId, count) in action.FungibleIdAndCounts) { - Assert.False(inventory.HasFungibleItem( - fungibleId, - 0, - 1)); + Assert.False( + inventory.HasFungibleItem( + fungibleId, + 0, + 1)); var garageAddr = Addresses.GetGarageAddress( AgentAddr, fungibleId); @@ -193,72 +196,80 @@ public void Execute_Success() public void Execute_Throws_InvalidActionFieldException() { // FungibleAssetValues and FungibleIdAndCounts are null. - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - null, - null, - null)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + null, + null, + null)); // Signer does not have permission of balance address. var invalidSignerAddr = new PrivateKey().Address; - Assert.Throws(() => Execute( - invalidSignerAddr, - 0, - _previousStates, - new TestRandom(), - _fungibleAssetValues, - null, - null)); + Assert.Throws( + () => Execute( + invalidSignerAddr, + 0, + _previousStates, + new TestRandom(), + _fungibleAssetValues, + null, + null)); // FungibleAssetValues contains negative value. - var negativeFungibleAssetValues = _fungibleAssetValues.Select(tuple => ( - tuple.balanceAddr, - tuple.value * -1)); - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - negativeFungibleAssetValues, - null, - null)); + var negativeFungibleAssetValues = _fungibleAssetValues.Select( + tuple => ( + tuple.balanceAddr, + tuple.value * -1)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + negativeFungibleAssetValues, + null, + null)); // InventoryAddr is null when FungibleIdAndCounts is not null. - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - null, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + null, + null, + _fungibleIdAndCounts)); // AgentAddr does not have permission of inventory address. var invalidInventoryAddr = new PrivateKey().Address; - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - null, - invalidInventoryAddr, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + null, + invalidInventoryAddr, + _fungibleIdAndCounts)); // Count of fungible id is negative. - var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select(tuple => ( - tuple.fungibleId, - tuple.count * -1)); - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - null, - _avatarAddress, - negativeFungibleIdAndCounts)); + var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select( + tuple => ( + tuple.fungibleId, + tuple.count * -1)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + null, + _avatarAddress, + negativeFungibleIdAndCounts)); } [Fact] @@ -270,14 +281,15 @@ public void Execute_Throws_Exception() new ActionContext { Signer = AgentAddr, }, AgentAddr, balance); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithNotEnoughCost, - new TestRandom(), - _fungibleAssetValues, - _avatarAddress, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithNotEnoughCost, + new TestRandom(), + _fungibleAssetValues, + _avatarAddress, + _fungibleIdAndCounts)); // Balance does not enough to send. var previousStatesWithEmptyBalances = _previousStates; @@ -289,14 +301,15 @@ public void Execute_Throws_Exception() value); } - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithEmptyBalances, - new TestRandom(), - _fungibleAssetValues, - null, - null)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithEmptyBalances, + new TestRandom(), + _fungibleAssetValues, + null, + null)); AvatarState avatarState; @@ -305,14 +318,15 @@ public void Execute_Throws_Exception() avatarState.inventory = new Inventory(); var previousStatesWithEmptyInventoryState = _previousStates.SetAvatarState(_avatarAddress, avatarState); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithEmptyInventoryState, - new TestRandom(), - null, - _avatarAddress, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithEmptyInventoryState, + new TestRandom(), + null, + _avatarAddress, + _fungibleIdAndCounts)); // Inventory does not have enough tradable fungible item. avatarState = _previousStates.GetAvatarState(_avatarAddress); @@ -327,14 +341,15 @@ public void Execute_Throws_Exception() var previousStatesWithNotEnoughInventoryState = _previousStates.SetAvatarState(_avatarAddress, avatarState); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithNotEnoughInventoryState, - new TestRandom(), - null, - _avatarAddress, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithNotEnoughInventoryState, + new TestRandom(), + null, + _avatarAddress, + _fungibleIdAndCounts)); // Fungible item garage's item mismatch with fungible id. for (var i = 0; i < _fungibleIdAndCounts.Length; i++) @@ -345,14 +360,15 @@ public void Execute_Throws_Exception() var garage = new FungibleItemGarage(_fungibleItems[nextIndex], 1); var previousStatesWithInvalidGarageState = _previousStates.SetLegacyState(addr, garage.Serialize()); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithInvalidGarageState, - new TestRandom(), - null, - _avatarAddress, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithInvalidGarageState, + new TestRandom(), + null, + _avatarAddress, + _fungibleIdAndCounts)); } // Fungible item garages can be overflowed. @@ -363,14 +379,15 @@ public void Execute_Throws_Exception() var garage = new FungibleItemGarage(_fungibleItems[i], int.MaxValue); var previousStatesWithInvalidGarageState = _previousStates.SetLegacyState(addr, garage.Serialize()); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithInvalidGarageState, - new TestRandom(), - null, - _avatarAddress, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithInvalidGarageState, + new TestRandom(), + null, + _avatarAddress, + _fungibleIdAndCounts)); } } @@ -407,17 +424,19 @@ private static (Address balanceAddr, FungibleAssetValue value)[] { return CurrenciesTest.GetSampleCurrencies() .Select(objects => (FungibleAssetValue)objects[0]) - .Where(fav => - (tableSheets?.LoadIntoMyGaragesCostSheet.HasCost(fav.Currency.Ticker) ?? - true) && - fav.Sign > 0) - .Select(fav => - { - // CRYSTAL's minorUnit is not actually used in network, avoid cost calculate exception in test. - var value = 1 * fav.Currency; - var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); - return (recipient, value); - }) + .Where( + fav => + (tableSheets?.LoadIntoMyGaragesCostSheet.HasCost(fav.Currency.Ticker) ?? + true) && + fav.Sign > 0) + .Select( + fav => + { + // CRYSTAL's minorUnit is not actually used in network, avoid cost calculate exception in test. + var value = 1 * fav.Currency; + var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); + return (recipient, value); + }) .ToArray(); } @@ -457,16 +476,18 @@ private static (Address balanceAddr, FungibleAssetValue value)[] var inventory = avatarState.inventory; var fungibleItemAndCounts = _tableSheets.MaterialItemSheet.OrderedList! .Where(row => _tableSheets.LoadIntoMyGaragesCostSheet.HasCost(row.ItemId)) - .Select(row => _nonTradableIds.Contains(row.Id) - ? ItemFactory.CreateMaterial(row) - : ItemFactory.CreateTradableMaterial(row)) - .Select((material, index) => - { - inventory.AddFungibleItem((ItemBase)material, index + 1); - return ( - fungibleItem: (IFungibleItem)material, - count: index + 1); - }).ToArray(); + .Select( + row => _nonTradableIds.Contains(row.Id) + ? ItemFactory.CreateMaterial(row) + : ItemFactory.CreateTradableMaterial(row)) + .Select( + (material, index) => + { + inventory.AddFungibleItem((ItemBase)material, index + 1); + return ( + fungibleItem: (IFungibleItem)material, + count: index + 1); + }).ToArray(); var garageCost = _tableSheets.LoadIntoMyGaragesCostSheet.GetGarageCost( fungibleAssetValues.Select(tuple => tuple.value), fungibleItemAndCounts diff --git a/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs b/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs index dae68f4ba7..42c9c461b4 100644 --- a/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs +++ b/.Lib9c.Tests/Action/Garages/UnloadFromMyGaragesTest.cs @@ -107,9 +107,11 @@ public void Serialize( var des = new UnloadFromMyGarages(); des.LoadPlainValue(ser); Assert.Equal(action.RecipientAvatarAddr, des.RecipientAvatarAddr); - Assert.True(action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? + Assert.True( + action.FungibleAssetValues?.SequenceEqual(des.FungibleAssetValues!) ?? des.FungibleAssetValues is null); - Assert.True(action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? + Assert.True( + action.FungibleIdAndCounts?.SequenceEqual(des.FungibleIdAndCounts!) ?? des.FungibleIdAndCounts is null); Assert.Equal(action.Memo, des.Memo); @@ -166,10 +168,11 @@ public void Execute_Success() AgentAddr, fungibleId); Assert.Equal(0, new FungibleItemGarage(nextStates.GetLegacyState(garageAddr)).Count); - Assert.True(avatarState.inventory.HasFungibleItem( - fungibleId, - 0, - count)); + Assert.True( + avatarState.inventory.HasFungibleItem( + fungibleId, + 0, + count)); } } @@ -178,9 +181,11 @@ public void Execute_Success() var mail = Assert.IsType(mailBox.First()); Assert.Equal(blockIndex, mail.blockIndex); Assert.Equal(blockIndex, mail.requiredBlockIndex); - Assert.True(action.FungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? + Assert.True( + action.FungibleAssetValues?.SequenceEqual(mail.FungibleAssetValues!) ?? mail.FungibleAssetValues is null); - Assert.True(action.FungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? + Assert.True( + action.FungibleIdAndCounts?.SequenceEqual(mail.FungibleIdAndCounts!) ?? mail.FungibleIdAndCounts is null); Assert.Equal(action.Memo, mail.Memo); } @@ -189,39 +194,44 @@ public void Execute_Success() public void Execute_Throws_InvalidActionFieldException() { // FungibleAssetValues and FungibleIdAndCounts are null. - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAvatarAddr, - null, - null)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAvatarAddr, + null, + null)); // FungibleAssetValues contains negative value. - var negativeFungibleAssetValues = _fungibleAssetValues.Select(tuple => - (tuple.balanceAddr, tuple.value * -1)); - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAvatarAddr, - negativeFungibleAssetValues, - null)); + var negativeFungibleAssetValues = _fungibleAssetValues.Select( + tuple => + (tuple.balanceAddr, tuple.value * -1)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAvatarAddr, + negativeFungibleAssetValues, + null)); // Count of fungible id is negative. - var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select(tuple => ( - tuple.fungibleId, - tuple.count * -1)); - Assert.Throws(() => Execute( - AgentAddr, - 0, - _previousStates, - new TestRandom(), - _recipientAvatarAddr, - null, - negativeFungibleIdAndCounts)); + var negativeFungibleIdAndCounts = _fungibleIdAndCounts.Select( + tuple => ( + tuple.fungibleId, + tuple.count * -1)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + _previousStates, + new TestRandom(), + _recipientAvatarAddr, + null, + negativeFungibleIdAndCounts)); } [Fact] @@ -239,14 +249,15 @@ public void Execute_Throws_Exception() value); } - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithEmptyBalances, - new TestRandom(), - _recipientAvatarAddr, - _fungibleAssetValues, - null)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithEmptyBalances, + new TestRandom(), + _recipientAvatarAddr, + _fungibleAssetValues, + null)); // Agent's fungible item garage state is null. foreach (var (fungibleId, _) in _fungibleIdAndCounts) @@ -256,14 +267,15 @@ public void Execute_Throws_Exception() fungibleId); var previousStatesWithNullGarageState = _previousStates.RemoveLegacyState(garageAddr); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithNullGarageState, - new TestRandom(), - _recipientAvatarAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithNullGarageState, + new TestRandom(), + _recipientAvatarAddr, + null, + _fungibleIdAndCounts)); } // Agent's fungible item garage does not contain enough items. @@ -278,14 +290,15 @@ public void Execute_Throws_Exception() var previousStatesWithNotEnoughCountOfGarageState = _previousStates.SetLegacyState(garageAddr, garage.Serialize()); - Assert.Throws(() => Execute( - AgentAddr, - 0, - previousStatesWithNotEnoughCountOfGarageState, - new TestRandom(), - _recipientAvatarAddr, - null, - _fungibleIdAndCounts)); + Assert.Throws( + () => Execute( + AgentAddr, + 0, + previousStatesWithNotEnoughCountOfGarageState, + new TestRandom(), + _recipientAvatarAddr, + null, + _fungibleIdAndCounts)); } } @@ -306,13 +319,14 @@ private static (UnloadFromMyGarages action, IWorld nextStates) Execute( memo); return ( action, - action.Execute(new ActionContext - { - Signer = signer, - BlockIndex = blockIndex, - PreviousState = previousState, - RandomSeed = random.Seed, - })); + action.Execute( + new ActionContext + { + Signer = signer, + BlockIndex = blockIndex, + PreviousState = previousState, + RandomSeed = random.Seed, + })); } private static (Address balanceAddr, FungibleAssetValue value)[] @@ -323,11 +337,12 @@ private static (Address balanceAddr, FungibleAssetValue value)[] return CurrenciesTest.GetSampleCurrencies() .Select(objects => (FungibleAssetValue)objects[0]) .Where(fav => fav.Sign > 0) - .Select(fav => - { - var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); - return (recipient, fav); - }) + .Select( + fav => + { + var recipient = Currencies.PickAddress(fav.Currency, agentAddr, avatarAddr); + return (recipient, fav); + }) .ToArray(); } @@ -366,19 +381,20 @@ private static (Address balanceAddr, FungibleAssetValue value)[] var fungibleItemAndCounts = _tableSheets.MaterialItemSheet.OrderedList! .Take(3) .Select(ItemFactory.CreateMaterial) - .Select((material, index) => - { - var garageAddr = Addresses.GetGarageAddress( - AgentAddr, - material.FungibleId); - var count = index + 1; - var garage = new FungibleItemGarage(material, count); - previousStates = previousStates.SetLegacyState( - garageAddr, - garage.Serialize()); + .Select( + (material, index) => + { + var garageAddr = Addresses.GetGarageAddress( + AgentAddr, + material.FungibleId); + var count = index + 1; + var garage = new FungibleItemGarage(material, count); + previousStates = previousStates.SetLegacyState( + garageAddr, + garage.Serialize()); - return (fungibleItem: (IFungibleItem)material, count); - }).ToArray(); + return (fungibleItem: (IFungibleItem)material, count); + }).ToArray(); return ( recipientAvatarAddr: AvatarAddr, fungibleAssetValues, diff --git a/.Lib9c.Tests/Action/GoldDistributionTest.cs b/.Lib9c.Tests/Action/GoldDistributionTest.cs index 012cc71521..f553a1b31c 100644 --- a/.Lib9c.Tests/Action/GoldDistributionTest.cs +++ b/.Lib9c.Tests/Action/GoldDistributionTest.cs @@ -9,28 +9,28 @@ public class GoldDistributionTest { public static readonly GoldDistribution[] Fixture = { - new() + new () { Address = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), AmountPerBlock = 100, StartBlock = 1, EndBlock = 100000, }, - new() + new () { Address = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"), AmountPerBlock = 3000, StartBlock = 3600, EndBlock = 13600, }, - new() + new () { Address = new Address("Fb90278C67f9b266eA309E6AE8463042f5461449"), AmountPerBlock = 100000000000, StartBlock = 2, EndBlock = 2, }, - new() + new () { Address = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"), AmountPerBlock = 1000000, @@ -44,7 +44,8 @@ public static string CreateFixtureCsvFile() var csvPath = Path.GetTempFileName(); using (var writer = File.CreateText(csvPath)) { - writer.Write(@"Address,AmountPerBlock,StartBlock,EndBlock + writer.Write( + @"Address,AmountPerBlock,StartBlock,EndBlock F9A15F870701268Bd7bBeA6502eB15F4997f32f9,1000000,0,0 F9A15F870701268Bd7bBeA6502eB15F4997f32f9,100,1,100000 Fb90278C67f9b266eA309E6AE8463042f5461449,3000,3600,13600 diff --git a/.Lib9c.Tests/Action/GrindingTest.cs b/.Lib9c.Tests/Action/GrindingTest.cs index ad9fa8c231..2b55f2bc66 100644 --- a/.Lib9c.Tests/Action/GrindingTest.cs +++ b/.Lib9c.Tests/Action/GrindingTest.cs @@ -201,8 +201,9 @@ Type exc if (chargeAp && apStoneExist) { - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateMaterial(row); _avatarState.inventory.AddItem(apStone); } @@ -217,8 +218,10 @@ Type exc } else { - Assert.Throws(exc, () => - Execute(state, _agentAddress, _avatarAddress, 1, chargeAp, _random, totalAsset, totalRewardCount, _tableSheets.MaterialItemSheet)); + Assert.Throws( + exc, + () => + Execute(state, _agentAddress, _avatarAddress, 1, chargeAp, _random, totalAsset, totalRewardCount, _tableSheets.MaterialItemSheet)); } } @@ -241,8 +244,9 @@ public void Execute_Throw_InvalidItemCountException(int equipmentCount) Assert.Equal(0 * _crystalCurrency, state.GetBalance(_avatarAddress, _crystalCurrency)); - Assert.Throws(() => - Execute(state, _agentAddress, _avatarAddress, equipmentCount, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); + Assert.Throws( + () => + Execute(state, _agentAddress, _avatarAddress, equipmentCount, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); } [Theory] @@ -269,8 +273,9 @@ public void Execute_Throw_FailedLoadStateException(bool agentExist, bool avatarE Assert.Equal(0 * _crystalCurrency, state.GetBalance(_avatarAddress, _crystalCurrency)); } - Assert.Throws(() => - Execute(state, _agentAddress, _avatarAddress, 1, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); + Assert.Throws( + () => + Execute(state, _agentAddress, _avatarAddress, 1, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); } [Theory] @@ -303,8 +308,10 @@ public void Execute_Throw_Equipment_Exception(bool equipmentExist, long required Assert.Equal(0 * _crystalCurrency, state.GetBalance(_avatarAddress, _crystalCurrency)); - Assert.Throws(exc, () => - Execute(state, _agentAddress, _avatarAddress, 1, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); + Assert.Throws( + exc, + () => + Execute(state, _agentAddress, _avatarAddress, 1, false, _random, 0, 0, _tableSheets.MaterialItemSheet)); } [Theory] @@ -366,13 +373,14 @@ private static IWorld Execute( ChargeAp = chargeAp, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = prevStates, - Signer = agentAddress, - BlockIndex = 1, - RandomSeed = random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = prevStates, + Signer = agentAddress, + BlockIndex = 1, + RandomSeed = random.Seed, + }); var crystalCurrency = Currencies.Crystal; // CrystalCurrencyState.Address; var nextAvatarState = nextState.GetAvatarState(avatarAddress); @@ -396,7 +404,7 @@ private static IWorld Execute( private class CalculateMaterialRewardData : IEnumerable { - private readonly List _data = new() + private readonly List _data = new () { new object[] { diff --git a/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs index f88b49fb43..3f5633d8b7 100644 --- a/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/AcceptGuildApplicationTest.cs @@ -37,43 +37,49 @@ public void Execute() // These cases should fail because the member didn't apply the guild and // non-guild-master-addresses cannot accept the guild application. Assert.Throws( - () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - })); + () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + })); Assert.Throws( - () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = appliedMemberAddress, - })); + () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = appliedMemberAddress, + })); Assert.Throws( - () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = nonAppliedMemberAddress, - })); + () => new AcceptGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = nonAppliedMemberAddress, + })); // These cases should fail because non-guild-master-addresses cannot accept the guild application. Assert.Throws( - () => new AcceptGuildApplication(appliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = appliedMemberAddress, - })); + () => new AcceptGuildApplication(appliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = appliedMemberAddress, + })); Assert.Throws( - () => new AcceptGuildApplication(appliedMemberAddress).Execute(new ActionContext + () => new AcceptGuildApplication(appliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = nonAppliedMemberAddress, + })); + + world = new AcceptGuildApplication(appliedMemberAddress).Execute( + new ActionContext { PreviousState = world, - Signer = nonAppliedMemberAddress, - })); - - world = new AcceptGuildApplication(appliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + Signer = guildMasterAddress, + }); Assert.False(world.TryGetGuildApplication(appliedMemberAddress, out _)); Assert.Equal(guildAddress, world.GetJoinedGuild(appliedMemberAddress)); diff --git a/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs b/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs index 6e56f5989a..4b0429e2b3 100644 --- a/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/ApplyGuildTest.cs @@ -37,17 +37,20 @@ public void Execute() var bannedWorld = world.Ban(guildAddress, guildMasterAddress, agentAddress); // This case should fail because the agent is banned by the guild. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = bannedWorld, - Signer = agentAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = bannedWorld, + Signer = agentAddress, + })); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + }); Assert.True(world.TryGetGuildApplication(agentAddress, out var application)); Assert.Equal(guildAddress, application.GuildAddress); diff --git a/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs b/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs index db636f327c..06ca5f007b 100644 --- a/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs +++ b/.Lib9c.Tests/Action/Guild/BanGuildMemberTest.cs @@ -51,11 +51,12 @@ public void Ban_By_GuildMaster() Assert.Equal(otherGuildAddress, world.GetJoinedGuild(otherGuildMemberAddress)); var action = new BanGuildMember(guildMemberAddress); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); // Guild Assert.False(world.IsBanned(guildAddress, guildMasterAddress)); @@ -69,11 +70,12 @@ public void Ban_By_GuildMaster() Assert.Equal(otherGuildAddress, world.GetJoinedGuild(otherGuildMemberAddress)); action = new BanGuildMember(otherGuildMasterAddress); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); // Guild Assert.False(world.IsBanned(guildAddress, guildMasterAddress)); @@ -87,11 +89,12 @@ public void Ban_By_GuildMaster() Assert.Equal(otherGuildAddress, world.GetJoinedGuild(otherGuildMemberAddress)); action = new BanGuildMember(otherGuildMemberAddress); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); // Guild Assert.False(world.IsBanned(guildAddress, guildMasterAddress)); @@ -106,11 +109,13 @@ public void Ban_By_GuildMaster() action = new BanGuildMember(guildMasterAddress); // GuildMaster cannot ban itself. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + })); } [Fact] @@ -130,27 +135,33 @@ public void Ban_By_GuildMember() .JoinGuild(guildAddress, targetGuildMemberAddress); // GuildMember tries to ban other guild member. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMemberAddress, + })); // GuildMember tries to ban itself. action = new BanGuildMember(guildMemberAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMemberAddress, + })); action = new BanGuildMember(otherAddress); // GuildMember tries to ban other not joined to its guild. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMemberAddress, + })); } [Fact] @@ -169,19 +180,23 @@ public void Ban_By_Other() // Other tries to ban GuildMember. var action = new BanGuildMember(targetGuildMemberAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = otherAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = otherAddress, + })); // Other tries to ban GuildMaster. action = new BanGuildMember(guildMasterAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = otherAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = otherAddress, + })); } [Fact] @@ -197,11 +212,12 @@ public void RejectGuildApplication() Assert.True(world.TryGetGuildApplication(agentAddress, out _)); var action = new BanGuildMember(agentAddress); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); Assert.True(world.IsBanned(guildAddress, agentAddress)); Assert.False(world.TryGetGuildApplication(agentAddress, out _)); diff --git a/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs index 06ff38d9b5..92518090f6 100644 --- a/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/CancelGuildApplicationTest.cs @@ -34,29 +34,32 @@ public void Execute() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress); Assert.Throws( - () => action.Execute(new ActionContext - { - PreviousState = world, - Signer = signer, - })); + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = signer, + })); var otherAddress = AddressUtil.CreateAgentAddress(); world = world.ApplyGuild(otherAddress, guildAddress); // It should fail because other agent applied the guild but the signer didn't apply. Assert.Throws( - () => action.Execute(new ActionContext + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = signer, + })); + + world = world.ApplyGuild(signer, guildAddress); + world = action.Execute( + new ActionContext { PreviousState = world, Signer = signer, - })); - - world = world.ApplyGuild(signer, guildAddress); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = signer, - }); + }); Assert.False(world.TryGetGuildApplication(signer, out _)); } diff --git a/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs b/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs index df8db3f1f7..525a4ba8eb 100644 --- a/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/MakeGuildTest.cs @@ -48,19 +48,22 @@ public void Execute(AgentAddress guildMasterAddress, bool fail) if (fail) { - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + })); } else { - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); var guildAddress = world.GetJoinedGuild(guildMasterAddress); Assert.NotNull(guildAddress); diff --git a/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs b/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs index a4f840bd6a..a16212586d 100644 --- a/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs +++ b/.Lib9c.Tests/Action/Guild/Migration/GuildMigrationCtrlTest.cs @@ -28,14 +28,17 @@ public void MigratePlanetariumPledgeToGuild_When_WithUnapprovedPledgeContract() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - false.Serialize(), // Unapproved - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + false.Serialize(), // Unapproved + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); - Assert.Throws(() => - GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); + Assert.Throws( + () => + GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); } [Fact] @@ -48,10 +51,12 @@ public void MigratePlanetariumPledgeToGuild_When_WithPledgeContract() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); world = GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target); @@ -72,8 +77,9 @@ public void MigratePlanetariumPledgeToGuild_When_WithoutPledgeContract() .JoinGuild(guildAddress, guildMasterAddress); Assert.Null(world.GetJoinedGuild(target)); - Assert.Throws(() => - GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); + Assert.Throws( + () => + GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); } [Fact] @@ -82,14 +88,17 @@ public void MigratePlanetariumPledgeToGuild_When_WithoutGuildYet() var target = AddressUtil.CreateAgentAddress(); var pledgeAddress = target.GetPledgeAddress(); var world = new World(MockUtil.MockModernWorldState) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); - Assert.Throws(() => - GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); + Assert.Throws( + () => + GuildMigrationCtrl.MigratePlanetariumPledgeToGuild(world, target)); } } } diff --git a/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs b/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs index c63beb306a..d03042788e 100644 --- a/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/Migration/MigratePledgeToGuildTest.cs @@ -45,31 +45,35 @@ public void Execute_When_WithPledgeContract() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); var action = new MigratePledgeToGuild(target); // Migrate by other. - var newWorld = action.Execute(new ActionContext - { - PreviousState = world, - Signer = caller, - }); + var newWorld = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = caller, + }); var joinedGuildAddress = Assert.IsType(newWorld.GetJoinedGuild(target)); Assert.True(newWorld.TryGetGuild(joinedGuildAddress, out var guild)); Assert.Equal(GuildConfig.PlanetariumGuildOwner, guild.GuildMasterAddress); // Migrate by itself. - newWorld = action.Execute(new ActionContext - { - PreviousState = world, - Signer = target, - }); + newWorld = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = target, + }); joinedGuildAddress = Assert.IsType(newWorld.GetJoinedGuild(target)); Assert.True(newWorld.TryGetGuild(joinedGuildAddress, out guild)); @@ -87,27 +91,33 @@ public void Execute_When_WithUnapprovedPledgeContract() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - false.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + false.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); var action = new MigratePledgeToGuild(target); // Migrate by other. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = caller, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = caller, + })); // Migrate by itself. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = target, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = target, + })); } [Fact] @@ -125,18 +135,22 @@ public void Execute_When_WithoutPledgeContract() var action = new MigratePledgeToGuild(target); // Migrate by other. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = caller, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = caller, + })); // Migrate by itself. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = target, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = target, + })); } [Fact] @@ -146,27 +160,33 @@ public void Execute_When_WithoutGuildYet() var caller = AddressUtil.CreateAgentAddress(); var pledgeAddress = target.GetPledgeAddress(); var world = new World(MockUtil.MockModernWorldState) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(target)); var action = new MigratePledgeToGuild(target); // Migrate by other. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = caller, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = caller, + })); // Migrate by itself. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = target, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = target, + })); } } } diff --git a/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs b/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs index 9564e916e9..a3a2ed73cc 100644 --- a/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/QuitGuildTest.cs @@ -32,29 +32,34 @@ public void Execute() .MakeGuild(guildAddress, guildMasterAddress); // This case should fail because guild master cannot quit the guild. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + })); // This case should fail because the agent is not a member of the guild. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + })); // Join the guild. world = world.JoinGuild(guildAddress, agentAddress); Assert.NotNull(world.GetJoinedGuild(agentAddress)); // This case should fail because the agent is not a member of the guild. - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + }); Assert.Null(world.GetJoinedGuild(agentAddress)); } diff --git a/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs b/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs index d063ca2db0..f43462d9c8 100644 --- a/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs +++ b/.Lib9c.Tests/Action/Guild/RejectGuildApplicationTest.cs @@ -38,43 +38,49 @@ public void Execute() // These cases should fail because the member didn't apply the guild and // non-guild-master-addresses cannot reject the guild application. Assert.Throws( - () => new RejectGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - })); + () => new RejectGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + })); Assert.Throws( - () => new RejectGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = appliedMemberAddress, - })); + () => new RejectGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = appliedMemberAddress, + })); Assert.Throws( - () => new RejectGuildApplication(nonAppliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = nonAppliedMemberAddress, - })); + () => new RejectGuildApplication(nonAppliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = nonAppliedMemberAddress, + })); // These cases should fail because non-guild-master-addresses cannot reject the guild application. Assert.Throws( - () => new RejectGuildApplication(appliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = appliedMemberAddress, - })); + () => new RejectGuildApplication(appliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = appliedMemberAddress, + })); Assert.Throws( - () => new RejectGuildApplication(appliedMemberAddress).Execute(new ActionContext + () => new RejectGuildApplication(appliedMemberAddress).Execute( + new ActionContext + { + PreviousState = world, + Signer = nonAppliedMemberAddress, + })); + + world = new RejectGuildApplication(appliedMemberAddress).Execute( + new ActionContext { PreviousState = world, - Signer = nonAppliedMemberAddress, - })); - - world = new RejectGuildApplication(appliedMemberAddress).Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + Signer = guildMasterAddress, + }); Assert.False(world.TryGetGuildApplication(appliedMemberAddress, out _)); Assert.Null(world.GetJoinedGuild(appliedMemberAddress)); diff --git a/.Lib9c.Tests/Action/Guild/RemoveGuildTest.cs b/.Lib9c.Tests/Action/Guild/RemoveGuildTest.cs index 766094d4c3..3cfb6b7fe8 100644 --- a/.Lib9c.Tests/Action/Guild/RemoveGuildTest.cs +++ b/.Lib9c.Tests/Action/Guild/RemoveGuildTest.cs @@ -32,11 +32,13 @@ public void Execute_By_GuildMember() IWorld world = new World(MockWorldState.CreateModern()); world = world.MakeGuild(guildAddress, guildMasterAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMemberAddress, + })); } [Fact] @@ -50,11 +52,12 @@ public void Execute_By_GuildMaster() IWorld world = new World(MockWorldState.CreateModern()); world = world.MakeGuild(guildAddress, guildMasterAddress); - var changedWorld = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + var changedWorld = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); Assert.False(changedWorld.TryGetGuild(guildAddress, out _)); Assert.Null(changedWorld.GetJoinedGuild(guildMasterAddress)); @@ -72,11 +75,13 @@ public void Execute_By_Other() IWorld world = new World(MockWorldState.CreateModern()); world = world.MakeGuild(guildAddress, guildMasterAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = otherAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = otherAddress, + })); } [Fact] @@ -94,11 +99,12 @@ public void ResetBannedAddresses() Assert.True(world.IsBanned(guildAddress, bannedAddress)); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); Assert.False(world.IsBanned(guildAddress, bannedAddress)); } diff --git a/.Lib9c.Tests/Action/Guild/UnbanGuildMemberTest.cs b/.Lib9c.Tests/Action/Guild/UnbanGuildMemberTest.cs index 9aedb745e7..997fa9cb15 100644 --- a/.Lib9c.Tests/Action/Guild/UnbanGuildMemberTest.cs +++ b/.Lib9c.Tests/Action/Guild/UnbanGuildMemberTest.cs @@ -39,18 +39,22 @@ public void Unban_By_GuildMember() .JoinGuild(guildAddress, targetGuildMemberAddress); // GuildMember tries to ban other guild member. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMemberAddress, + })); // GuildMember tries to ban itself. - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = world, - Signer = targetGuildMemberAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = world, + Signer = targetGuildMemberAddress, + })); } [Fact] @@ -69,11 +73,12 @@ public void Unban_By_GuildMaster() Assert.True(world.IsBanned(guildAddress, targetGuildMemberAddress)); Assert.Null(world.GetJoinedGuild(targetGuildMemberAddress)); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = guildMasterAddress, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = guildMasterAddress, + }); Assert.False(world.IsBanned(guildAddress, targetGuildMemberAddress)); Assert.Null(world.GetJoinedGuild(targetGuildMemberAddress)); diff --git a/.Lib9c.Tests/Action/HackAndSlashRandomBuffTest.cs b/.Lib9c.Tests/Action/HackAndSlashRandomBuffTest.cs index 969a34a2c1..b90fb3511e 100644 --- a/.Lib9c.Tests/Action/HackAndSlashRandomBuffTest.cs +++ b/.Lib9c.Tests/Action/HackAndSlashRandomBuffTest.cs @@ -121,12 +121,13 @@ public void Execute(int stageId, bool advancedGacha, int balance, int gatheredSt if (excType is null) { - var nextState = action.Execute(new ActionContext - { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = _random.Seed, + }); Assert.Equal( nextState.GetBalance(_agentAddress, CrystalCalculator.CRYSTAL), @@ -134,15 +135,18 @@ public void Execute(int stageId, bool advancedGacha, int balance, int gatheredSt } else { - Assert.Throws(excType, () => - { - action.Execute(new ActionContext + Assert.Throws( + excType, + () => { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = _random.Seed, + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = _random.Seed, + }); }); - }); } } @@ -179,12 +183,13 @@ public void ContainMinimumBuffRank(bool advancedGacha, CrystalRandomBuffSheet.Ro AvatarAddress = _avatarAddress, AdvancedGacha = advancedGacha, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = _random.Seed, + }); var newGachaState = new CrystalRandomSkillState( gachaStateAddress, (List)nextState.GetLegacyState(gachaStateAddress)); diff --git a/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs b/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs index 24a7ecd0d1..7aad750478 100644 --- a/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs +++ b/.Lib9c.Tests/Action/HackAndSlashSweepTest.cs @@ -105,7 +105,8 @@ public HackAndSlashSweepTest() .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); avatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -127,12 +128,14 @@ public void Execute_FailedLoadStateException() IWorld state = new World(MockUtil.MockModernWorldState); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Theory] @@ -153,12 +156,14 @@ public void Execute_SheetRowNotFoundException(int worldId, int stageId) List.Empty.Add(worldId.Serialize()) ); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Theory] @@ -180,12 +185,14 @@ public void Execute_SheetRowColumnException(int worldId, int stageId) List.Empty.Add(worldId.Serialize()) ); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Theory] @@ -213,12 +220,14 @@ public void Execute_InvalidStageException(int clearedWorldId, int clearedStageId ) .SetAvatarState(_avatarAddress, _avatarState); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Theory] @@ -257,12 +266,14 @@ public void Execute_InvalidWorldException(int worldId, int stageId, bool unlocke stageId = stageId, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Fact] @@ -289,12 +300,14 @@ public void Execute_UsageLimitExceedException() stageId = 2, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } [Theory] @@ -313,8 +326,9 @@ public void Execute_NotEnoughMaterialException(int useApStoneCount, int holdingA new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 400; - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(row); avatarState.inventory.AddItem(apStone, holdingApStoneCount); @@ -348,12 +362,14 @@ public void Execute_NotEnoughMaterialException(int useApStoneCount, int holdingA stageId = 2, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } } @@ -401,13 +417,15 @@ public void Execute_NotEnoughActionPointException() stageId = 2, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } } @@ -455,13 +473,15 @@ public void Execute_PlayCountIsZeroException() stageId = 2, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } } @@ -509,13 +529,15 @@ public void Execute_NotEnoughCombatPointException() stageId = stageId, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } } @@ -540,8 +562,9 @@ public void ExecuteWithStake(int stakingLevel) new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 3; - var itemRow = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var itemRow = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(itemRow); avatarState.inventory.AddItem(apStone); @@ -581,12 +604,13 @@ public void ExecuteWithStake(int stakingLevel) stageId = stageId, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); var nextAvatar = nextState.GetAvatarState(_avatarAddress); Assert.Equal(expectedLevel, nextAvatar.level); Assert.Equal(expectedExp, nextAvatar.exp); @@ -654,12 +678,13 @@ public void CheckRewardItems(int worldId, int stageId) stageId = stageId, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); var nextAvatar = nextState.GetAvatarState(_avatarAddress); var circleRow = materialSheet.Values.First(i => i.ItemSubType == ItemSubType.Circle); @@ -690,8 +715,9 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 new WorldInformation(0, _initialState.GetSheet(), 25); avatarState.level = 3; - var itemRow = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var itemRow = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(itemRow); avatarState.inventory.AddItem(apStone); @@ -728,13 +754,14 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 SlotIndex = 1, }; - state = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + state = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); var action = new HackAndSlashSweep { @@ -752,12 +779,15 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 stageId = stageId, }; - Assert.Throws(exception, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + exception, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } else { @@ -812,13 +842,15 @@ public void Execute_ArgumentOutOfRangeException(int ap, int apPotion) stageId = 2, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } } } diff --git a/.Lib9c.Tests/Action/HackAndSlashTest.cs b/.Lib9c.Tests/Action/HackAndSlashTest.cs index 0db89f7609..bbee537f21 100644 --- a/.Lib9c.Tests/Action/HackAndSlashTest.cs +++ b/.Lib9c.Tests/Action/HackAndSlashTest.cs @@ -136,7 +136,8 @@ public void Execute(int avatarLevel, int worldId, int stageId, bool isWeaponLock .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); previousAvatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -184,13 +185,14 @@ public void Execute(int avatarLevel, int worldId, int stageId, bool isWeaponLock AvatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); @@ -259,12 +261,13 @@ public void Execute_With_UpdateQuestList(int worldId, int stageId) ); // Second Execute - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + state = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); avatarState = state.GetAvatarState(avatarState.address); avatarWorldQuests = avatarState.questList.OfType().ToList(); @@ -288,9 +291,10 @@ public void MaxLevelTest() try { stageId = _tableSheets.StageSheet - .FirstOrDefault(row => - previousAvatarState.level - row.Value.Id <= StageRewardExpHelper.DifferLowerLimit || - previousAvatarState.level - row.Value.Id > StageRewardExpHelper.DifferUpperLimit) + .FirstOrDefault( + row => + previousAvatarState.level - row.Value.Id <= StageRewardExpHelper.DifferLowerLimit || + previousAvatarState.level - row.Value.Id > StageRewardExpHelper.DifferUpperLimit) .Value.Id; } catch @@ -300,8 +304,9 @@ public void MaxLevelTest() } var worldRow = _tableSheets.WorldSheet - .FirstOrDefault(row => stageId >= row.Value.StageBegin && - stageId <= row.Value.StageEnd); + .FirstOrDefault( + row => stageId >= row.Value.StageBegin && + stageId <= row.Value.StageEnd); var worldId = worldRow.Value.Id; previousAvatarState.worldInformation = new WorldInformation( @@ -322,12 +327,13 @@ public void MaxLevelTest() AvatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.Equal(maxLevelExp + requiredExp - 1, nextAvatarState.exp); @@ -381,12 +387,14 @@ public void MultipleEquipmentTest(ItemSubType type, int maxCount) AvatarAddress = _avatarAddress, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -413,12 +421,14 @@ public void Execute_Throw_FailedLoadStateException(bool empty) .SetAvatarState(_avatarAddress, _avatarState) .SetAccount(Addresses.Inventory, new Account(MockUtil.MockAccountState)); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -439,12 +449,14 @@ public void ExecuteThrowSheetRowColumnException(int stageId) AvatarAddress = _avatarAddress, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -466,12 +478,14 @@ public void ExecuteThrowSheetRowNotFoundExceptionByStage() var state = _initialState; state = state.SetLegacyState(Addresses.TableSheet.Derive(nameof(StageSheet)), "test".Serialize()); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -501,12 +515,14 @@ public void ExecuteThrowFailedAddWorldException() Assert.False(avatarState.worldInformation.IsStageCleared(0)); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -539,12 +555,14 @@ public void Execute_Throw_InvalidWorldException(int worldId, int stageId, bool u ); } - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -580,12 +598,14 @@ public void ExecuteThrowInvalidStageException() var state = _initialState; state = state.SetAvatarState(_avatarAddress, avatarState); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -607,12 +627,14 @@ public void ExecuteThrowInvalidStageExceptionUnlockedWorld() _avatarState.worldInformation.TryGetWorld(1, out var world); Assert.False(world.IsStageCleared); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -646,12 +668,14 @@ public void ExecuteThrowInvalidEquipmentException(ItemSubType itemSubType) var state = _initialState.SetAvatarState(_avatarAddress, avatarState); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -690,12 +714,14 @@ public void ExecuteThrowEquipmentSlotUnlockException(ItemSubType itemSubType) AvatarAddress = _avatarAddress, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -724,12 +750,14 @@ public void ExecuteThrowNotEnoughActionPointException(int ap, int playCount = 1) state = state.SetAvatarState(_avatarAddress, avatarState) .SetActionPoint(_avatarAddress, ap); - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -778,13 +806,14 @@ public void ExecuteWithoutPlayCount() AvatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = 1, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = 1, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.True(nextAvatarState.worldInformation.IsStageCleared(1)); @@ -844,12 +873,14 @@ public void Execute_Throw_NotEnoughAvatarLevelException(int avatarLevel) AvatarAddress = avatarState.address, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = avatarState.agentAddress, - RandomSeed = random.Seed, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = avatarState.agentAddress, + RandomSeed = random.Seed, + })); SerializeException(exec); } @@ -878,12 +909,14 @@ public void ExecuteThrowInvalidItemCountException() ApStoneCount = -1, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = avatarState.agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = avatarState.agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -914,12 +947,14 @@ public void ExecuteThrowPlayCountIsZeroException(int totalPlayCount, int apStone ApStoneCount = apStoneCount, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = avatarState.agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = avatarState.agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -941,12 +976,14 @@ public void ExecuteThrowUsageLimitExceedException() ApStoneCount = 11, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _avatarState.agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _avatarState.agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -968,12 +1005,14 @@ public void ExecuteThrowNotEnoughMaterialException() ApStoneCount = 1, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _avatarState.agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _avatarState.agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -1009,7 +1048,8 @@ public void CheckRewardItems(int worldId, int stageId) .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); previousAvatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); @@ -1054,13 +1094,14 @@ public void CheckRewardItems(int worldId, int stageId) AvatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = 1, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = 1, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.True(nextAvatarState.worldInformation.IsStageCleared(stageId)); @@ -1079,9 +1120,10 @@ x.item is IFungibleItem ownedFungibleItem && var questItemRewardSheet = state.GetSheet(); var materialItemSheet = state.GetSheet(); var sortedMaterialItemSheet = materialItemSheet - .Where(x => - x.Value.ItemSubType == ItemSubType.EquipmentMaterial || - x.Value.ItemSubType == ItemSubType.MonsterPart).ToList(); + .Where( + x => + x.Value.ItemSubType == ItemSubType.EquipmentMaterial || + x.Value.ItemSubType == ItemSubType.MonsterPart).ToList(); var selectedIdn = new Dictionary(); foreach (var row in questItemRewardSheet) @@ -1144,7 +1186,8 @@ public void CheckCrystalRandomSkillState( .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); previousAvatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); @@ -1187,8 +1230,9 @@ public void CheckCrystalRandomSkillState( if (useCrystalSkill) { skillState.Update(int.MaxValue, _tableSheets.CrystalStageBuffGachaSheet); - skillState.Update(_tableSheets.CrystalRandomBuffSheet - .Select(pair => pair.Value.Id).ToList()); + skillState.Update( + _tableSheets.CrystalRandomBuffSheet + .Select(pair => pair.Value.Id).ToList()); } state = state.SetLegacyState(skillStateAddress, skillState.Serialize()); @@ -1235,8 +1279,9 @@ public void CheckCrystalRandomSkillState( { var skill = _tableSheets .SkillSheet - .FirstOrDefault(pair => pair.Key == _tableSheets - .CrystalRandomBuffSheet[stageBuffId.Value].SkillId); + .FirstOrDefault( + pair => pair.Key == _tableSheets + .CrystalRandomBuffSheet[stageBuffId.Value].SkillId); if (skill.Value != null) { skillsOnWaveStart.Add(SkillFactory.GetV1(skill.Value, default, 100)); @@ -1320,7 +1365,9 @@ public void CheckUsedApByStaking(int level, int playCount) var expectedAp = state.GetActionPoint(_avatarAddress) - _tableSheets.StakeActionPointCoefficientSheet.GetActionPointByStaking( - _tableSheets.StageSheet[stageId].CostAP, playCount, level); + _tableSheets.StageSheet[stageId].CostAP, + playCount, + level); var action = new HackAndSlash { Costumes = new List(), @@ -1368,8 +1415,9 @@ public void CheckUsingApStoneWithStaking(int level, int apStoneCount, int totalR 0, _tableSheets.WorldSheet, clearedStageId); - var apStoneRow = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var apStoneRow = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(apStoneRow); previousAvatarState.inventory.AddItem(apStone, apStoneCount); var stakeStateAddress = StakeState.DeriveAddress(_agentAddress); @@ -1425,8 +1473,9 @@ public void ExecuteThrowInvalidRepeatPlayException() level = 1, }; - var apStoneRow = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var apStoneRow = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(apStoneRow); avatarState.inventory.AddItem(apStone); var state = _initialState.SetAvatarState(_avatarAddress, avatarState) @@ -1444,12 +1493,14 @@ public void ExecuteThrowInvalidRepeatPlayException() ApStoneCount = 1, }; - var exec = Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = state, - Signer = avatarState.agentAddress, - RandomSeed = 0, - })); + var exec = Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = avatarState.agentAddress, + RandomSeed = 0, + })); SerializeException(exec); } @@ -1485,7 +1536,8 @@ public void ExecuteTwoRepetitions() .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); previousAvatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -1534,13 +1586,14 @@ public void ExecuteTwoRepetitions() AvatarAddress = _avatarAddress, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, + }); var action2 = new HackAndSlash { @@ -1557,13 +1610,14 @@ public void ExecuteTwoRepetitions() AvatarAddress = _avatarAddress, }; - action2.Execute(new ActionContext - { - PreviousState = nextState, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, - }); + action2.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, + }); } [Theory] @@ -1599,7 +1653,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); previousAvatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -1644,13 +1699,14 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 SlotIndex = 1, }; - state = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + state = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); var action = new HackAndSlash { @@ -1667,12 +1723,15 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 AvatarAddress = _avatarAddress, }; - Assert.Throws(exception, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - })); + Assert.Throws( + exception, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + })); } private static void SerializeException(Exception exec) diff --git a/.Lib9c.Tests/Action/InitializeStatesTest.cs b/.Lib9c.Tests/Action/InitializeStatesTest.cs index 01d0d679f7..53a250b2f6 100644 --- a/.Lib9c.Tests/Action/InitializeStatesTest.cs +++ b/.Lib9c.Tests/Action/InitializeStatesTest.cs @@ -41,7 +41,7 @@ public void Execute() #pragma warning restore CS0618 var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( @@ -60,13 +60,14 @@ public void Execute() pendingActivationStates: new[] { pendingActivation, } ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Signer = minterKey.Address, - Miner = default, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Signer = minterKey.Address, + Miner = default, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var addresses = new List
() { @@ -103,7 +104,7 @@ public void ExecuteWithAuthorizedMinersState() #pragma warning restore CS0618 var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( @@ -127,13 +128,14 @@ public void ExecuteWithAuthorizedMinersState() ) ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var fetchedState = new AuthorizedMinersState( (Dictionary)genesisState.GetLegacyState(AuthorizedMinersState.Address) @@ -159,7 +161,7 @@ public void ExecuteWithActivateAdminKey() #pragma warning restore CS0618 var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(privateKey, nonce); var adminAddress = new Address("F9A15F870701268Bd7bBeA6502eB15F4997f32f9"); @@ -176,13 +178,14 @@ public void ExecuteWithActivateAdminKey() pendingActivationStates: new[] { pendingActivation, } ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var fetchedState = new ActivatedAccountsState( (Dictionary)genesisState.GetLegacyState(Addresses.ActivatedAccount)); @@ -228,13 +231,14 @@ public void ExecuteWithCredits() creditsState: creditState ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var fetchedState = new CreditsState( (Dictionary)genesisState.GetLegacyState(CreditsState.Address)); @@ -258,7 +262,7 @@ public void ExecuteWithoutAdminState() #pragma warning restore CS0618 var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; var privateKey = new PrivateKey(); - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(privateKey, nonce); var action = new InitializeStates( @@ -274,13 +278,14 @@ public void ExecuteWithoutAdminState() pendingActivationStates: new[] { pendingActivation, } ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var fetchedState = new ActivatedAccountsState( (Dictionary)genesisState.GetLegacyState(Addresses.ActivatedAccount)); @@ -317,13 +322,14 @@ public void ExecuteWithoutInitialSupply() pendingActivationStates: Array.Empty() ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); Assert.Equal(0 * ncg, genesisState.GetBalance(GoldCurrencyState.Address, ncg)); } @@ -358,13 +364,14 @@ public void ExecuteWithAssetMinters() assetMinters: new[] { default(Address), }.ToHashSet() ); - var genesisState = action.Execute(new ActionContext() - { - BlockIndex = 0, - Miner = default, - Signer = minterKey.Address, - PreviousState = new World(MockUtil.MockModernWorldState), - }); + var genesisState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + Miner = default, + Signer = minterKey.Address, + PreviousState = new World(MockUtil.MockModernWorldState), + }); var assetMinters = Assert.IsType(genesisState.GetLegacyState(Addresses.AssetMinters)); Assert.Contains(default(Address).Serialize(), assetMinters); diff --git a/.Lib9c.Tests/Action/InvalidTransferSiginerExceptionTest.cs b/.Lib9c.Tests/Action/InvalidTransferSiginerExceptionTest.cs index 288f5157a9..d314bf028a 100644 --- a/.Lib9c.Tests/Action/InvalidTransferSiginerExceptionTest.cs +++ b/.Lib9c.Tests/Action/InvalidTransferSiginerExceptionTest.cs @@ -14,27 +14,30 @@ public void Serialize() var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); var exc = new InvalidTransferSignerException( - new Address(new byte[] - { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, - }), - new Address(new byte[] - { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, - }), - new Address(new byte[] - { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x03, - }) + new Address( + new byte[] + { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, + }), + new Address( + new byte[] + { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, + }), + new Address( + new byte[] + { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, + }) ); formatter.Serialize(ms, exc); diff --git a/.Lib9c.Tests/Action/IssueTokenTest.cs b/.Lib9c.Tests/Action/IssueTokenTest.cs index ea69a8c5eb..368d3d68cf 100644 --- a/.Lib9c.Tests/Action/IssueTokenTest.cs +++ b/.Lib9c.Tests/Action/IssueTokenTest.cs @@ -24,11 +24,12 @@ public class IssueTokenTest public IssueTokenTest() { _signer = new PrivateKey().Address; - _avatarAddress = _signer.Derive(string.Format( - CultureInfo.InvariantCulture, - CreateAvatar.DeriveFormat, - 0 - )); + _avatarAddress = _signer.Derive( + string.Format( + CultureInfo.InvariantCulture, + CreateAvatar.DeriveFormat, + 0 + )); var sheets = TableSheetsImporter.ImportSheets(); var tableSheets = new TableSheets(sheets); @@ -200,14 +201,15 @@ public void Execute_Throw_InvalidCurrencyException() .MintAsset(actionContext, _signer, Currencies.Garage * 1000) .MintAsset(actionContext, _signer, currencyWithMinter * 1000); - Assert.Throws(() => action.Execute( - new ActionContext() - { - PreviousState = prevState, - Signer = _signer, - BlockIndex = 42, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _signer, + BlockIndex = 42, + } + )); } } } diff --git a/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs b/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs index 136f49794c..fe954030d8 100644 --- a/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs +++ b/.Lib9c.Tests/Action/IssueTokensFromGarageTest.cs @@ -68,9 +68,11 @@ public void PlainValue() var action = new IssueTokensFromGarage(specs); var expected = Dictionary.Empty .Add("type_id", "issue_tokens_from_garage") - .Add("values", List.Empty - .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) - .Add(new List(default(Null), new FungibleItemValue(SampleFungibleId, 42).Serialize()))); + .Add( + "values", + List.Empty + .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) + .Add(new List(default(Null), new FungibleItemValue(SampleFungibleId, 42).Serialize()))); Assert.Equal( expected, action.PlainValue @@ -82,9 +84,11 @@ public void LoadPlainValue() { var encoded = Dictionary.Empty .Add("type_id", "issue_tokens_from_garage") - .Add("values", List.Empty - .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) - .Add(new List(default(Null), new FungibleItemValue(SampleFungibleId, 42).Serialize()))); + .Add( + "values", + List.Empty + .Add(new List((Currencies.Crystal * 1000).Serialize(), default(Null))) + .Add(new List(default(Null), new FungibleItemValue(SampleFungibleId, 42).Serialize()))); var action = new IssueTokensFromGarage(); action.LoadPlainValue(encoded); var expected = new List() @@ -99,10 +103,11 @@ public void LoadPlainValue() [Fact] public void Execute_With_FungibleAssetValue() { - var action = new IssueTokensFromGarage(new[] - { - IssueTokensFromGarage.Spec.FromFungibleAssetValue(Currencies.Crystal * 42), - }); + var action = new IssueTokensFromGarage( + new[] + { + IssueTokensFromGarage.Spec.FromFungibleAssetValue(Currencies.Crystal * 42), + }); var nextState = action.Execute( new ActionContext() @@ -128,10 +133,11 @@ public void Execute_With_FungibleAssetValue() [Fact] public void Execute_With_FungibleItemValue() { - var action = new IssueTokensFromGarage(new[] - { - IssueTokensFromGarage.Spec.FromFungibleItemValue(new FungibleItemValue(SampleFungibleId, 42)), - }); + var action = new IssueTokensFromGarage( + new[] + { + IssueTokensFromGarage.Spec.FromFungibleItemValue(new FungibleItemValue(SampleFungibleId, 42)), + }); var nextState = action.Execute( new ActionContext() diff --git a/.Lib9c.Tests/Action/ItemEnhancementTest.cs b/.Lib9c.Tests/Action/ItemEnhancementTest.cs index 5eb1504b8e..99edf2233d 100644 --- a/.Lib9c.Tests/Action/ItemEnhancementTest.cs +++ b/.Lib9c.Tests/Action/ItemEnhancementTest.cs @@ -198,9 +198,10 @@ public void Execute( } else { - equipment.Exp = _tableSheets.EnhancementCostSheetV3.OrderedList.First(r => - r.ItemSubType == equipment.ItemSubType && r.Grade == equipment.Grade && - r.Level == equipment.level).Exp; + equipment.Exp = _tableSheets.EnhancementCostSheetV3.OrderedList.First( + r => + r.ItemSubType == equipment.ItemSubType && r.Grade == equipment.Grade && + r.Level == equipment.level).Exp; } var startExp = equipment.Exp; @@ -211,9 +212,10 @@ public void Execute( _avatarState.inventory.AddItem(equipment, 1); - var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault(r => - r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && - r.Level == startLevel); + var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault( + r => + r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && + r.Level == startLevel); var expectedExpIncrement = 0L; var materialIds = new List(); var duplicatedGuid = Guid.NewGuid(); @@ -229,9 +231,10 @@ public void Execute( } else { - material.Exp = _tableSheets.EnhancementCostSheetV3.OrderedList.First(r => - r.ItemSubType == material.ItemSubType && r.Grade == material.Grade && - r.Level == material.level).Exp; + material.Exp = _tableSheets.EnhancementCostSheetV3.OrderedList.First( + r => + r.ItemSubType == material.ItemSubType && r.Grade == material.Grade && + r.Level == material.level).Exp; } if (!(duplicated && i > 0)) @@ -284,13 +287,14 @@ public void Execute( slotIndex = 0, }; - var nextState = action.Execute(new ActionContext() - { - PreviousState = _initialState, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = _initialState, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = 0, + }); var allSlotState = nextState.GetAllCombinationSlotState(_avatarAddress); var slotState = allSlotState.GetSlot(0); @@ -332,8 +336,9 @@ public void Execute( for (var i = startLevel + 1; i <= level; i++) { var currentRow = _tableSheets.EnhancementCostSheetV3.OrderedList - .First(x => - x.Grade == 1 && x.ItemSubType == equipment.ItemSubType && x.Level == i); + .First( + x => + x.Grade == 1 && x.ItemSubType == equipment.ItemSubType && x.Level == i); baseMinAtk *= currentRow.BaseStatGrowthMin.NormalizeFromTenThousandths() + 1; baseMaxAtk *= currentRow.BaseStatGrowthMax.NormalizeFromTenThousandths() + 1; @@ -406,9 +411,10 @@ public void Execute_With_Hammer(bool oldStart) _avatarState.inventory.AddItem(equipment, 1); - var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault(r => - r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && - r.Level == startLevel); + var startRow = _tableSheets.EnhancementCostSheetV3.OrderedList.FirstOrDefault( + r => + r.Grade == equipment.Grade && r.ItemSubType == equipment.ItemSubType && + r.Level == startLevel); var expectedExpIncrement = 0L; var materialIds = new List(); for (var i = 0; i < materialCount; i++) @@ -423,7 +429,8 @@ public void Execute_With_Hammer(bool oldStart) } _avatarState.inventory.AddItem( - ItemFactory.CreateMaterial(_tableSheets.MaterialItemSheet[hammerId]), 3); + ItemFactory.CreateMaterial(_tableSheets.MaterialItemSheet[hammerId]), + 3); var hammerExp = _tableSheets.EnhancementCostSheetV3.GetHammerExp(hammerId) * 3; @@ -468,13 +475,14 @@ public void Execute_With_Hammer(bool oldStart) }, }; - var nextState = action.Execute(new ActionContext() - { - PreviousState = _initialState, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = _initialState, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = 0, + }); var allSlotState = nextState.GetAllCombinationSlotState(_avatarAddress); var slotState = allSlotState.GetSlot(0); @@ -515,8 +523,9 @@ public void Execute_With_Hammer(bool oldStart) for (var i = startLevel + 1; i <= level; i++) { var currentRow = _tableSheets.EnhancementCostSheetV3.OrderedList - .First(x => - x.Grade == 1 && x.ItemSubType == equipment.ItemSubType && x.Level == i); + .First( + x => + x.Grade == 1 && x.ItemSubType == equipment.ItemSubType && x.Level == i); baseMinAtk *= currentRow.BaseStatGrowthMin.NormalizeFromTenThousandths() + 1; baseMaxAtk *= currentRow.BaseStatGrowthMax.NormalizeFromTenThousandths() + 1; diff --git a/.Lib9c.Tests/Action/JoinArena1Test.cs b/.Lib9c.Tests/Action/JoinArena1Test.cs index 71d03e2ed5..331c3ade8a 100644 --- a/.Lib9c.Tests/Action/JoinArena1Test.cs +++ b/.Lib9c.Tests/Action/JoinArena1Test.cs @@ -102,7 +102,7 @@ public JoinArena1Test(ITestOutputHelper outputHelper) .SetAvatarState(_avatar2Address, avatar2State) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((var key, var value) in sheets) + foreach (var (key, value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -130,7 +130,8 @@ public JoinArena1Test(ITestOutputHelper outputHelper) .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); avatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -180,7 +181,8 @@ public void Execute(long blockIndex, int championshipId, int round, string balan if (!arenaSheet.TryGetValue(championshipId, out var row)) { throw new SheetRowNotFoundException( - nameof(ArenaSheet), $"championship Id : {championshipId}"); + nameof(ArenaSheet), + $"championship Id : {championshipId}"); } var avatarState = _state.GetAvatarState(_avatarAddress); @@ -201,13 +203,14 @@ public void Execute(long blockIndex, int championshipId, int round, string balan avatarAddress = _avatarAddress, }; - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signer, - RandomSeed = _random.Seed, - BlockIndex = blockIndex, - }); + state = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signer, + RandomSeed = _random.Seed, + BlockIndex = blockIndex, + }); // ArenaParticipants var arenaParticipantsAdr = ArenaParticipants.DeriveAddress(championshipId, round); @@ -277,12 +280,14 @@ public void Execute_SheetRowNotFoundException(int championshipId) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + })); } [Theory] @@ -302,13 +307,15 @@ public void Execute_RoundNotFoundByIdsException(int round) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Theory] @@ -330,13 +337,15 @@ public void Execute_NotEnoughMedalException(int round) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 100, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 100, + })); } [Theory] @@ -357,13 +366,15 @@ public void Execute_NotEnoughFungibleAssetValueException(int round, long blockIn avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -382,21 +393,24 @@ public void Execute_ArenaScoreAlreadyContainsException() avatarAddress = _avatarAddress, }; - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signer, - RandomSeed = _random.Seed, - BlockIndex = 1, - }); - - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 2, - })); + state = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signer, + RandomSeed = _random.Seed, + BlockIndex = 1, + }); + + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 2, + })); } [Fact] @@ -422,13 +436,15 @@ public void Execute_ArenaScoreAlreadyContainsException2() avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Fact] @@ -454,13 +470,15 @@ public void Execute_ArenaInformationAlreadyContainsException() avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Fact] @@ -475,12 +493,14 @@ public void Execute_NotEnoughClearedStageLevelException() avatarAddress = _avatar2Address, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = _state, - Signer = _signer2, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = _state, + Signer = _signer2, + RandomSeed = 0, + })); } } } diff --git a/.Lib9c.Tests/Action/JoinArena3Test.cs b/.Lib9c.Tests/Action/JoinArena3Test.cs index 413d123387..d592929ddd 100644 --- a/.Lib9c.Tests/Action/JoinArena3Test.cs +++ b/.Lib9c.Tests/Action/JoinArena3Test.cs @@ -105,7 +105,7 @@ public JoinArena3Test(ITestOutputHelper outputHelper) .SetLegacyState(gameConfigState.address, gameConfigState.Serialize()) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((var key, var value) in sheets) + foreach (var (key, value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -133,7 +133,8 @@ public JoinArena3Test(ITestOutputHelper outputHelper) .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); avatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -182,7 +183,8 @@ public void Execute(long blockIndex, int championshipId, int round, string balan if (!arenaSheet.TryGetValue(championshipId, out var row)) { throw new SheetRowNotFoundException( - nameof(ArenaSheet), $"championship Id : {championshipId}"); + nameof(ArenaSheet), + $"championship Id : {championshipId}"); } var avatarState = _state.GetAvatarState(_avatarAddress); @@ -204,13 +206,14 @@ public void Execute(long blockIndex, int championshipId, int round, string balan avatarAddress = _avatarAddress, }; - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signer, - RandomSeed = _random.Seed, - BlockIndex = blockIndex, - }); + state = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signer, + RandomSeed = _random.Seed, + BlockIndex = blockIndex, + }); // ArenaParticipants var arenaParticipantsAdr = ArenaParticipants.DeriveAddress(championshipId, round); @@ -281,12 +284,14 @@ public void Execute_SheetRowNotFoundException(int championshipId) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + })); } [Theory] @@ -307,13 +312,15 @@ public void Execute_RoundNotFoundByIdsException(int round) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Theory] @@ -336,13 +343,15 @@ public void Execute_NotEnoughMedalException(int round) avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 100, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 100, + })); } [Theory] @@ -364,13 +373,15 @@ public void Execute_NotEnoughFungibleAssetValueException(int round, long blockIn avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -390,21 +401,24 @@ public void Execute_ArenaScoreAlreadyContainsException() avatarAddress = _avatarAddress, }; - state = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signer, - RandomSeed = _random.Seed, - BlockIndex = 1, - }); - - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 2, - })); + state = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signer, + RandomSeed = _random.Seed, + BlockIndex = 1, + }); + + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 2, + })); } [Fact] @@ -431,13 +445,15 @@ public void Execute_ArenaScoreAlreadyContainsException2() avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Fact] @@ -464,13 +480,15 @@ public void Execute_ArenaInformationAlreadyContainsException() avatarAddress = _avatarAddress, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + BlockIndex = 1, + })); } [Fact] @@ -486,12 +504,14 @@ public void Execute_NotEnoughClearedStageLevelException() avatarAddress = _avatar2Address, }; - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = _state, - Signer = _signer2, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = _state, + Signer = _signer2, + RandomSeed = 0, + })); } [Theory] @@ -505,7 +525,8 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 if (!arenaSheet.TryGetValue(championshipId, out var row)) { throw new SheetRowNotFoundException( - nameof(ArenaSheet), $"championship Id : {championshipId}"); + nameof(ArenaSheet), + $"championship Id : {championshipId}"); } var avatarState = _state.GetAvatarState(_avatarAddress); @@ -522,13 +543,14 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 SlotIndex = 1, }; - state = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - }); + state = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + }); var action = new JoinArena3() { @@ -544,12 +566,15 @@ public void ExecuteDuplicatedException(int slotIndex, int runeId, int slotIndex2 avatarAddress = _avatarAddress, }; - Assert.Throws(exception, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _signer, - RandomSeed = 0, - })); + Assert.Throws( + exception, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _signer, + RandomSeed = 0, + })); } } } diff --git a/.Lib9c.Tests/Action/JoinArenaTest.cs b/.Lib9c.Tests/Action/JoinArenaTest.cs index 1c2b5dabcd..04d3d9f672 100644 --- a/.Lib9c.Tests/Action/JoinArenaTest.cs +++ b/.Lib9c.Tests/Action/JoinArenaTest.cs @@ -60,13 +60,16 @@ public void Execute_OffSeason_Success() [Fact] public void Execute_Season_Success() { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Season && - e2.EntranceFee > 0)); - var roundData = row.Round.First(e => - e.ArenaType == ArenaType.Season && - e.EntranceFee > 0); + var row = _tableSheets.ArenaSheet.OrderedList!.First( + e => + e.Round.Any( + e2 => + e2.ArenaType == ArenaType.Season && + e2.EntranceFee > 0)); + var roundData = row.Round.First( + e => + e.ArenaType == ArenaType.Season && + e.EntranceFee > 0); var blockIndex = roundData.StartBlockIndex; var fee = ArenaHelper.GetEntranceFee( roundData, @@ -89,10 +92,12 @@ public void Execute_Season_Success() [Fact] public void Execute_Championship_Success() { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Championship && - e2.RequiredMedalCount > 0)); + var row = _tableSheets.ArenaSheet.OrderedList!.First( + e => + e.Round.Any( + e2 => + e2.ArenaType == ArenaType.Championship && + e2.RequiredMedalCount > 0)); Assert.True(row.TryGetChampionshipRound(out var roundData)); var blockIndex = roundData.StartBlockIndex; var fee = ArenaHelper.GetEntranceFee( @@ -125,60 +130,66 @@ public void Execute_Championship_Success() [InlineData(int.MaxValue)] public void Execute_SheetRowNotFoundException(int championshipId) { - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - 0, - 0, - _myAvatarState.address, - championshipId, - 1, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + _world, + _myAgentState.address, + 0, + 0, + _myAvatarState.address, + championshipId, + 1, + new List(), + new List(), + new List())); } [Theory] [InlineData(10)] public void Execute_RoundNotFoundByIdsException(int round) { - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - 0, - 0, - _myAvatarState.address, - 1, - round, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + _world, + _myAgentState.address, + 0, + 0, + _myAvatarState.address, + 1, + round, + new List(), + new List(), + new List())); } [Fact] public void Execute_NotEnoughFungibleAssetValueException() { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Season && - e2.EntranceFee > 0)); - var roundData = row.Round.First(e => - e.ArenaType == ArenaType.Season && - e.EntranceFee > 0); + var row = _tableSheets.ArenaSheet.OrderedList!.First( + e => + e.Round.Any( + e2 => + e2.ArenaType == ArenaType.Season && + e2.EntranceFee > 0)); + var roundData = row.Round.First( + e => + e.ArenaType == ArenaType.Season && + e.EntranceFee > 0); var blockIndex = roundData.StartBlockIndex; // with 0 assets. - Assert.Throws(() => Execute( - _world, - _myAgentState.address, - blockIndex, - 0, - _myAvatarState.address, - row.ChampionshipId, - roundData.Round, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + _world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); // get discounted fee. var fee = ArenaHelper.GetEntranceFee( @@ -189,17 +200,18 @@ public void Execute_NotEnoughFungibleAssetValueException() .MintAsset(new ActionContext(), _myAgentState.address, fee) .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); // with not enough assets in discount period. - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex - 1, - 0, - _myAvatarState.address, - row.ChampionshipId, - roundData.Round, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + world, + _myAgentState.address, + blockIndex - 1, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); // get original fee. fee = ArenaHelper.GetEntranceFee( @@ -210,26 +222,29 @@ public void Execute_NotEnoughFungibleAssetValueException() .MintAsset(new ActionContext(), _myAgentState.address, fee) .BurnAsset(new ActionContext(), _myAgentState.address, new FungibleAssetValue(fee.Currency, 0, 1)); // with not enough assets in discount period. - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex, - 0, - _myAvatarState.address, - row.ChampionshipId, - roundData.Round, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); } [Fact] public void Execute_NotEnoughMedalException() { - var row = _tableSheets.ArenaSheet.OrderedList!.First(e => - e.Round.Any(e2 => - e2.ArenaType == ArenaType.Championship && - e2.RequiredMedalCount > 0)); + var row = _tableSheets.ArenaSheet.OrderedList!.First( + e => + e.Round.Any( + e2 => + e2.ArenaType == ArenaType.Championship && + e2.RequiredMedalCount > 0)); Assert.True(row.TryGetChampionshipRound(out var roundData)); var blockIndex = roundData.StartBlockIndex; var fee = ArenaHelper.GetEntranceFee( @@ -237,17 +252,18 @@ public void Execute_NotEnoughMedalException() blockIndex, _myAvatarState.level); var world = _world.MintAsset(new ActionContext(), _myAgentState.address, fee); - Assert.Throws(() => Execute( - world, - _myAgentState.address, - blockIndex, - 0, - _myAvatarState.address, - row.ChampionshipId, - roundData.Round, - new List(), - new List(), - new List())); + Assert.Throws( + () => Execute( + world, + _myAgentState.address, + blockIndex, + 0, + _myAvatarState.address, + row.ChampionshipId, + roundData.Round, + new List(), + new List(), + new List())); } private IWorld Execute( @@ -271,13 +287,14 @@ private IWorld Execute( equipments = equipments, runeInfos = runeInfos, }; - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = signer, - BlockIndex = blockIndex, - RandomSeed = randomSeed, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = signer, + BlockIndex = blockIndex, + RandomSeed = randomSeed, + }); // check ItemSlotState var itemSlotState = new ItemSlotState(BattleType.Arena); diff --git a/.Lib9c.Tests/Action/MigrateFeeTest.cs b/.Lib9c.Tests/Action/MigrateFeeTest.cs index 56f4f946b4..26e1135ebe 100644 --- a/.Lib9c.Tests/Action/MigrateFeeTest.cs +++ b/.Lib9c.Tests/Action/MigrateFeeTest.cs @@ -49,13 +49,14 @@ public void Execute() Memo = "memo", }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = state, - RandomSeed = 0, - Signer = admin, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = state, + RandomSeed = 0, + Signer = admin, + }); foreach (var (sender, _, _) in transferData) { @@ -126,13 +127,15 @@ public void Execute_Throw_InsufficientBalanceException() Memo = "memo", }; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = state, - RandomSeed = 0, - Signer = admin, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = state, + RandomSeed = 0, + Signer = admin, + })); } } } diff --git a/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs b/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs index ec24c0c5f2..f3f4d17fe5 100644 --- a/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs +++ b/.Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs @@ -56,7 +56,7 @@ public MigrateMonsterCollectionTest(ITestOutputHelper outputHelper) .SetAvatarState(_avatarAddress, avatarState) .SetLegacyState(Addresses.GoldCurrency, goldCurrencyState.Serialize()); - foreach ((var key, var value) in sheets) + foreach (var (key, value) in sheets) { _state = _state .SetLegacyState(Addresses.TableSheet.Derive(key), value.Serialize()); @@ -68,19 +68,24 @@ public void Execute_ThrowsIfAlreadyStakeStateExists() { var monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); var monsterCollectionState = new MonsterCollectionState( - monsterCollectionAddress, 1, 0); + monsterCollectionAddress, + 1, + 0); var stakeStateAddress = StakeState.DeriveAddress(_signer); var states = _state.SetLegacyState( - stakeStateAddress, new StakeState(stakeStateAddress, 0).SerializeV2()) + stakeStateAddress, + new StakeState(stakeStateAddress, 0).SerializeV2()) .SetLegacyState(monsterCollectionAddress, monsterCollectionState.Serialize()); var action = new MigrateMonsterCollection(_avatarAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = states, - Signer = _signer, - BlockIndex = 0, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signer, + BlockIndex = 0, + RandomSeed = 0, + })); } [Fact] @@ -88,25 +93,29 @@ public void Execute_After_V100220ObsoleteIndex() { var monsterCollectionAddress = MonsterCollectionState.DeriveAddress(_signer, 0); var monsterCollectionState = new MonsterCollectionState( - monsterCollectionAddress, 1, ActionObsoleteConfig.V100220ObsoleteIndex - MonsterCollectionState.RewardInterval); + monsterCollectionAddress, + 1, + ActionObsoleteConfig.V100220ObsoleteIndex - MonsterCollectionState.RewardInterval); var currency = _state.GetGoldCurrency(); var context = new ActionContext(); var states = _state .SetLegacyState(monsterCollectionAddress, monsterCollectionState.Serialize()) .MintAsset(context, monsterCollectionAddress, currency * 100); var action = new MigrateMonsterCollection(_avatarAddress); - states = action.Execute(new ActionContext - { - PreviousState = states, - Signer = _signer, - BlockIndex = ActionObsoleteConfig.V100220ObsoleteIndex + 1, - RandomSeed = 0, - }); + states = action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signer, + BlockIndex = ActionObsoleteConfig.V100220ObsoleteIndex + 1, + RandomSeed = 0, + }); - Assert.True(states.TryGetAvatarState( - _signer, - _avatarAddress, - out var avatarState)); + Assert.True( + states.TryGetAvatarState( + _signer, + _avatarAddress, + out var avatarState)); Assert.Equal(80, avatarState.inventory.Items.First(item => item.item.Id == 400000).count); Assert.Equal(1, avatarState.inventory.Items.First(item => item.item.Id == 500000).count); @@ -130,13 +139,14 @@ public void Execute(int collectionLevel, long claimBlockIndex, long receivedBloc Assert.Equal(stakedAmount * currency, states.GetBalance(collectionAddress, currency)); var action = new MigrateMonsterCollection(_avatarAddress); - states = action.Execute(new ActionContext - { - PreviousState = states, - Signer = _signer, - BlockIndex = claimBlockIndex, - RandomSeed = 0, - }); + states = action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signer, + BlockIndex = claimBlockIndex, + RandomSeed = 0, + }); Assert.True(states.TryGetStakeState(_signer, out var stakeState)); Assert.Equal( @@ -167,7 +177,7 @@ public void Serialization() private class ExecuteFixture : IEnumerable { - private readonly List _data = new() + private readonly List _data = new () { new object[] { diff --git a/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs b/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs index 3b908c059c..eae2e9000b 100644 --- a/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs +++ b/.Lib9c.Tests/Action/MigrationActivatedAccountsStateTest.cs @@ -24,12 +24,13 @@ public void Execute() var action = new MigrationActivatedAccountsState(); - var nextState = action.Execute(new ActionContext() - { - PreviousState = state, - Signer = admin, - BlockIndex = 1, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = admin, + BlockIndex = 1, + }); var nextAccountsState = new ActivatedAccountsState( (Dictionary)nextState.GetLegacyState(ActivatedAccountsState.Address) diff --git a/.Lib9c.Tests/Action/MintAssetsTest.cs b/.Lib9c.Tests/Action/MintAssetsTest.cs index 4912009be8..a180b480f3 100644 --- a/.Lib9c.Tests/Action/MintAssetsTest.cs +++ b/.Lib9c.Tests/Action/MintAssetsTest.cs @@ -63,10 +63,12 @@ public void PlainValue() var act = new MintAssets(r, null); var expected = Dictionary.Empty .Add("type_id", MintAssets.TypeIdentifier) - .Add("values", List.Empty - .Add(Null.Value) - .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) - .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); + .Add( + "values", + List.Empty + .Add(Null.Value) + .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) + .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); Assert.Equal( expected, act.PlainValue @@ -75,10 +77,12 @@ public void PlainValue() var act2 = new MintAssets(r, "memo"); var expected2 = Dictionary.Empty .Add("type_id", MintAssets.TypeIdentifier) - .Add("values", List.Empty - .Add((Text)"memo") - .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) - .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); + .Add( + "values", + List.Empty + .Add((Text)"memo") + .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) + .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); Assert.Equal( expected2, act2.PlainValue @@ -90,10 +94,12 @@ public void LoadPlainValue() { var pv = Dictionary.Empty .Add("type_id", "mint_assets") - .Add("values", List.Empty - .Add(default(Null)) - .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) - .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); + .Add( + "values", + List.Empty + .Add(default(Null)) + .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) + .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); var act = new MintAssets(); act.LoadPlainValue(pv); @@ -107,10 +113,12 @@ public void LoadPlainValue() var pv2 = Dictionary.Empty .Add("type_id", "mint_assets") - .Add("values", List.Empty - .Add((Text)"memo") - .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) - .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); + .Add( + "values", + List.Empty + .Add((Text)"memo") + .Add(new List(default(Address).Bencoded, (_ncgCurrency * 100).Serialize(), default(Null))) + .Add(new List(new Address("0x47d082a115c63e7b58b1532d20e631538eafadde").Bencoded, (_ncgCurrency * 1000).Serialize(), default(Null)))); var act2 = new MintAssets(); act2.LoadPlainValue(pv2); Assert.Equal("memo", act2.Memo); @@ -265,21 +273,23 @@ public void Execute_Throws_InvalidMinterException() } // Denies others - Assert.Throws(() => action.Execute( - new ActionContext() - { - PreviousState = _prevState, - Signer = default, - BlockIndex = 1, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = _prevState, + Signer = default, + BlockIndex = 1, + } + )); } [Fact] public void Execute_Crystal() { - var tx = Transaction.Deserialize(Convert.FromBase64String( - "ZDE6UzcxOjBFAiEAhzt5mDMzPwi6y+W+DJ53T4TKwt6YMaFTi38rKYqf7ZMCICV36ngA3Gi+rXkdG5hCUtlLXjAz8H2IKMNaCdCy/N90MTphbGR1Nzp0eXBlX2lkdTExOm1pbnRfYXNzZXRzdTY6dmFsdWVzbHU3Mzp7ImlhcCI6IHsiZ19za3UiOiAiZ19wa2dfYmxhY2tmcmlkYXkwMSIsICJhX3NrdSI6ICJhX3BrZ19ibGFja2ZyaWRheTAxIn19bDIwOgNS/yy36WH9ZHgDqZJiTdhQeCGFbGR1MTM6ZGVjaW1hbFBsYWNlczE6EnU3Om1pbnRlcnNudTY6dGlja2VydTc6Q1JZU1RBTGVpMjUwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMGVlbmVsMjA6H3yZ4KY1m33Wn0P0t+LAvTf5oidubDMyOjmR4E3YCNwLwksh9a23vxmXMS+HANrxM0vzSTbooIE6aTMwMDAwZWVlbDIwOh98meCmNZt91p9D9LfiwL03+aInbmwzMjr4+vksnA0OjgZpQ2Hqh7/IspqK6N6TBEuYRwpXY27Q4Gk0MDBlZWVlZWUxOmczMjpyn6JpWGSKNbU+jjkF0R7FOxtJKb9fSZiErtffYW9ZEzE6bGk0ZTE6bWxkdTEzOmRlY2ltYWxQbGFjZXMxOhJ1NzptaW50ZXJzbnU2OnRpY2tlcnU0Ok1lYWRlaTEwMDAwMDAwMDAwMDAwMDAwMDBlZTE6bmkxMTU3N2UxOnA2NToEq54xog2Nv1BCv8Js6dntmg4yrXh6HlqjroGI+lFDhhU1rMcTLNjnTUwfC5T4Q1deOt1piNPMsfVNfFn7lTXXiTE6czIwOhwq6XOAz7T3MgSeRU9tmiXUlnxvMTp0dTI3OjIyMDEtMDEtMzFUMjM6NTk6NTkuOTk5MDAwWjE6dWxlZQ==")); + var tx = Transaction.Deserialize( + Convert.FromBase64String( + "ZDE6UzcxOjBFAiEAhzt5mDMzPwi6y+W+DJ53T4TKwt6YMaFTi38rKYqf7ZMCICV36ngA3Gi+rXkdG5hCUtlLXjAz8H2IKMNaCdCy/N90MTphbGR1Nzp0eXBlX2lkdTExOm1pbnRfYXNzZXRzdTY6dmFsdWVzbHU3Mzp7ImlhcCI6IHsiZ19za3UiOiAiZ19wa2dfYmxhY2tmcmlkYXkwMSIsICJhX3NrdSI6ICJhX3BrZ19ibGFja2ZyaWRheTAxIn19bDIwOgNS/yy36WH9ZHgDqZJiTdhQeCGFbGR1MTM6ZGVjaW1hbFBsYWNlczE6EnU3Om1pbnRlcnNudTY6dGlja2VydTc6Q1JZU1RBTGVpMjUwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMGVlbmVsMjA6H3yZ4KY1m33Wn0P0t+LAvTf5oidubDMyOjmR4E3YCNwLwksh9a23vxmXMS+HANrxM0vzSTbooIE6aTMwMDAwZWVlbDIwOh98meCmNZt91p9D9LfiwL03+aInbmwzMjr4+vksnA0OjgZpQ2Hqh7/IspqK6N6TBEuYRwpXY27Q4Gk0MDBlZWVlZWUxOmczMjpyn6JpWGSKNbU+jjkF0R7FOxtJKb9fSZiErtffYW9ZEzE6bGk0ZTE6bWxkdTEzOmRlY2ltYWxQbGFjZXMxOhJ1NzptaW50ZXJzbnU2OnRpY2tlcnU0Ok1lYWRlaTEwMDAwMDAwMDAwMDAwMDAwMDBlZTE6bmkxMTU3N2UxOnA2NToEq54xog2Nv1BCv8Js6dntmg4yrXh6HlqjroGI+lFDhhU1rMcTLNjnTUwfC5T4Q1deOt1piNPMsfVNfFn7lTXXiTE6czIwOhwq6XOAz7T3MgSeRU9tmiXUlnxvMTp0dTI3OjIyMDEtMDEtMzFUMjM6NTk6NTkuOTk5MDAwWjE6dWxlZQ==")); var a = tx.Actions.First(); var action = new MintAssets(); action.LoadPlainValue(a); diff --git a/.Lib9c.Tests/Action/PatchTableSheetTest.cs b/.Lib9c.Tests/Action/PatchTableSheetTest.cs index 748c0bc0d1..af6751a2a6 100644 --- a/.Lib9c.Tests/Action/PatchTableSheetTest.cs +++ b/.Lib9c.Tests/Action/PatchTableSheetTest.cs @@ -50,11 +50,12 @@ public void Execute() TableName = nameof(WorldSheet), TableCsv = worldSheetCsvColumnLine, }; - var nextState = patchTableSheetAction.Execute(new ActionContext - { - BlockIndex = 0, - PreviousState = _initialState, - }); + var nextState = patchTableSheetAction.Execute( + new ActionContext + { + BlockIndex = 0, + PreviousState = _initialState, + }); var nextWorldSheetCsv = nextState.GetSheetCsv(); Assert.Single(nextWorldSheetCsv.Split('\n')); @@ -68,11 +69,12 @@ public void Execute() TableName = nameof(WorldSheet), TableCsv = worldSheetCsv, }; - nextState = patchTableSheetAction.Execute(new ActionContext - { - BlockIndex = 0, - PreviousState = _initialState, - }); + nextState = patchTableSheetAction.Execute( + new ActionContext + { + BlockIndex = 0, + PreviousState = _initialState, + }); nextWorldSheet = nextState.GetSheet(); Assert.Equal(worldSheetRowCount, nextWorldSheet.Count); @@ -126,30 +128,32 @@ public void CheckPermission() TableCsv = "New Value", }; - var exc1 = Assert.Throws(() => - { - action.Execute( - new ActionContext() - { - BlockIndex = 101, - PreviousState = state, - Signer = adminAddress, - } - ); - }); + var exc1 = Assert.Throws( + () => + { + action.Execute( + new ActionContext() + { + BlockIndex = 101, + PreviousState = state, + Signer = adminAddress, + } + ); + }); Assert.Equal(101, exc1.BlockIndex); - var exc2 = Assert.Throws(() => - { - action.Execute( - new ActionContext() - { - BlockIndex = 5, - PreviousState = state, - Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), - } - ); - }); + var exc2 = Assert.Throws( + () => + { + action.Execute( + new ActionContext() + { + BlockIndex = 5, + PreviousState = state, + Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), + } + ); + }); Assert.Equal(new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), exc2.Signer); } diff --git a/.Lib9c.Tests/Action/PendingActivationDoesNotExistsExceptionTest.cs b/.Lib9c.Tests/Action/PendingActivationDoesNotExistsExceptionTest.cs index 874b7e9c59..625cd0c328 100644 --- a/.Lib9c.Tests/Action/PendingActivationDoesNotExistsExceptionTest.cs +++ b/.Lib9c.Tests/Action/PendingActivationDoesNotExistsExceptionTest.cs @@ -14,13 +14,14 @@ public void Serialize() var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); var exc = new PendingActivationDoesNotExistsException( - new Address(new byte[] - { - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, - }) + new Address( + new byte[] + { + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, + }) ); formatter.Serialize(ms, exc); diff --git a/.Lib9c.Tests/Action/PetEnhancement0Test.cs b/.Lib9c.Tests/Action/PetEnhancement0Test.cs index b8ca0881c8..0712a4aa2a 100644 --- a/.Lib9c.Tests/Action/PetEnhancement0Test.cs +++ b/.Lib9c.Tests/Action/PetEnhancement0Test.cs @@ -63,30 +63,32 @@ public void Execute_Success( public void Execute_Throw_InvalidActionFieldException_AgentAddress() { var invalidAgentAddr = new PrivateKey().Address; - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - invalidAgentAddr, - _avatarAddr, - _targetPetId, - 0, - 1)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + invalidAgentAddr, + _avatarAddr, + _targetPetId, + 0, + 1)); } [Fact] public void Execute_Throw_InvalidActionFieldException_AvatarAddress() { var invalidAvatarAddr = new PrivateKey().Address; - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - invalidAvatarAddr, - _targetPetId, - 0, - 1)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + invalidAvatarAddr, + _targetPetId, + 0, + 1)); } [Theory] @@ -98,43 +100,46 @@ public void Execute_Throw_InvalidActionFieldException_PetLevel( int currentPetLevel, int targetPetLevel) { - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - _avatarAddr, - _targetPetId, - currentPetLevel, - targetPetLevel)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + _avatarAddr, + _targetPetId, + currentPetLevel, + targetPetLevel)); } [Fact] public void Execute_Throw_SheetRowNotFoundException() { // PetSheet - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - _avatarAddr, - _targetPetId, - 0, - 1, - removePetRow: true)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + _avatarAddr, + _targetPetId, + 0, + 1, + removePetRow: true)); // PetCostSheet - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - _avatarAddr, - _targetPetId, - 0, - 1, - removePetCostRow: true)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + _avatarAddr, + _targetPetId, + 0, + 1, + removePetCostRow: true)); } [Fact] @@ -142,30 +147,32 @@ public void Execute_Throw_PetCostNotFoundException() { const int targetPetLevel = 1; - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - _avatarAddr, - _targetPetId, - 0, - targetPetLevel, - removePetCostRowWithTargetPetLevel: true)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + _avatarAddr, + _targetPetId, + 0, + targetPetLevel, + removePetCostRowWithTargetPetLevel: true)); } [Fact] public void Execute_Throw_RoundNotFoundException() { - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex - 1, - _agentAddr, - _avatarAddr, - _targetPetId, - 0, - 1)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex - 1, + _agentAddr, + _avatarAddr, + _targetPetId, + 0, + 1)); } [Theory] @@ -174,16 +181,17 @@ public void Execute_Throw_NotEnoughFungibleAssetValueException( int currentPetLevel, int targetPetLevel) { - Assert.Throws(() => - Execute( - _initialStatesWithAvatarStateV2, - _firstRoundStartBlockIndex, - _agentAddr, - _avatarAddr, - _targetPetId, - currentPetLevel, - targetPetLevel, - false)); + Assert.Throws( + () => + Execute( + _initialStatesWithAvatarStateV2, + _firstRoundStartBlockIndex, + _agentAddr, + _avatarAddr, + _targetPetId, + currentPetLevel, + targetPetLevel, + false)); } private static IWorld Execute( @@ -288,13 +296,14 @@ private static IWorld Execute( PetId = petId, TargetLevel = targetPetLevel, }; - var nextStates = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = prevStates, - RandomSeed = 0, - Signer = agentAddr, - }); + var nextStates = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = prevStates, + RandomSeed = 0, + Signer = agentAddr, + }); var nextNcgBal = nextStates.GetBalance(agentAddr, ncgCurrency); var nextSoulStoneBal = nextStates.GetBalance(avatarAddr, soulStoneCurrency); Assert.Equal(0, nextNcgBal.MajorUnit); diff --git a/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs b/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs index a1208b49b3..88f7aa5afc 100644 --- a/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs +++ b/.Lib9c.Tests/Action/PrepareRewardAssetsTest.cs @@ -44,12 +44,13 @@ public void Execute(bool admin, bool includeNcg, Type exc) var action = new PrepareRewardAssets(poolAddress, assets); if (exc is null) { - var nextState = action.Execute(new ActionContext - { - Signer = admin ? adminAddress : poolAddress, - BlockIndex = 1, - PreviousState = state, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = admin ? adminAddress : poolAddress, + BlockIndex = 1, + PreviousState = state, + }); foreach (var asset in assets) { Assert.Equal(asset, nextState.GetBalance(poolAddress, asset.Currency)); @@ -57,12 +58,15 @@ public void Execute(bool admin, bool includeNcg, Type exc) } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - Signer = admin ? adminAddress : poolAddress, - BlockIndex = 1, - PreviousState = state, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + Signer = admin ? adminAddress : poolAddress, + BlockIndex = 1, + PreviousState = state, + })); } } } diff --git a/.Lib9c.Tests/Action/RaidTest.cs b/.Lib9c.Tests/Action/RaidTest.cs index 51aab04f26..8159364ab9 100644 --- a/.Lib9c.Tests/Action/RaidTest.cs +++ b/.Lib9c.Tests/Action/RaidTest.cs @@ -97,15 +97,16 @@ int runeId2 { var blockIndex = _tableSheets.WorldBossListSheet.Values .OrderBy(x => x.StartedBlockIndex) - .First(x => - { - if (exc == typeof(InsufficientBalanceException)) + .First( + x => { - return ncgExist ? x.TicketPrice > 0 : x.EntranceFee > 0; - } + if (exc == typeof(InsufficientBalanceException)) + { + return ncgExist ? x.TicketPrice > 0 : x.EntranceFee > 0; + } - return true; - }) + return true; + }) .StartedBlockIndex; var action = new Raid @@ -429,22 +430,26 @@ int runeId2 SlotIndex = 1, }; - state = unlockRuneSlot.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = state, - Signer = _agentAddress, - RandomSeed = 0, - }); + state = unlockRuneSlot.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = state, + Signer = _agentAddress, + RandomSeed = 0, + }); } - Assert.Throws(exc, () => action.Execute(new ActionContext - { - BlockIndex = blockIndex + executeOffset, - PreviousState = state, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + BlockIndex = blockIndex + executeOffset, + PreviousState = state, + RandomSeed = 0, + Signer = _agentAddress, + })); } } @@ -567,13 +572,14 @@ public void Execute_With_Reward() ); var blockIndex = worldBossRow.StartedBlockIndex + gameConfigState.WorldBossRequiredInterval; - var nextState = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = state, - RandomSeed = randomSeed, - Signer = _agentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = state, + RandomSeed = randomSeed, + Signer = _agentAddress, + }); Assert.True(nextState.TryGetLegacyState(raiderAddress, out List rawRaider)); var nextRaiderState = new RaiderState(rawRaider); diff --git a/.Lib9c.Tests/Action/RankingBattleTest.cs b/.Lib9c.Tests/Action/RankingBattleTest.cs index ae617ff92e..17729cb901 100644 --- a/.Lib9c.Tests/Action/RankingBattleTest.cs +++ b/.Lib9c.Tests/Action/RankingBattleTest.cs @@ -162,15 +162,17 @@ public void ExecuteActionObsoletedException() equipmentIds = new List(), }; - Assert.Throws(() => - { - action.Execute(new ActionContext + Assert.Throws( + () => { - PreviousState = previousState, - Signer = _agent1Address, - RandomSeed = 0, + action.Execute( + new ActionContext + { + PreviousState = previousState, + Signer = _agent1Address, + RandomSeed = 0, + }); }); - }); } } } diff --git a/.Lib9c.Tests/Action/RapidCombinationTest.cs b/.Lib9c.Tests/Action/RapidCombinationTest.cs index 347c1bf82e..1760a54ee2 100644 --- a/.Lib9c.Tests/Action/RapidCombinationTest.cs +++ b/.Lib9c.Tests/Action/RapidCombinationTest.cs @@ -98,8 +98,9 @@ public void Execute() _initialState.GetSheet(), slotStateUnlockStage); - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.Hourglass); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.Hourglass); avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), 83); avatarState.inventory.AddItem(ItemFactory.CreateTradableMaterial(row), 100); Assert.True(avatarState.inventory.HasFungibleItem(row.ItemId, 0, 183)); @@ -144,12 +145,13 @@ public void Execute() slotIndexList = new List { 0, }, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = 51, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = 51, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); var item = nextAvatarState.inventory.Equipments.First(); @@ -170,8 +172,9 @@ public void Execute_Many() _initialState.GetSheet(), slotStateUnlockStage); - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.Hourglass); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.Hourglass); var numOfHourglass = 83 * AvatarState.DefaultCombinationSlotCount; avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), numOfHourglass); @@ -228,12 +231,13 @@ public void Execute_Many() slotIndexList = slotIndexList, }; - var nextState = action.Execute(new ActionContext - { - PreviousState = targetState, - Signer = _agentAddress, - BlockIndex = 51, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = targetState, + Signer = _agentAddress, + BlockIndex = 51, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); var item = nextAvatarState.inventory.Equipments.First(); @@ -246,10 +250,11 @@ public void Execute_Many() [Fact] public void Execute_Throw_CombinationSlotResultNullException() { - var slotAddress = _avatarAddress.Derive(string.Format( - CultureInfo.InvariantCulture, - CombinationSlotState.DeriveFormat, - 0)); + var slotAddress = _avatarAddress.Derive( + string.Format( + CultureInfo.InvariantCulture, + CombinationSlotState.DeriveFormat, + 0)); var slotState = new CombinationSlotState(slotAddress, 0); slotState.Update(null, 0, 0); @@ -262,12 +267,14 @@ public void Execute_Throw_CombinationSlotResultNullException() slotIndexList = new List { 0, }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = 1, + })); } [Theory] @@ -317,12 +324,14 @@ public void Execute_Throw_RequiredBlockIndexException(int itemRequiredBlockIndex slotIndexList = new List { 0, }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = contextBlockIndex, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = contextBlockIndex, + })); } [Theory] @@ -392,12 +401,14 @@ public void Execute_Throw_NotEnoughMaterialException(int materialCount, int trad slotIndexList = new List { 0, }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = 51, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = 51, + })); } [Theory] @@ -475,8 +486,9 @@ public void Execute_Throw_RequiredAppraiseBlockException() _initialState.GetSheet(), slotStateUnlockStage); - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.Hourglass); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.Hourglass); avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), 22); var firstEquipmentRow = _tableSheets.EquipmentItemSheet.First; @@ -520,12 +532,14 @@ public void Execute_Throw_RequiredAppraiseBlockException() slotIndexList = new List { 0, }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = 1, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = 1, + })); } [Theory] @@ -544,8 +558,9 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( _initialState.GetSheet(), slotStateUnlockStage); - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.Hourglass); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.Hourglass); avatarState.inventory.AddItem(ItemFactory.CreateMaterial(row), 83); avatarState.inventory.AddItem(ItemFactory.CreateTradableMaterial(row), 100); Assert.True(avatarState.inventory.HasFungibleItem(row.ItemId, 0, 183)); @@ -588,10 +603,11 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( case 9: { - Assert.True(ItemEnhancement9.TryGetRow( - equipment, - _tableSheets.EnhancementCostSheetV2, - out var costRow)); + Assert.True( + ItemEnhancement9.TryGetRow( + equipment, + _tableSheets.EnhancementCostSheetV2, + out var costRow)); var equipmentResult = ItemEnhancement9.GetEnhancementResult(costRow, random); equipment.LevelUp( random, @@ -613,10 +629,11 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( case 10: { - Assert.True(ItemEnhancement10.TryGetRow( - equipment, - _tableSheets.EnhancementCostSheetV2, - out var costRow)); + Assert.True( + ItemEnhancement10.TryGetRow( + equipment, + _tableSheets.EnhancementCostSheetV2, + out var costRow)); var equipmentResult = ItemEnhancement10.GetEnhancementResult(costRow, random); equipment.LevelUp( random, @@ -638,10 +655,11 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( case 11: { - Assert.True(ItemEnhancement11.TryGetRow( - equipment, - _tableSheets.EnhancementCostSheetV2, - out var costRow)); + Assert.True( + ItemEnhancement11.TryGetRow( + equipment, + _tableSheets.EnhancementCostSheetV2, + out var costRow)); var equipmentResult = ItemEnhancement11.GetEnhancementResult(costRow, random); equipment.LevelUp( random, @@ -688,12 +706,13 @@ public void Execute_NotThrow_InvalidOperationException_When_TargetSlotCreatedBy( slotIndexList = new List { 0, }, }; - action.Execute(new ActionContext - { - PreviousState = tempState, - Signer = _agentAddress, - BlockIndex = 51, - }); + action.Execute( + new ActionContext + { + PreviousState = tempState, + Signer = _agentAddress, + BlockIndex = 51, + }); } } } diff --git a/.Lib9c.Tests/Action/ReRegisterProductTest.cs b/.Lib9c.Tests/Action/ReRegisterProductTest.cs index 91c49c27cb..7326bc08ee 100644 --- a/.Lib9c.Tests/Action/ReRegisterProductTest.cs +++ b/.Lib9c.Tests/Action/ReRegisterProductTest.cs @@ -228,13 +228,14 @@ bool fromPreviousAction updateSellInfos = new[] { updateSellInfo, }, }; - var expectedState = action.Execute(new ActionContext - { - BlockIndex = 101, - PreviousState = prevState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var expectedState = action.Execute( + new ActionContext + { + BlockIndex = 101, + PreviousState = prevState, + RandomSeed = 0, + Signer = _agentAddress, + }); var updateSellShopAddress = ShardedShopStateV2.DeriveAddress(itemSubType, updateSellOrderId); var nextShopState = new ShardedShopStateV2((Dictionary)expectedState.GetLegacyState(updateSellShopAddress)); @@ -274,13 +275,14 @@ bool fromPreviousAction }, }; - var actualState = reRegister.Execute(new ActionContext - { - BlockIndex = 101, - PreviousState = prevState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var actualState = reRegister.Execute( + new ActionContext + { + BlockIndex = 101, + PreviousState = prevState, + RandomSeed = 0, + Signer = _agentAddress, + }); var targetShopState = new ShardedShopStateV2((Dictionary)actualState.GetLegacyState(shardedShopAddress)); var nextOrderDigestListState = new OrderDigestListState((Dictionary)actualState.GetLegacyState(orderDigestList.Address)); diff --git a/.Lib9c.Tests/Action/RedeemCodeTest.cs b/.Lib9c.Tests/Action/RedeemCodeTest.cs index 56f92de295..bbf5d01a30 100644 --- a/.Lib9c.Tests/Action/RedeemCodeTest.cs +++ b/.Lib9c.Tests/Action/RedeemCodeTest.cs @@ -18,21 +18,23 @@ namespace Lib9c.Tests.Action public class RedeemCodeTest { - private readonly Address _agentAddress = new (new byte[] - { - 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, - }); + private readonly Address _agentAddress = new ( + new byte[] + { + 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, + }); - private readonly Address _avatarAddress = new (new byte[] - { - 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, - }); + private readonly Address _avatarAddress = new ( + new byte[] + { + 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, + }); private readonly Dictionary _sheets; private readonly TableSheets _tableSheets; @@ -48,10 +50,11 @@ public void Execute() { var privateKey = new PrivateKey(); var publicKey = privateKey.PublicKey; - var prevRedeemCodesState = new RedeemCodeState(new Dictionary() - { - [publicKey] = new (1), - }); + var prevRedeemCodesState = new RedeemCodeState( + new Dictionary() + { + [publicKey] = new (1), + }); var gameConfigState = new GameConfigState(); var agentState = new AgentState(_agentAddress); agentState.avatarAddresses[0] = _avatarAddress; @@ -89,14 +92,15 @@ public void Execute() _avatarAddress ); - var nextState = redeemCode.Execute(new ActionContext() - { - BlockIndex = 1, - Miner = default, - PreviousState = initialState, - Signer = _agentAddress, - RandomSeed = 0, - }); + var nextState = redeemCode.Execute( + new ActionContext() + { + BlockIndex = 1, + Miner = default, + PreviousState = initialState, + Signer = _agentAddress, + RandomSeed = 0, + }); // Check target avatar & agent var nextAvatarState = nextState.GetAvatarState(_avatarAddress); diff --git a/.Lib9c.Tests/Action/RegisterProduct0Test.cs b/.Lib9c.Tests/Action/RegisterProduct0Test.cs index b6b4e76f76..ebf3946dfe 100644 --- a/.Lib9c.Tests/Action/RegisterProduct0Test.cs +++ b/.Lib9c.Tests/Action/RegisterProduct0Test.cs @@ -239,13 +239,14 @@ public void Execute() }, }, }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + }); var nextAvatarState = nextState.GetAvatarState(AvatarAddress); Assert.Empty(nextAvatarState.inventory.Items); @@ -293,12 +294,15 @@ public void Execute_Validate_RegisterInfos(params ValidateMember[] validateMembe AvatarAddress = AvatarAddress, RegisterInfos = new[] { registerInfo, }, }; - Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext - { - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + validateMember.Exc, + () => action.Execute( + new ActionContext + { + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + })); } } } @@ -363,13 +367,15 @@ public void Execute_Throw_ItemDoesNotExistException(ProductType type, int itemCo }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - Signer = _agentAddress, - BlockIndex = blockIndex, - RandomSeed = 0, - PreviousState = _initialState, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + Signer = _agentAddress, + BlockIndex = blockIndex, + RandomSeed = 0, + PreviousState = _initialState, + })); } [Fact] diff --git a/.Lib9c.Tests/Action/RegisterProductTest.cs b/.Lib9c.Tests/Action/RegisterProductTest.cs index 48d31d1bb4..afb223aa41 100644 --- a/.Lib9c.Tests/Action/RegisterProductTest.cs +++ b/.Lib9c.Tests/Action/RegisterProductTest.cs @@ -267,13 +267,14 @@ public void Execute() }, }, }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + }); var nextAvatarState = nextState.GetAvatarState(AvatarAddress); Assert.Empty(nextAvatarState.inventory.Items); @@ -321,12 +322,15 @@ public void Execute_Validate_RegisterInfos(params ValidateMember[] validateMembe AvatarAddress = AvatarAddress, RegisterInfos = new[] { registerInfo, }, }; - Assert.Throws(validateMember.Exc, () => action.Execute(new ActionContext - { - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + validateMember.Exc, + () => action.Execute( + new ActionContext + { + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + })); } } } @@ -392,13 +396,15 @@ public void Execute_Throw_ItemDoesNotExistException(ProductType type, int itemCo }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - Signer = _agentAddress, - BlockIndex = blockIndex, - RandomSeed = 0, - PreviousState = _initialState, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + Signer = _agentAddress, + BlockIndex = blockIndex, + RandomSeed = 0, + PreviousState = _initialState, + })); } [Fact] @@ -444,13 +450,15 @@ public void Execute_Throw_DuplicateOrderIdException() }, }, }; - Assert.Throws(() => action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + })); } public class ValidateMember diff --git a/.Lib9c.Tests/Action/RenewAdminStateTest.cs b/.Lib9c.Tests/Action/RenewAdminStateTest.cs index 77816069f3..59005a3aee 100644 --- a/.Lib9c.Tests/Action/RenewAdminStateTest.cs +++ b/.Lib9c.Tests/Action/RenewAdminStateTest.cs @@ -31,11 +31,12 @@ public void Execute() { var newValidUntil = _validUntil + 1000; var action = new RenewAdminState(newValidUntil); - var stateDelta = action.Execute(new ActionContext - { - PreviousState = _stateDelta, - Signer = _adminPrivateKey.Address, - }); + var stateDelta = action.Execute( + new ActionContext + { + PreviousState = _stateDelta, + Signer = _adminPrivateKey.Address, + }); var adminState = new AdminState((Bencodex.Types.Dictionary)stateDelta.GetLegacyState(Addresses.Admin)); Assert.Equal(newValidUntil, adminState.ValidUntil); @@ -47,15 +48,17 @@ public void RejectSignerExceptAdminAddress() { var newValidUntil = _validUntil + 1000; var action = new RenewAdminState(newValidUntil); - Assert.Throws(() => - { - var userPrivateKey = new PrivateKey(); - action.Execute(new ActionContext + Assert.Throws( + () => { - PreviousState = _stateDelta, - Signer = userPrivateKey.Address, + var userPrivateKey = new PrivateKey(); + action.Execute( + new ActionContext + { + PreviousState = _stateDelta, + Signer = userPrivateKey.Address, + }); }); - }); } [Fact] @@ -63,12 +66,13 @@ public void RenewAdminStateEvenAlreadyExpired() { var newValidUntil = _validUntil + 1000; var action = new RenewAdminState(newValidUntil); - var stateDelta = action.Execute(new ActionContext - { - BlockIndex = _validUntil + 1, - PreviousState = _stateDelta, - Signer = _adminPrivateKey.Address, - }); + var stateDelta = action.Execute( + new ActionContext + { + BlockIndex = _validUntil + 1, + PreviousState = _stateDelta, + Signer = _adminPrivateKey.Address, + }); var adminState = new AdminState((Bencodex.Types.Dictionary)stateDelta.GetLegacyState(Addresses.Admin)); Assert.Equal(newValidUntil, adminState.ValidUntil); @@ -93,38 +97,43 @@ public void CreatePendingActivationsAfterRenewAdminState() random.NextBytes(nonce); var privateKey = new PrivateKey(); - var createPendingActivations = new CreatePendingActivations(new[] - { - new PendingActivationState(nonce, privateKey.PublicKey), - }); + var createPendingActivations = new CreatePendingActivations( + new[] + { + new PendingActivationState(nonce, privateKey.PublicKey), + }); var blockIndex = _validUntil + 1; - Assert.Throws(() => createPendingActivations.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = _stateDelta, - Signer = _adminPrivateKey.Address, - })); + Assert.Throws( + () => createPendingActivations.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = _stateDelta, + Signer = _adminPrivateKey.Address, + })); var newValidUntil = _validUntil + 1000; var action = new RenewAdminState(newValidUntil); - var stateDelta = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = _stateDelta, - Signer = _adminPrivateKey.Address, - }); + var stateDelta = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = _stateDelta, + Signer = _adminPrivateKey.Address, + }); // After 100 blocks. blockIndex += 100; Assert.True(blockIndex < newValidUntil); - stateDelta = createPendingActivations.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = stateDelta, - Signer = _adminPrivateKey.Address, - }); + stateDelta = createPendingActivations.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = stateDelta, + Signer = _adminPrivateKey.Address, + }); var expectedPendingActivationStateAddress = PendingActivationState.DeriveAddress(nonce, privateKey.PublicKey); diff --git a/.Lib9c.Tests/Action/RequestPledgeTest.cs b/.Lib9c.Tests/Action/RequestPledgeTest.cs index d26eaa8e83..5db3039dbf 100644 --- a/.Lib9c.Tests/Action/RequestPledgeTest.cs +++ b/.Lib9c.Tests/Action/RequestPledgeTest.cs @@ -31,11 +31,12 @@ public void Execute(int contractedMead) Assert.Equal(0 * mead, states.GetBalance(address, mead)); Assert.Equal(2 * mead, states.GetBalance(patron, mead)); - var nextState = action.Execute(new ActionContext - { - Signer = patron, - PreviousState = states, - }); + var nextState = action.Execute( + new ActionContext + { + Signer = patron, + PreviousState = states, + }); var contract = Assert.IsType(nextState.GetLegacyState(address.GetPledgeAddress())); Assert.Equal(patron, contract[0].ToAddress()); @@ -58,11 +59,13 @@ public void Execute_Throw_AlreadyContractedException() RefillMead = 1, }; - Assert.Throws(() => action.Execute(new ActionContext - { - Signer = patron, - PreviousState = states, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + Signer = patron, + PreviousState = states, + })); } } } diff --git a/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs b/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs index 205f4f8fda..9d75490517 100644 --- a/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs +++ b/.Lib9c.Tests/Action/RetrieveAvatarAssetsTest.cs @@ -59,13 +59,14 @@ public RetrieveAvatarAssetsTest() new GameConfigState(_csv[nameof(GameConfigSheet)]).Serialize()) .SetLegacyState(Addresses.GoldCurrency, new GoldCurrencyState(_currency).Serialize()); - _state = ca.Execute(new ActionContext - { - PreviousState = state, - BlockIndex = 0, - Signer = _signer, - RandomSeed = 0, - }); + _state = ca.Execute( + new ActionContext + { + PreviousState = state, + BlockIndex = 0, + Signer = _signer, + RandomSeed = 0, + }); } [Fact] @@ -115,13 +116,14 @@ public void Execute() Assert.Equal(1 * _currency, prevState.GetBalance(avatarAddress, _currency)); var action = new RetrieveAvatarAssets(avatarAddress); - var nextState = action.Execute(new ActionContext - { - PreviousState = prevState, - BlockIndex = 1L, - Signer = _signer, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = prevState, + BlockIndex = 1L, + Signer = _signer, + RandomSeed = 0, + }); Assert.Equal(0 * _currency, nextState.GetBalance(avatarAddress, _currency)); Assert.Equal(1 * _currency, nextState.GetBalance(_signer, _currency)); } @@ -152,13 +154,15 @@ public void Execute_Throw_ArgumentOutOfRangeException() Assert.Equal(0 * _currency, _state.GetBalance(avatarAddress, _currency)); var action = new RetrieveAvatarAssets(avatarAddress); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _state, - BlockIndex = 1L, - Signer = _signer, - RandomSeed = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _state, + BlockIndex = 1L, + Signer = _signer, + RandomSeed = 0, + })); } } } diff --git a/.Lib9c.Tests/Action/RewardGoldTest.cs b/.Lib9c.Tests/Action/RewardGoldTest.cs index 8753b343e7..204b895d09 100644 --- a/.Lib9c.Tests/Action/RewardGoldTest.cs +++ b/.Lib9c.Tests/Action/RewardGoldTest.cs @@ -97,9 +97,10 @@ public void WeeklyArenaRankingBoard(bool resetCount, bool updateNext) ArenaScoreHelper.GetScoreV4); var gameConfigState = new GameConfigState(); gameConfigState.Set(_tableSheets.GameConfigSheet); - IWorld state = new World(_baseState - .SetLegacyState(weekly.address, weekly.Serialize()) - .SetLegacyState(gameConfigState.address, gameConfigState.Serialize())); + IWorld state = new World( + _baseState + .SetLegacyState(weekly.address, weekly.Serialize()) + .SetLegacyState(gameConfigState.address, gameConfigState.Serialize())); var blockIndex = 0; if (resetCount) @@ -113,9 +114,10 @@ public void WeeklyArenaRankingBoard(bool resetCount, bool updateNext) blockIndex = gameConfigState.WeeklyArenaInterval; // Avoid NRE in test case. var nextWeekly = new WeeklyArenaState(1); - state = new World(state - .SetLegacyState(weekly.address, weekly.Serialize()) - .SetLegacyState(nextWeekly.address, nextWeekly.Serialize())); + state = new World( + state + .SetLegacyState(weekly.address, weekly.Serialize()) + .SetLegacyState(nextWeekly.address, nextWeekly.Serialize())); } Assert.False(weekly.Ended); diff --git a/.Lib9c.Tests/Action/RuneEnhancementTest.cs b/.Lib9c.Tests/Action/RuneEnhancementTest.cs index 174d26579d..40be4910fc 100644 --- a/.Lib9c.Tests/Action/RuneEnhancementTest.cs +++ b/.Lib9c.Tests/Action/RuneEnhancementTest.cs @@ -308,14 +308,16 @@ public void Execute_RuneCostNotFoundException() TryCount = 1, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -374,14 +376,16 @@ public void Execute_RuneCostDataNotFoundException() TryCount = 1, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Theory] @@ -492,14 +496,16 @@ public void Execute_NotEnoughFungibleAssetValueException(bool ncg, bool crystal, return; } - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -547,14 +553,16 @@ public void Execute_TryCountIsZeroException() TryCount = 0, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -598,14 +606,16 @@ public void Execute_FailedLoadStateException() TryCount = 0, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Theory] diff --git a/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs index 641f64f607..ea89eae0b5 100644 --- a/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/ArenaScenarioTest.cs @@ -81,7 +81,8 @@ public ArenaScenarioTest(ITestOutputHelper outputHelper) .Id; var costume = (Costume)ItemFactory.CreateItem( - _tableSheets.ItemSheet[costumeId], random); + _tableSheets.ItemSheet[costumeId], + random); avatarState.inventory.AddItem(costume); costumes.Add(costume.ItemId); } @@ -108,13 +109,14 @@ public IWorld JoinArena( avatarAddress = avatarAddress, }; - _state = action.Execute(new ActionContext - { - PreviousState = _state, - Signer = signer, - RandomSeed = random.Seed, - BlockIndex = roundData.StartBlockIndex, - }); + _state = action.Execute( + new ActionContext + { + PreviousState = _state, + Signer = signer, + RandomSeed = random.Seed, + BlockIndex = roundData.StartBlockIndex, + }); return _state; } @@ -138,13 +140,14 @@ public IWorld BattleArena( equipments = new List(), }; - _state = action.Execute(new ActionContext - { - PreviousState = _state, - Signer = signer, - RandomSeed = random.Seed, - BlockIndex = blockIndex, - }); + _state = action.Execute( + new ActionContext + { + PreviousState = _state, + Signer = signer, + RandomSeed = random.Seed, + BlockIndex = blockIndex, + }); return _state; } diff --git a/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs index 93efe5a94b..ca69be09e4 100644 --- a/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/AuraScenarioTest.cs @@ -104,13 +104,15 @@ public void HackAndSlash() RuneInfos = new List(), }; - Assert.Throws(() => has.Execute(new ActionContext - { - BlockIndex = 2, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + () => has.Execute( + new ActionContext + { + BlockIndex = 2, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + })); has.Equipments = new List { @@ -118,13 +120,14 @@ public void HackAndSlash() }; // equip aura because auraIgnoreSheet is empty - var nextState = has.Execute(new ActionContext - { - BlockIndex = 3, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = has.Execute( + new ActionContext + { + BlockIndex = 3, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + }); var avatarState = _initialState.GetAvatarState(_avatarAddress); Assert_Player(avatarState, nextState, _avatarAddress, itemSlotStateAddress); @@ -155,13 +158,14 @@ public void Raid() RuneInfos = new List(), }; - var nextState = raid.Execute(new ActionContext - { - BlockIndex = 5045201, - PreviousState = prevState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = raid.Execute( + new ActionContext + { + BlockIndex = 5045201, + PreviousState = prevState, + RandomSeed = 0, + Signer = _agentAddress, + }); Assert_Player(avatarState, nextState, _avatarAddress, itemSlotStateAddress); } @@ -195,12 +199,13 @@ public void Arena() }, runeInfos = new List(), }; - var nextState = join.Execute(new ActionContext - { - BlockIndex = 1, - Signer = _agentAddress, - PreviousState = prevState, - }); + var nextState = join.Execute( + new ActionContext + { + BlockIndex = 1, + Signer = _agentAddress, + PreviousState = prevState, + }); var arenaAvatarStateAdr = ArenaAvatarState.DeriveAddress(avatarAddress); var serializedArenaAvatarState = (List)nextState.GetLegacyState(arenaAvatarStateAdr); var arenaAvatarState = new ArenaAvatarState(serializedArenaAvatarState); @@ -228,13 +233,14 @@ public void Arena() runeInfos = new List(), }; - var nextState = battle.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = prevState, - BlockIndex = 2, - RandomSeed = 0, - }); + var nextState = battle.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = prevState, + BlockIndex = 2, + RandomSeed = 0, + }); var avatarState = prevState.GetAvatarState(avatarAddress); var enemyAvatarState = prevState.GetAvatarState(enemyAvatarAddress); var simulator = new ArenaSimulator(new TestRandom(), 10); @@ -290,12 +296,13 @@ public void Grinding() _aura.ItemId, }, }; - var nextState = grinding.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = _initialState, - BlockIndex = 1L, - }); + var nextState = grinding.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = _initialState, + BlockIndex = 1L, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.False(nextAvatarState.inventory.TryGetNonFungibleItem(_aura.ItemId, out _)); @@ -335,12 +342,14 @@ public void Market() ChargeAp = false, }; // Because Aura is not ITradableItem. - Assert.Throws(() => register.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = previousState, - BlockIndex = 0L, - })); + Assert.Throws( + () => register.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = previousState, + BlockIndex = 0L, + })); } private void Assert_Player(AvatarState avatarState, IWorld state, Address avatarAddress, Address itemSlotStateAddress) diff --git a/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs index 1def4bfec4..edeb37d0ab 100644 --- a/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/CollectionScenarioTest.cs @@ -49,7 +49,12 @@ public CollectionScenarioTest() rankingMapAddress ); _initialState = _initialState.SetAvatarState( - avatarAddress, avatarState, true, true, true, true) + avatarAddress, + avatarState, + true, + true, + true, + true) .SetActionPoint(avatarAddress, DailyReward.ActionPointMax); } @@ -98,12 +103,13 @@ public void HackAndSlash(bool collectionExist) Foods = new List(), }; - action.Execute(new ActionContext - { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = 0, - }); + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = 0, + }); } [Theory] @@ -137,13 +143,14 @@ public void Raid(bool collectionExist) RuneInfos = new List(), FoodIds = new List(), }; - action.Execute(new ActionContext - { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = _tableSheets.WorldBossListSheet.First().Value.StartedBlockIndex, - }); + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = _tableSheets.WorldBossListSheet.First().Value.StartedBlockIndex, + }); } [Theory] @@ -182,7 +189,12 @@ public void BattleArena(bool collectionExist) } prevStates = prevStates.SetAvatarState( - avatarAddress, avatarState, false, false, true, false); + avatarAddress, + avatarState, + false, + false, + true, + false); var join = new JoinArena3 { @@ -193,12 +205,13 @@ public void BattleArena(bool collectionExist) equipments = new List(), runeInfos = new List(), }; - var nextState = join.Execute(new ActionContext - { - BlockIndex = 1, - Signer = _agentAddress, - PreviousState = prevStates, - }); + var nextState = join.Execute( + new ActionContext + { + BlockIndex = 1, + Signer = _agentAddress, + PreviousState = prevStates, + }); prevStates = nextState; } @@ -219,13 +232,14 @@ public void BattleArena(bool collectionExist) runeInfos = new List(), }; - battle.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = prevStates, - BlockIndex = 2, - RandomSeed = 0, - }); + battle.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = prevStates, + BlockIndex = 2, + RandomSeed = 0, + }); } } @@ -254,9 +268,10 @@ public void EventDungeonBattle(bool collectionExist) } var scheduleRow = _tableSheets.EventScheduleSheet.Values.First(); - Assert.True(_tableSheets.EventDungeonSheet.TryGetRowByEventScheduleId( - scheduleRow.Id, - out var eventDungeonRow)); + Assert.True( + _tableSheets.EventDungeonSheet.TryGetRowByEventScheduleId( + scheduleRow.Id, + out var eventDungeonRow)); var action = new EventDungeonBattle { AvatarAddress = _avatarAddress, @@ -269,13 +284,14 @@ public void EventDungeonBattle(bool collectionExist) EventDungeonId = eventDungeonRow.Id, }; - action.Execute(new ActionContext - { - PreviousState = states, - Signer = _agentAddress, - RandomSeed = 0, - BlockIndex = scheduleRow.StartBlockIndex, - }); + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _agentAddress, + RandomSeed = 0, + BlockIndex = scheduleRow.StartBlockIndex, + }); } } } diff --git a/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs index 41f39cf5da..b3fbeef251 100644 --- a/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/GrimoireScenarioTest.cs @@ -104,13 +104,15 @@ public void HackAndSlash() RuneInfos = new List(), }; - Assert.Throws(() => has.Execute(new ActionContext - { - BlockIndex = 2, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - })); + Assert.Throws( + () => has.Execute( + new ActionContext + { + BlockIndex = 2, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + })); has.Equipments = new List { @@ -118,13 +120,14 @@ public void HackAndSlash() }; // equip grimoire because grimoireIgnoreSheet is empty - var nextState = has.Execute(new ActionContext - { - BlockIndex = 3, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = has.Execute( + new ActionContext + { + BlockIndex = 3, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _agentAddress, + }); var avatarState = _initialState.GetAvatarState(_avatarAddress); Assert_Player(avatarState, nextState, _avatarAddress, itemSlotStateAddress); @@ -155,13 +158,14 @@ public void Raid() RuneInfos = new List(), }; - var nextState = raid.Execute(new ActionContext - { - BlockIndex = 5045201, - PreviousState = prevState, - RandomSeed = 0, - Signer = _agentAddress, - }); + var nextState = raid.Execute( + new ActionContext + { + BlockIndex = 5045201, + PreviousState = prevState, + RandomSeed = 0, + Signer = _agentAddress, + }); Assert_Player(avatarState, nextState, _avatarAddress, itemSlotStateAddress); } @@ -195,12 +199,13 @@ public void Arena() }, runeInfos = new List(), }; - var nextState = join.Execute(new ActionContext - { - BlockIndex = 1, - Signer = _agentAddress, - PreviousState = prevState, - }); + var nextState = join.Execute( + new ActionContext + { + BlockIndex = 1, + Signer = _agentAddress, + PreviousState = prevState, + }); var arenaAvatarStateAdr = ArenaAvatarState.DeriveAddress(avatarAddress); var serializedArenaAvatarState = (List)nextState.GetLegacyState(arenaAvatarStateAdr); var arenaAvatarState = new ArenaAvatarState(serializedArenaAvatarState); @@ -228,13 +233,14 @@ public void Arena() runeInfos = new List(), }; - var nextState = battle.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = prevState, - BlockIndex = 2, - RandomSeed = 0, - }); + var nextState = battle.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = prevState, + BlockIndex = 2, + RandomSeed = 0, + }); var avatarState = prevState.GetAvatarState(avatarAddress); var enemyAvatarState = prevState.GetAvatarState(enemyAvatarAddress); var simulator = new ArenaSimulator(new TestRandom(), 10); @@ -291,12 +297,13 @@ public void Grinding() _grimoire.ItemId, }, }; - var nextState = grinding.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = _initialState, - BlockIndex = 1L, - }); + var nextState = grinding.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = _initialState, + BlockIndex = 1L, + }); var nextAvatarState = nextState.GetAvatarState(_avatarAddress); Assert.False(nextAvatarState.inventory.TryGetNonFungibleItem(_grimoire.ItemId, out _)); @@ -336,12 +343,14 @@ public void Market() ChargeAp = false, }; // Because Grimoire is not ITradableItem. - Assert.Throws(() => register.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = previousState, - BlockIndex = 0L, - })); + Assert.Throws( + () => register.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = previousState, + BlockIndex = 0L, + })); } private void Assert_Player(AvatarState avatarState, IWorld state, Address avatarAddress, Address itemSlotStateAddress) diff --git a/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs b/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs index 9a412eec80..ab1aaf082d 100644 --- a/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs +++ b/.Lib9c.Tests/Action/Scenario/ItemCraftTest.cs @@ -78,10 +78,11 @@ public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) foreach (var recipe in recipeList) { allMaterialList = allMaterialList - .Concat(recipe.GetAllMaterials( - _tableSheets.EquipmentItemSubRecipeSheetV2, - CraftType.Normal - )) + .Concat( + recipe.GetAllMaterials( + _tableSheets.EquipmentItemSubRecipeSheetV2, + CraftType.Normal + )) .ToList(); } @@ -132,13 +133,14 @@ public void CraftEquipmentTest(int randomSeed, int[] targetItemIdList) subRecipeId = equipmentRecipe.SubRecipeIds?[0], }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = randomSeed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = randomSeed, + }); var allSlotState = stateV2.GetAllCombinationSlotState(_avatarAddr); var slotState = allSlotState.GetSlot(i); // TEST: requiredBlock @@ -216,13 +218,14 @@ public void CraftConsumableTest(int randomSeed, int[] targetItemIdList) recipeId = recipe.Id, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = randomSeed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = randomSeed, + }); var allSlotState = stateV2.GetAllCombinationSlotState(_avatarAddr); var slotState = allSlotState.GetSlot(i); @@ -298,13 +301,14 @@ int[] targetItemIdList SlotIndex = i, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = eventRow.StartBlockIndex, - RandomSeed = randomSeed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = eventRow.StartBlockIndex, + RandomSeed = randomSeed, + }); var allSlotState = stateV2.GetAllCombinationSlotState(_avatarAddr); var slotState = allSlotState.GetSlot(i); // TEST: requiredBlockIndex @@ -393,13 +397,14 @@ int[] targetItemIdList MaterialsToUse = materialsToUse, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = eventRow.StartBlockIndex, - RandomSeed = randomSeed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = eventRow.StartBlockIndex, + RandomSeed = randomSeed, + }); var slotState = stateV2.GetCombinationSlotStateLegacy(_avatarAddr, i); // TEST: requiredBlockIndex Assert.Equal(recipe.RequiredBlockIndex, slotState.RequiredBlockIndex); diff --git a/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs index aad1695d8e..54ef3b06ff 100644 --- a/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/MarketScenarioTest.cs @@ -186,29 +186,31 @@ public void Register_And_Buy() { case FavProduct favProduct: productType = ProductType.FungibleAssetValue; - productInfoList.Add(new FavProductInfo - { - AgentAddress = _sellerAgentAddress, - AvatarAddress = _sellerAvatarAddress, - Price = product.Price, - ProductId = productId, - Type = productType, - }); + productInfoList.Add( + new FavProductInfo + { + AgentAddress = _sellerAgentAddress, + AvatarAddress = _sellerAvatarAddress, + Price = product.Price, + ProductId = productId, + Type = productType, + }); break; case ItemProduct itemProduct: productType = itemProduct.TradableItem is TradableMaterial ? ProductType.Fungible : ProductType.NonFungible; - productInfoList.Add(new ItemProductInfo - { - AgentAddress = _sellerAgentAddress, - AvatarAddress = _sellerAvatarAddress, - Price = product.Price, - ProductId = productId, - Type = productType, - ItemSubType = itemProduct.TradableItem.ItemSubType, - TradableId = itemProduct.TradableItem.TradableId, - }); + productInfoList.Add( + new ItemProductInfo + { + AgentAddress = _sellerAgentAddress, + AvatarAddress = _sellerAvatarAddress, + Price = product.Price, + ProductId = productId, + Type = productType, + ItemSubType = itemProduct.TradableItem.ItemSubType, + TradableId = itemProduct.TradableItem.TradableId, + }); break; default: throw new ArgumentOutOfRangeException(nameof(product)); @@ -261,29 +263,31 @@ public void Register_And_Buy() { case FavProduct favProduct: productType = ProductType.FungibleAssetValue; - productInfoList.Add(new FavProductInfo - { - AgentAddress = _sellerAgentAddress2, - AvatarAddress = _sellerAvatarAddress2, - Price = product.Price, - ProductId = productId, - Type = productType, - }); + productInfoList.Add( + new FavProductInfo + { + AgentAddress = _sellerAgentAddress2, + AvatarAddress = _sellerAvatarAddress2, + Price = product.Price, + ProductId = productId, + Type = productType, + }); break; case ItemProduct itemProduct: productType = itemProduct.TradableItem is TradableMaterial ? ProductType.Fungible : ProductType.NonFungible; - productInfoList.Add(new ItemProductInfo - { - AgentAddress = _sellerAgentAddress2, - AvatarAddress = _sellerAvatarAddress2, - Price = product.Price, - ProductId = productId, - Type = productType, - ItemSubType = itemProduct.TradableItem.ItemSubType, - TradableId = itemProduct.TradableItem.TradableId, - }); + productInfoList.Add( + new ItemProductInfo + { + AgentAddress = _sellerAgentAddress2, + AvatarAddress = _sellerAvatarAddress2, + Price = product.Price, + ProductId = productId, + Type = productType, + ItemSubType = itemProduct.TradableItem.ItemSubType, + TradableId = itemProduct.TradableItem.TradableId, + }); break; default: throw new ArgumentOutOfRangeException(nameof(product)); @@ -396,13 +400,14 @@ public void Register_And_Cancel() }, }, }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _sellerAgentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _sellerAgentAddress, + }); var nextAvatarState = nextState.GetAvatarState(_sellerAvatarAddress); Assert.Empty(nextAvatarState.inventory.Items); @@ -484,13 +489,14 @@ public void Register_And_Cancel() }, }, }; - var latestState = action2.Execute(new ActionContext - { - BlockIndex = 2L, - PreviousState = nextState, - RandomSeed = 0, - Signer = _sellerAgentAddress, - }); + var latestState = action2.Execute( + new ActionContext + { + BlockIndex = 2L, + PreviousState = nextState, + RandomSeed = 0, + Signer = _sellerAgentAddress, + }); var latestAvatarState = latestState.GetAvatarState(_sellerAvatarAddress); foreach (var productInfo in action2.ProductInfos) @@ -570,13 +576,14 @@ public void Register_And_ReRegister() }, }, }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _sellerAgentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _sellerAgentAddress, + }); var nextAvatarState = nextState.GetAvatarState(_sellerAvatarAddress); Assert.Empty(nextAvatarState.inventory.Items); @@ -619,8 +626,9 @@ public void Register_And_ReRegister() case ItemProduct itemProduct: { var registerInfo = - action.RegisterInfos.OfType().First(r => - r.TradableId == itemProduct.TradableItem.TradableId); + action.RegisterInfos.OfType().First( + r => + r.TradableId == itemProduct.TradableItem.TradableId); Assert.Equal(product.ProductId, guid); Assert.Equal(registerInfo.Price, product.Price); Assert.Equal(registerInfo.ItemCount, itemProduct.ItemCount); @@ -729,8 +737,9 @@ public void Register_And_ReRegister() case ItemProduct itemProduct: { var registerInfo = - action2.ReRegisterInfos.Select(r => r.Item2).OfType().First(r => - r.TradableId == itemProduct.TradableItem.TradableId); + action2.ReRegisterInfos.Select(r => r.Item2).OfType().First( + r => + r.TradableId == itemProduct.TradableItem.TradableId); Assert.Equal(product.ProductId, newProductId); Assert.Equal(registerInfo.Price, product.Price); Assert.Equal(registerInfo.ItemCount, itemProduct.ItemCount); @@ -815,13 +824,14 @@ public void ReRegister_Order() AvatarAddress = _sellerAvatarAddress, ReRegisterInfos = reRegisterInfoList, }; - var nextState = action.Execute(new ActionContext - { - BlockIndex = 2L, - PreviousState = _initialState, - RandomSeed = 0, - Signer = _sellerAgentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 2L, + PreviousState = _initialState, + RandomSeed = 0, + Signer = _sellerAgentAddress, + }); Assert.Empty(new OrderDigestListState((Dictionary)nextState.GetLegacyState(digestListAddress)).OrderDigestList); Assert.Contains( @@ -898,22 +908,24 @@ public void HardFork() }, }; var random = new TestRandom(); - var nextState = action.Execute(new ActionContext - { - BlockIndex = 1L, - PreviousState = _initialState, - RandomSeed = random.Seed, - Signer = _sellerAgentAddress, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = 1L, + PreviousState = _initialState, + RandomSeed = random.Seed, + Signer = _sellerAgentAddress, + }); Guid fungibleProductId = default; Guid nonFungibleProductId = default; Guid assetProductId = default; var productsStateAddress = ProductsState.DeriveAddress(_sellerAvatarAddress); var productsState = new ProductsState((List)nextState.GetLegacyState(productsStateAddress)); foreach (var product in productsState.ProductIds.Select(Product.DeriveAddress) - .Select(productAddress => - ProductFactory.DeserializeProduct( - (List)nextState.GetLegacyState(productAddress)))) + .Select( + productAddress => + ProductFactory.DeserializeProduct( + (List)nextState.GetLegacyState(productAddress)))) { switch (product) { @@ -975,13 +987,14 @@ public void HardFork() AvatarAddress = _sellerAvatarAddress, ProductInfos = productInfos, }; - var canceledState = cancelAction.Execute(new ActionContext - { - BlockIndex = 2L, - PreviousState = nextState, - RandomSeed = random.Seed, - Signer = _sellerAgentAddress, - }); + var canceledState = cancelAction.Execute( + new ActionContext + { + BlockIndex = 2L, + PreviousState = nextState, + RandomSeed = random.Seed, + Signer = _sellerAgentAddress, + }); var avatarState = canceledState.GetAvatarState(_sellerAvatarAddress); Assert.Equal(2, avatarState.inventory.Items.Count); Assert.True(avatarState.inventory.TryGetTradableItem(tradableMaterial.TradableId, 0L, 1, out var materialItem)); @@ -1058,13 +1071,15 @@ public void HardFork() ), }, }; - Assert.Throws(() => reRegisterAction.Execute(new ActionContext - { - BlockIndex = 2L, - PreviousState = nextState, - RandomSeed = random.Seed, - Signer = _sellerAgentAddress, - })); + Assert.Throws( + () => reRegisterAction.Execute( + new ActionContext + { + BlockIndex = 2L, + PreviousState = nextState, + RandomSeed = random.Seed, + Signer = _sellerAgentAddress, + })); //Buy var buyAction = new BuyProduct @@ -1073,13 +1088,14 @@ public void HardFork() ProductInfos = productInfos, }; - var tradedState = buyAction.Execute(new ActionContext - { - BlockIndex = 3L, - PreviousState = nextState, - RandomSeed = random.Seed, - Signer = _buyerAgentAddress, - }); + var tradedState = buyAction.Execute( + new ActionContext + { + BlockIndex = 3L, + PreviousState = nextState, + RandomSeed = random.Seed, + Signer = _buyerAgentAddress, + }); var buyerAvatarState = tradedState.GetAvatarState(_buyerAvatarAddress); var arenaData = _tableSheets.ArenaSheet.GetRoundByBlockIndex(3L); @@ -1220,13 +1236,14 @@ private static IWorld Execute_Grinding_Custom_Equipment( EquipmentIds = equipmentList.Select(e => e.ItemId).ToList(), ChargeAp = false, }; - var nextState = grinding.Execute(new ActionContext - { - PreviousState = state, - Signer = agentAddress, - BlockIndex = 1, - RandomSeed = random.Seed, - }); + var nextState = grinding.Execute( + new ActionContext + { + PreviousState = state, + Signer = agentAddress, + BlockIndex = 1, + RandomSeed = random.Seed, + }); return nextState; } @@ -1243,26 +1260,27 @@ private static IWorld Execute_Register_Custom_Equipment( { var avatarState = state.GetAvatarState(avatarAddress); var price = 1 * Currency.Legacy("NCG", 2, null); - var registerInfos = expectedReward.Select(expected => - { - materialItemSheet.TryGetValue(expected.id, out var materialRow); - Assert.NotNull(materialRow); - Assert.True(materialRow.ItemSubType is ItemSubType.Circle or ItemSubType.Scroll); - avatarState.inventory.TryGetFungibleItems(materialRow.ItemId, out var items); - Assert.Single(items); - var item = items.First(); - - Assert.Equal(expected.count, item.count); - Assert.IsAssignableFrom(item.item); - return new RegisterInfo + var registerInfos = expectedReward.Select( + expected => { - AvatarAddress = avatarAddress, - Price = price, - TradableId = ((ITradableFungibleItem)item.item).TradableId, - ItemCount = item.count, - Type = ProductType.Fungible, - }; - }); + materialItemSheet.TryGetValue(expected.id, out var materialRow); + Assert.NotNull(materialRow); + Assert.True(materialRow.ItemSubType is ItemSubType.Circle or ItemSubType.Scroll); + avatarState.inventory.TryGetFungibleItems(materialRow.ItemId, out var items); + Assert.Single(items); + var item = items.First(); + + Assert.Equal(expected.count, item.count); + Assert.IsAssignableFrom(item.item); + return new RegisterInfo + { + AvatarAddress = avatarAddress, + Price = price, + TradableId = ((ITradableFungibleItem)item.item).TradableId, + ItemCount = item.count, + Type = ProductType.Fungible, + }; + }); for (var i = 0; i < GameConfig.RequireClearedStageLevel.ActionsInShop; i++) { @@ -1277,13 +1295,14 @@ private static IWorld Execute_Register_Custom_Equipment( RegisterInfos = registerInfos, ChargeAp = false, }; - var nextState = register.Execute(new ActionContext - { - PreviousState = state, - Signer = agentAddress, - BlockIndex = 2, - RandomSeed = random.Seed, - }); + var nextState = register.Execute( + new ActionContext + { + PreviousState = state, + Signer = agentAddress, + BlockIndex = 2, + RandomSeed = random.Seed, + }); return nextState; } diff --git a/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs index 0c67b4451a..dad193bff4 100644 --- a/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/MeadScenarioTest.cs @@ -128,11 +128,12 @@ private IWorld Execute(IActionContext context, IWorld state, IAction action, Add { Assert.True(state.GetBalance(signer, Currencies.Mead) > 0 * Currencies.Mead); var nextState = state.BurnAsset(context, signer, 1 * Currencies.Mead); - var executedState = action.Execute(new ActionContext - { - Signer = signer, - PreviousState = nextState, - }); + var executedState = action.Execute( + new ActionContext + { + Signer = signer, + PreviousState = nextState, + }); return RewardGold.TransferMead(context, executedState); } } diff --git a/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs index 6b5c1c546e..35440fae87 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/AdditionalOptionRateByFixedValueTest.cs @@ -58,7 +58,8 @@ int petLevel // Get Materials and stages var materialList = recipe.GetAllMaterials( - _tableSheets.EquipmentItemSubRecipeSheetV2, CraftType.Premium + _tableSheets.EquipmentItemSubRecipeSheetV2, + CraftType.Premium ).ToList(); var stageList = List.Empty; for (var i = 0; i < recipe.UnlockStage; i++) diff --git a/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs index 328d1e8549..41ee94e5dd 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/CommonTest.cs @@ -90,13 +90,14 @@ public void PetCannotBeUsedToTwoSlotsAtTheSameTime() subRecipeId = recipe.SubRecipeIds?[0], petId = petId, }; - stateV2 = action1.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = random.Seed, - }); + stateV2 = action1.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = random.Seed, + }); // Combination2: Raises error var action2 = new CombinationEquipment @@ -107,14 +108,15 @@ public void PetCannotBeUsedToTwoSlotsAtTheSameTime() subRecipeId = recipe.SubRecipeIds?[0], petId = petId, }; - Assert.Throws(() => action2.Execute( - new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 1L, - RandomSeed = random.Seed, - }) + Assert.Throws( + () => action2.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 1L, + RandomSeed = random.Seed, + }) ); } } diff --git a/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs index 6ee53b69b1..d1df573b8c 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/DiscountMaterialCostCrystalTest.cs @@ -119,13 +119,14 @@ public void CraftEquipmentTest( payByCrystal = true, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = random.Seed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = random.Seed, + }); // TEST: All given crystals are used Assert.Equal(0 * crystal, stateV2.GetBalance(_agentAddr, crystal)); diff --git a/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs index 023bf69cbb..e872c89dc7 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/IncreaseBlockPerHourglassTest.cs @@ -148,13 +148,14 @@ public void RapidCombinationTest_Equipment( petId = _petId, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = random.Seed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = random.Seed, + }); // Do rapid combination var rapidAction = new RapidCombination @@ -162,13 +163,14 @@ public void RapidCombinationTest_Equipment( avatarAddress = _avatarAddr, slotIndexList = new List { 0, }, }; - stateV2 = rapidAction.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0, - RandomSeed = random.Seed, - }); + stateV2 = rapidAction.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0, + RandomSeed = random.Seed, + }); var allSlotState = stateV2.GetAllCombinationSlotState(_avatarAddr); var slotState = allSlotState.GetSlot(0); @@ -180,8 +182,9 @@ public void RapidCombinationTest_Equipment( // TEST: All Hourglasses should be used var avatarState = stateV2.GetAvatarState(_avatarAddr); - Assert.Throws(() => - avatarState.inventory.Items.First(item => item.item.Id == _hourglassItemId)); + Assert.Throws( + () => + avatarState.inventory.Items.First(item => item.item.Id == _hourglassItemId)); } } } diff --git a/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs b/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs index daa02f862b..fa08e63a0e 100644 --- a/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs +++ b/.Lib9c.Tests/Action/Scenario/Pet/ReduceRequiredBlockTest.cs @@ -105,13 +105,14 @@ public void CombinationEquipmentTest(int? petLevel) petId = _petId, }; - stateV2 = action.Execute(new ActionContext - { - PreviousState = stateV2, - Signer = _agentAddr, - BlockIndex = 0L, - RandomSeed = random.Seed, - }); + stateV2 = action.Execute( + new ActionContext + { + PreviousState = stateV2, + Signer = _agentAddr, + BlockIndex = 0L, + RandomSeed = random.Seed, + }); var allSlotState = stateV2.GetAllCombinationSlotState(_avatarAddr); var slotState = allSlotState.GetSlot(0); diff --git a/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs index b02c12bef6..e83d66f729 100644 --- a/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/RuneScenarioTest.cs @@ -75,13 +75,14 @@ public void Craft_And_Unlock_And_Equip() RuneId = runeId, }; - var prevState = craftAction.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = initialState, - RandomSeed = 0, - Signer = agentAddress, - }); + var prevState = craftAction.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = initialState, + RandomSeed = 0, + Signer = agentAddress, + }); allRuneState = Assert.IsType(prevState.GetRuneState(avatarAddress, out _)); @@ -99,13 +100,14 @@ public void Craft_And_Unlock_And_Equip() SlotIndex = 6, }; - var state = unlockAction.Execute(new ActionContext - { - BlockIndex = 1, - PreviousState = prevState, - RandomSeed = 0, - Signer = agentAddress, - }); + var state = unlockAction.Execute( + new ActionContext + { + BlockIndex = 1, + PreviousState = prevState, + RandomSeed = 0, + Signer = agentAddress, + }); var runeSlotState = new RuneSlotState((List)state.GetLegacyState(runeSlotStateAddress)); Assert.Single(runeSlotState.GetRuneSlot().Where(r => r.RuneSlotType == RuneSlotType.Crystal && !r.IsLock)); @@ -125,13 +127,14 @@ public void Craft_And_Unlock_And_Equip() }, }; - var nextState = has.Execute(new ActionContext - { - BlockIndex = 2, - PreviousState = state, - RandomSeed = 0, - Signer = agentAddress, - }); + var nextState = has.Execute( + new ActionContext + { + BlockIndex = 2, + PreviousState = state, + RandomSeed = 0, + Signer = agentAddress, + }); var nextAvatarState = nextState.GetAvatarState(avatarAddress); Assert.True(nextAvatarState.worldInformation.IsStageCleared(1)); @@ -182,7 +185,8 @@ public void MigrateToRuneStateModule() var runeState = new RuneState(testRuneId); runeState.LevelUp(testRuneLevel); initialState = initialState.SetLegacyState( - RuneState.DeriveAddress(avatarAddress, testRuneId), runeState.Serialize() + RuneState.DeriveAddress(avatarAddress, testRuneId), + runeState.Serialize() ); var costumes = new List(); @@ -205,13 +209,14 @@ public void MigrateToRuneStateModule() StageId = 1, AvatarAddress = avatarAddress, }; - var state = action.Execute(new ActionContext - { - PreviousState = initialState, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, - }); + var state = action.Execute( + new ActionContext + { + PreviousState = initialState, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = ActionObsoleteConfig.V100301ExecutedBlockIndex, + }); var runeStates = state.GetRuneState(avatarAddress, out var migrateRequired); Assert.False(migrateRequired); var runeStateExist = runeStates.TryGetRuneState(testRuneId, out var nextRuneState); diff --git a/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs b/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs index bdbc8cec1f..431886cd51 100644 --- a/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs +++ b/.Lib9c.Tests/Action/Scenario/SellAndCancellationAndSellTest.cs @@ -75,8 +75,9 @@ public SellAndCancellationAndSellTest(ITestOutputHelper outputHelper) public void Execute_With_TradableMaterial() { var previousStates = _initialState; - var apStoneRow = _tableSheets.MaterialItemSheet.OrderedList!.First(row => - row.ItemSubType == ItemSubType.ApStone); + var apStoneRow = _tableSheets.MaterialItemSheet.OrderedList!.First( + row => + row.ItemSubType == ItemSubType.ApStone); var apStone = ItemFactory.CreateTradableMaterial(apStoneRow); var avatarState = previousStates.GetAvatarState(_avatarAddress); // Add 10 ap stones to inventory. @@ -97,22 +98,24 @@ public void Execute_With_TradableMaterial() var nextStates = previousStates; foreach (var sellAction in sellActions) { - nextStates = sellAction.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = nextStates, - BlockIndex = sellBlockIndex, - RandomSeed = random.Seed, - }); + nextStates = sellAction.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = nextStates, + BlockIndex = sellBlockIndex, + RandomSeed = random.Seed, + }); // TODO: Check state.. inventory, orders.. } // Check inventory does not have ap stones. var nextAvatarState = nextStates.GetAvatarState(_avatarAddress); - Assert.False(nextAvatarState.inventory.RemoveFungibleItem( - apStone.FungibleId, - sellBlockIndex, - 1)); + Assert.False( + nextAvatarState.inventory.RemoveFungibleItem( + apStone.FungibleId, + sellBlockIndex, + 1)); // Cancel sell orders. var sellCancellationActions = new[] @@ -124,44 +127,48 @@ public void Execute_With_TradableMaterial() }; foreach (var sellCancellationAction in sellCancellationActions) { - nextStates = sellCancellationAction.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = nextStates, - BlockIndex = sellBlockIndex + 1L, - RandomSeed = random.Seed, - }); + nextStates = sellCancellationAction.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = nextStates, + BlockIndex = sellBlockIndex + 1L, + RandomSeed = random.Seed, + }); // TODO: Check state.. inventory, orders.. } // Check inventory has 10 ap stones. nextAvatarState = nextStates.GetAvatarState(_avatarAddress); - Assert.True(nextAvatarState.inventory.RemoveFungibleItem( - apStone.FungibleId, - sellBlockIndex + 1L, - 10)); + Assert.True( + nextAvatarState.inventory.RemoveFungibleItem( + apStone.FungibleId, + sellBlockIndex + 1L, + 10)); // Sell 10 ap stones at once. var newSellOrderId = Guid.NewGuid(); var newSellAction = GetSell(apStone, 10, newSellOrderId); - nextStates = newSellAction.Execute(new ActionContext - { - Signer = _agentAddress, - PreviousState = nextStates, - BlockIndex = sellBlockIndex + 2L, - RandomSeed = random.Seed, - }); + nextStates = newSellAction.Execute( + new ActionContext + { + Signer = _agentAddress, + PreviousState = nextStates, + BlockIndex = sellBlockIndex + 2L, + RandomSeed = random.Seed, + }); // Check inventory does not have ap stones. nextAvatarState = nextStates.GetAvatarState(_avatarAddress); - Assert.False(nextAvatarState.inventory.RemoveFungibleItem( - apStone.FungibleId, - sellBlockIndex + 2L, - 1)); + Assert.False( + nextAvatarState.inventory.RemoveFungibleItem( + apStone.FungibleId, + sellBlockIndex + 2L, + 1)); } private Sell GetSell(ITradableItem tradableItem, int count, Guid orderId) => - new() + new () { sellerAvatarAddress = _avatarAddress, tradableId = tradableItem.TradableId, diff --git a/.Lib9c.Tests/Action/Scenario/StakeAndClaimScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/StakeAndClaimScenarioTest.cs index e4c0b7bedb..f6194a9e39 100644 --- a/.Lib9c.Tests/Action/Scenario/StakeAndClaimScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/StakeAndClaimScenarioTest.cs @@ -178,12 +178,13 @@ private static IWorld Stake2( long blockIndex) { var stake2 = new Stake2(stakingAmount); - return stake2.Execute(new ActionContext - { - PreviousState = state, - Signer = agentAddr, - BlockIndex = blockIndex, - }); + return stake2.Execute( + new ActionContext + { + PreviousState = state, + Signer = agentAddr, + BlockIndex = blockIndex, + }); } private static IWorld Stake3( @@ -193,12 +194,13 @@ private static IWorld Stake3( long blockIndex) { var stake3 = new Stake(stakingAmount); - return stake3.Execute(new ActionContext - { - PreviousState = state, - Signer = agentAddr, - BlockIndex = blockIndex, - }); + return stake3.Execute( + new ActionContext + { + PreviousState = state, + Signer = agentAddr, + BlockIndex = blockIndex, + }); } private static IWorld ClaimStakeReward9( @@ -208,12 +210,13 @@ private static IWorld ClaimStakeReward9( long blockIndex) { var claimStakingReward9 = new ClaimStakeReward(avatarAddr); - return claimStakingReward9.Execute(new ActionContext - { - PreviousState = state, - Signer = agentAddr, - BlockIndex = blockIndex, - }); + return claimStakingReward9.Execute( + new ActionContext + { + PreviousState = state, + Signer = agentAddr, + BlockIndex = blockIndex, + }); } private static void ValidateStakedState( diff --git a/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs b/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs index 3e64d19c5f..ea5219519c 100644 --- a/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs +++ b/.Lib9c.Tests/Action/Scenario/WorldUnlockScenarioTest.cs @@ -84,10 +84,11 @@ public void UnlockWorldByHackAndSlashAfterPatchTableWithAddRow( Assert.True(_tableSheets.WorldSheet.ContainsKey(worldIdToClear)); Assert.True(_tableSheets.StageSheet.ContainsKey(stageIdToClear)); Assert.True(_tableSheets.WorldSheet.ContainsKey(worldIdToUnlock)); - Assert.False(_tableSheets.WorldUnlockSheet.TryGetUnlockedInformation( - worldIdToClear, - stageIdToClear, - out _)); + Assert.False( + _tableSheets.WorldUnlockSheet.TryGetUnlockedInformation( + worldIdToClear, + stageIdToClear, + out _)); var avatarState = _initialState.GetAvatarState(_avatarAddress); avatarState.level = avatarLevel; @@ -113,12 +114,13 @@ public void UnlockWorldByHackAndSlashAfterPatchTableWithAddRow( Foods = new List(), RuneInfos = new List(), }; - nextState = hackAndSlash.Execute(new ActionContext - { - PreviousState = nextState, - Signer = _agentAddress, - RandomSeed = 0, - }); + nextState = hackAndSlash.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = _agentAddress, + RandomSeed = 0, + }); avatarState = nextState.GetAvatarState(_avatarAddress); Assert.True(avatarState.worldInformation.IsStageCleared(stageIdToClear)); @@ -143,22 +145,24 @@ public void UnlockWorldByHackAndSlashAfterPatchTableWithAddRow( TableName = nameof(WorldUnlockSheet), TableCsv = tableCsv, }; - nextState = patchTableSheet.Execute(new ActionContext - { - PreviousState = nextState, - Signer = AdminState.Address, - RandomSeed = 0, - }); + nextState = patchTableSheet.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = AdminState.Address, + RandomSeed = 0, + }); var nextTableCsv = nextState.GetSheetCsv(); Assert.Equal(nextTableCsv, tableCsv); - nextState = hackAndSlash.Execute(new ActionContext - { - PreviousState = nextState, - Signer = _agentAddress, - RandomSeed = 0, - }); + nextState = hackAndSlash.Execute( + new ActionContext + { + PreviousState = nextState, + Signer = _agentAddress, + RandomSeed = 0, + }); avatarState = nextState.GetAvatarState(_avatarAddress); Assert.True(avatarState.worldInformation.IsWorldUnlocked(worldIdToUnlock)); diff --git a/.Lib9c.Tests/Action/SecureMiningRewardTest.cs b/.Lib9c.Tests/Action/SecureMiningRewardTest.cs index 70bd835309..df0586f486 100644 --- a/.Lib9c.Tests/Action/SecureMiningRewardTest.cs +++ b/.Lib9c.Tests/Action/SecureMiningRewardTest.cs @@ -73,14 +73,15 @@ public void Execute_InvalidSigner() { var invalidSigner = new Address("0x94cde435616875310f0739FAf2c8671c58987bf0"); var action = new SecureMiningReward(_recipient); - Assert.Throws(() => action.Execute( - new ActionContext - { - PreviousState = _previousState, - Signer = invalidSigner, - BlockIndex = 1, - } - )); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _previousState, + Signer = invalidSigner, + BlockIndex = 1, + } + )); } } } diff --git a/.Lib9c.Tests/Action/Stake2Test.cs b/.Lib9c.Tests/Action/Stake2Test.cs index dc45b9feb7..3eb4326e9c 100644 --- a/.Lib9c.Tests/Action/Stake2Test.cs +++ b/.Lib9c.Tests/Action/Stake2Test.cs @@ -58,13 +58,15 @@ public Stake2Test(ITestOutputHelper outputHelper) public void Execute_Throws_WhenNotEnoughBalance() { var action = new Stake2(200); - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _signerAddress, - BlockIndex = 100, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _signerAddress, + BlockIndex = 100, + })); } [Fact] @@ -82,13 +84,15 @@ public void Execute_Throws_WhenThereIsMonsterCollection() monsterCollectionAddress, new MonsterCollectionState(monsterCollectionAddress, 1, 0).Serialize()); var action = new Stake2(200); - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 100, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 100, + })); } [Fact] @@ -100,43 +104,50 @@ public void Execute_Throws_WhenClaimableExisting() .SetLegacyState(stakeStateAddress, new StakeState(stakeStateAddress, 0).Serialize()) .MintAsset(context, stakeStateAddress, _currency * 50); var action = new Stake2(100); - Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = StakeState.RewardInterval, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = StakeState.RewardInterval, + })); } [Fact] public void Execute_Throws_WhenCancelOrUpdateWhileLockup() { var action = new Stake2(51); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _signerAddress, - BlockIndex = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _signerAddress, + BlockIndex = 0, + }); // Cancel var updateAction = new Stake2(0); - Assert.Throws(() => updateAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 1, - })); + Assert.Throws( + () => updateAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 1, + })); // Less updateAction = new Stake2(50); - Assert.Throws(() => updateAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 1, - })); + Assert.Throws( + () => updateAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 1, + })); // Same (since 4611070) if (states.TryGetStakeState(_signerAddress, out var stakeState)) @@ -147,20 +158,24 @@ public void Execute_Throws_WhenCancelOrUpdateWhileLockup() } updateAction = new Stake2(51); - Assert.Throws(() => updateAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 4611070, - })); + Assert.Throws( + () => updateAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 4611070, + })); // At 4611070 - 99, it should be updated. - Assert.True(updateAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 4611070 - 99, - }).TryGetStakeState(_signerAddress, out stakeState)); + Assert.True( + updateAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 4611070 - 99, + }).TryGetStakeState(_signerAddress, out stakeState)); Assert.Equal(4611070 - 99, stakeState.StartedBlockIndex); } @@ -168,12 +183,13 @@ public void Execute_Throws_WhenCancelOrUpdateWhileLockup() public void Execute() { var action = new Stake2(100); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _signerAddress, - BlockIndex = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _signerAddress, + BlockIndex = 0, + }); Assert.Equal(_currency * 0, states.GetBalance(_signerAddress, _currency)); Assert.Equal( @@ -201,12 +217,13 @@ public void Execute() stakeState.Achievements); states = states.SetLegacyState(stakeState.address, producedStakeState.SerializeV2()); var cancelAction = new Stake2(0); - states = cancelAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = StakeState.LockupInterval, - }); + states = cancelAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = StakeState.LockupInterval, + }); Assert.Null(states.GetLegacyState(stakeState.address)); Assert.Equal(_currency * 0, states.GetBalance(stakeState.address, _currency)); @@ -217,12 +234,13 @@ public void Execute() public void Update() { var action = new Stake2(50); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - Signer = _signerAddress, - BlockIndex = 0, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + Signer = _signerAddress, + BlockIndex = 0, + }); states.TryGetStakeState(_signerAddress, out var stakeState); Assert.Equal(0, stakeState.StartedBlockIndex); @@ -232,12 +250,13 @@ public void Update() Assert.Equal(_currency * 50, states.GetBalance(_signerAddress, _currency)); var updateAction = new Stake2(100); - states = updateAction.Execute(new ActionContext - { - PreviousState = states, - Signer = _signerAddress, - BlockIndex = 1, - }); + states = updateAction.Execute( + new ActionContext + { + PreviousState = states, + Signer = _signerAddress, + BlockIndex = 1, + }); states.TryGetStakeState(_signerAddress, out stakeState); Assert.Equal(1, stakeState.StartedBlockIndex); @@ -251,20 +270,22 @@ public void Update() public void RestrictForStakeStateV2() { var action = new Stake2(50); - Assert.Throws(() => action.Execute(new ActionContext - { - PreviousState = _initialState.SetLegacyState( - StakeState.DeriveAddress(_signerAddress), - new StakeStateV2( - new Contract( - "StakeRegularFixedRewardSheet_V1", - "StakeRegularRewardSheet_V1", - 50400, - 201600), - 0).Serialize()), - Signer = _signerAddress, - BlockIndex = 0, - })); + Assert.Throws( + () => action.Execute( + new ActionContext + { + PreviousState = _initialState.SetLegacyState( + StakeState.DeriveAddress(_signerAddress), + new StakeStateV2( + new Contract( + "StakeRegularFixedRewardSheet_V1", + "StakeRegularRewardSheet_V1", + 50400, + 201600), + 0).Serialize()), + Signer = _signerAddress, + BlockIndex = 0, + })); } [Fact] diff --git a/.Lib9c.Tests/Action/StakeTest.cs b/.Lib9c.Tests/Action/StakeTest.cs index a433c31608..83f56f1214 100644 --- a/.Lib9c.Tests/Action/StakeTest.cs +++ b/.Lib9c.Tests/Action/StakeTest.cs @@ -123,13 +123,14 @@ public void Execute_Throw_MonsterCollectionExistingException( 0); previousState = previousState .SetLegacyState(monsterCollectionAddr, monsterCollectionState.Serialize()); - Assert.Throws(() => - Execute( - 0, - previousState, - new TestRandom(), - _agentAddr, - 0)); + Assert.Throws( + () => + Execute( + 0, + previousState, + new TestRandom(), + _agentAddr, + 0)); } [Theory] @@ -137,13 +138,14 @@ public void Execute_Throw_MonsterCollectionExistingException( [InlineData(long.MinValue)] public void Execute_Throw_ArgumentOutOfRangeException_Via_Negative_Amount(long amount) { - Assert.Throws(() => - Execute( - 0, - _initialState, - new TestRandom(), - _agentAddr, - amount)); + Assert.Throws( + () => + Execute( + 0, + _initialState, + new TestRandom(), + _agentAddr, + amount)); } [Theory] @@ -157,13 +159,14 @@ public void Execute_Throw_StateNullException_Via_Sheet(string sheetName) var previousState = _initialState.SetLegacyState( Addresses.GetSheetAddress(sheetName), Null.Value); - Assert.Throws(() => - Execute( - 0, - previousState, - new TestRandom(), - _agentAddr, - 0)); + Assert.Throws( + () => + Execute( + 0, + previousState, + new TestRandom(), + _agentAddr, + 0)); } [Theory] @@ -172,13 +175,14 @@ public void Execute_Throw_StateNullException_Via_Sheet(string sheetName) [InlineData(1)] public void Execute_Throw_ArgumentOutOfRangeException_Via_Minimum_Amount(long amount) { - Assert.Throws(() => - Execute( - 0, - _initialState, - new TestRandom(), - _agentAddr, - amount)); + Assert.Throws( + () => + Execute( + 0, + _initialState, + new TestRandom(), + _agentAddr, + amount)); } [Theory] @@ -199,25 +203,27 @@ public void Execute_Throws_NotEnoughFungibleAssetValueException( _ncg * balance); } - Assert.Throws(() => - Execute( - 0, - previousState, - new TestRandom(), - _agentAddr, - amount)); + Assert.Throws( + () => + Execute( + 0, + previousState, + new TestRandom(), + _agentAddr, + amount)); } [Fact] public void Execute_Throw_StateNullException_Via_0_Amount() { - Assert.Throws(() => - Execute( - 0, - _initialState, - new TestRandom(), - _agentAddr, - 0)); + Assert.Throws( + () => + Execute( + 0, + _initialState, + new TestRandom(), + _agentAddr, + 0)); } [Theory] @@ -243,13 +249,14 @@ public void Execute_Throw_StakeExistingClaimableException_With_StakeState( stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeState.Serialize()); - Assert.Throws(() => - Execute( - blockIndex, - previousState, - new TestRandom(), - _agentAddr, - previousAmount)); + Assert.Throws( + () => + Execute( + blockIndex, + previousState, + new TestRandom(), + _agentAddr, + previousAmount)); } [Theory] @@ -275,13 +282,14 @@ public void Execute_Throw_StakeExistingClaimableException_With_StakeStateV2( stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeStateV2.Serialize()); - Assert.Throws(() => - Execute( - blockIndex, - previousState, - new TestRandom(), - _agentAddr, - previousAmount)); + Assert.Throws( + () => + Execute( + blockIndex, + previousState, + new TestRandom(), + _agentAddr, + previousAmount)); } [Theory] @@ -313,13 +321,14 @@ public void stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeState.Serialize()); - Assert.Throws(() => - Execute( - blockIndex, - previousState, - new TestRandom(), - _agentAddr, - reducedAmount)); + Assert.Throws( + () => + Execute( + blockIndex, + previousState, + new TestRandom(), + _agentAddr, + reducedAmount)); } [Theory] @@ -349,13 +358,14 @@ public void stakeStateAddr, _ncg * previousAmount) .SetLegacyState(stakeStateAddr, stakeStateV2.Serialize()); - Assert.Throws(() => - Execute( - blockIndex, - previousState, - new TestRandom(), - _agentAddr, - reducedAmount)); + Assert.Throws( + () => + Execute( + blockIndex, + previousState, + new TestRandom(), + _agentAddr, + reducedAmount)); } [Theory] @@ -486,13 +496,14 @@ private IWorld Execute( _ncg); var previousTotalBalance = previousBalance + previousStakeBalance; var action = new Stake(amount); - var nextState = action.Execute(new ActionContext - { - BlockIndex = blockIndex, - PreviousState = previousState, - RandomSeed = random.Seed, - Signer = signer, - }); + var nextState = action.Execute( + new ActionContext + { + BlockIndex = blockIndex, + PreviousState = previousState, + RandomSeed = random.Seed, + Signer = signer, + }); var amountNCG = _ncg * amount; var nextBalance = nextState.GetBalance(signer, _ncg); diff --git a/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs b/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs index 4a935c6764..1fe7a4ab74 100644 --- a/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs +++ b/.Lib9c.Tests/Action/Summon/AuraSummonTest.cs @@ -237,8 +237,9 @@ Type expectedExc var checkedEquipments = new List(); foreach (var equipmentId in expectedEquipmentId) { - var resultEquipment = equipments.First(e => - e.Id == equipmentId && !checkedEquipments.Contains(e.ItemId) + var resultEquipment = equipments.First( + e => + e.Id == equipmentId && !checkedEquipments.Contains(e.ItemId) ); checkedEquipments.Add(resultEquipment.ItemId); @@ -254,16 +255,19 @@ Type expectedExc else { // Failure - Assert.Throws(expectedExc, () => - { - action.Execute(new ActionContext + Assert.Throws( + expectedExc, + () => { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = random.Seed, + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = random.Seed, + }); }); - }); } } } diff --git a/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs b/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs index 0a451b81e3..08ec4c6e4f 100644 --- a/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs +++ b/.Lib9c.Tests/Action/Summon/RuneSummonTest.cs @@ -173,16 +173,19 @@ Type expectedExc else { // Failure - Assert.Throws(expectedExc, () => - { - action.Execute(new ActionContext + Assert.Throws( + expectedExc, + () => { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = random.Seed, + action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = random.Seed, + }); }); - }); } } diff --git a/.Lib9c.Tests/Action/TransferAssetTest.cs b/.Lib9c.Tests/Action/TransferAssetTest.cs index 46ba0131d4..e89f62a335 100644 --- a/.Lib9c.Tests/Action/TransferAssetTest.cs +++ b/.Lib9c.Tests/Action/TransferAssetTest.cs @@ -30,7 +30,8 @@ public class TransferAssetTest } ); - private static readonly Address _recipient = new (new byte[] + private static readonly Address _recipient = new ( + new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, @@ -45,8 +46,9 @@ public class TransferAssetTest [Fact] public void Constructor_ThrowsMemoLengthOverflowException() { - Assert.Throws(() => - new TransferAsset(_sender, _recipient, _currency * 100, new string(' ', 100))); + Assert.Throws( + () => + new TransferAsset(_sender, _recipient, _currency * 100, new string(' ', 100))); } [Fact] @@ -63,12 +65,13 @@ public void Execute() _recipient, _currency * 100 ); - var nextState = action.Execute(new ActionContext() - { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); Assert.Equal(_currency * 900, nextState.GetBalance(_sender, _currency)); Assert.Equal(_currency * 110, nextState.GetBalance(_recipient, _currency)); @@ -88,16 +91,18 @@ public void Execute_Throw_InvalidTransferSignerException() _currency * 100 ); - var exc = Assert.Throws(() => - { - _ = action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - // 송금자가 직접 사인하지 않으면 실패해야 합니다. - Signer = _recipient, - BlockIndex = 1, + _ = action.Execute( + new ActionContext() + { + PreviousState = prevState, + // 송금자가 직접 사인하지 않으면 실패해야 합니다. + Signer = _recipient, + BlockIndex = 1, + }); }); - }); Assert.Equal(exc.Sender, _sender); Assert.Equal(exc.Recipient, _recipient); @@ -118,15 +123,17 @@ public void Execute_Throw_InvalidTransferRecipientException() _currency * 100 ); - var exc = Assert.Throws(() => - { - _ = action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + _ = action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(exc.Sender, _sender); Assert.Equal(exc.Recipient, _sender); @@ -146,15 +153,17 @@ public void Execute_Throw_InsufficientBalanceException() _currency * 100000 ); - var exc = Assert.Throws(() => - { - action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(_sender, exc.Address); Assert.Equal(_currency, exc.Balance.Currency); @@ -181,15 +190,17 @@ public void Execute_Throw_InvalidTransferMinterException(bool minterAsSender) _recipient, currencyBySender * 100 ); - var ex = Assert.Throws(() => - { - action.Execute(new ActionContext() + var ex = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(new[] { minter, }, ex.Minters); Assert.Equal(_sender, ex.Sender); @@ -257,12 +268,14 @@ public void Execute_Throw_InvalidTransferCurrencyException() _recipient, 1000 * crystal ); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = prevState, - Signer = _sender, - BlockIndex = TransferAsset3.CrystalTransferringRestrictionStartIndex, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = TransferAsset3.CrystalTransferringRestrictionStartIndex, + })); } [Fact] @@ -271,13 +284,16 @@ public void LoadPlainValue_ThrowsMemoLengthOverflowException() var action = new TransferAsset(); var plainValue = Dictionary.Empty .Add("type_id", "transfer_asset5") - .Add("values", new Dictionary(new[] - { - new KeyValuePair((Text)"sender", _sender.Serialize()), - new KeyValuePair((Text)"recipient", _recipient.Serialize()), - new KeyValuePair((Text)"amount", (_currency * 100).Serialize()), - new KeyValuePair((Text)"memo", new string(' ', 81).Serialize()), - })); + .Add( + "values", + new Dictionary( + new[] + { + new KeyValuePair((Text)"sender", _sender.Serialize()), + new KeyValuePair((Text)"recipient", _recipient.Serialize()), + new KeyValuePair((Text)"amount", (_currency * 100).Serialize()), + new KeyValuePair((Text)"memo", new string(' ', 81).Serialize()), + })); Assert.Throws(() => action.LoadPlainValue(plainValue)); } @@ -294,60 +310,72 @@ public void Execute_Throw_ArgumentException() _currency * 100 ); // 스테이킹 주소에 송금하려고 하면 실패합니다. - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new StakeState(StakeState.DeriveAddress(_recipient), 0).SerializeV2()), - Signer = _sender, - BlockIndex = 1, - })); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new StakeStateV2( - new Contract( - "StakeRegularFixedRewardSheet_V1", - "StakeRegularRewardSheet_V1", - 50400, - 201600), - 0).Serialize()), - Signer = _sender, - BlockIndex = 1, - })); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new MonsterCollectionState( - MonsterCollectionState.DeriveAddress(_sender, 0), - 1, - 0) - .Serialize()), - Signer = _sender, - BlockIndex = 1, - })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new StakeState(StakeState.DeriveAddress(_recipient), 0).SerializeV2()), + Signer = _sender, + BlockIndex = 1, + })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new StakeStateV2( + new Contract( + "StakeRegularFixedRewardSheet_V1", + "StakeRegularRewardSheet_V1", + 50400, + 201600), + 0).Serialize()), + Signer = _sender, + BlockIndex = 1, + })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new MonsterCollectionState( + MonsterCollectionState.DeriveAddress(_sender, 0), + 1, + 0) + .Serialize()), + Signer = _sender, + BlockIndex = 1, + })); var monsterCollectionRewardSheet = new MonsterCollectionRewardSheet(); monsterCollectionRewardSheet.Set( "level,required_gold,reward_id\n1,500,1\n2,1800,2\n3,7200,3\n4,54000,4\n5,270000,5\n6,480000,6\n7,1500000,7\n"); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new MonsterCollectionState0( - MonsterCollectionState.DeriveAddress(_sender, 0), - 1, - 0, - monsterCollectionRewardSheet) - .Serialize()), - Signer = _sender, - BlockIndex = 1, - })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new MonsterCollectionState0( + MonsterCollectionState.DeriveAddress(_sender, 0), + 1, + 0, + monsterCollectionRewardSheet) + .Serialize()), + Signer = _sender, + BlockIndex = 1, + })); } [Theory] diff --git a/.Lib9c.Tests/Action/TransferAssetsTest.cs b/.Lib9c.Tests/Action/TransferAssetsTest.cs index b5f1ade24c..a952d276f0 100644 --- a/.Lib9c.Tests/Action/TransferAssetsTest.cs +++ b/.Lib9c.Tests/Action/TransferAssetsTest.cs @@ -30,14 +30,16 @@ public class TransferAssetsTest } ); - private static readonly Address _recipient = new (new byte[] + private static readonly Address _recipient = new ( + new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, } ); - private static readonly Address _recipient2 = new (new byte[] + private static readonly Address _recipient2 = new ( + new byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, @@ -52,15 +54,16 @@ public class TransferAssetsTest [Fact] public void Constructor_ThrowsMemoLengthOverflowException() { - Assert.Throws(() => - new TransferAssets( - _sender, - new List<(Address, FungibleAssetValue)>() - { - (_recipient, _currency * 100), - }, - new string(' ', 100) - ) + Assert.Throws( + () => + new TransferAssets( + _sender, + new List<(Address, FungibleAssetValue)>() + { + (_recipient, _currency * 100), + }, + new string(' ', 100) + ) ); } @@ -81,12 +84,13 @@ public void Execute() (_recipient2, _currency * 100), } ); - var nextState = action.Execute(new ActionContext() - { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, - }); + var nextState = action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); Assert.Equal(_currency * 800, nextState.GetBalance(_sender, _currency)); Assert.Equal(_currency * 110, nextState.GetBalance(_recipient, _currency)); @@ -110,16 +114,18 @@ public void Execute_Throw_InvalidTransferSignerException() } ); - var exc = Assert.Throws(() => - { - _ = action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - // 송금자가 직접 사인하지 않으면 실패해야 합니다. - Signer = _recipient, - BlockIndex = 1, + _ = action.Execute( + new ActionContext() + { + PreviousState = prevState, + // 송금자가 직접 사인하지 않으면 실패해야 합니다. + Signer = _recipient, + BlockIndex = 1, + }); }); - }); Assert.Equal(exc.Sender, _sender); Assert.Equal(exc.Recipient, _recipient); @@ -141,15 +147,17 @@ public void Execute_Throw_InvalidTransferRecipientException() } ); - var exc = Assert.Throws(() => - { - _ = action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + _ = action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(exc.Sender, _sender); Assert.Equal(exc.Recipient, _sender); @@ -171,15 +179,17 @@ public void Execute_Throw_InsufficientBalanceException() } ); - var exc = Assert.Throws(() => - { - action.Execute(new ActionContext() + var exc = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(_sender, exc.Address); Assert.Equal(_currency, exc.Balance.Currency); @@ -204,15 +214,17 @@ public void Execute_Throw_InvalidTransferMinterException() (_recipient, currencyBySender * 100), } ); - var ex = Assert.Throws(() => - { - action.Execute(new ActionContext() + var ex = Assert.Throws( + () => { - PreviousState = prevState, - Signer = _sender, - BlockIndex = 1, + action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = 1, + }); }); - }); Assert.Equal(new[] { _sender, }, ex.Minters); Assert.Equal(_sender, ex.Sender); @@ -281,12 +293,15 @@ public void LoadPlainValue_ThrowsMemoLengthOverflowException() var action = new TransferAssets(); var plainValue = Dictionary.Empty .Add("type_id", "transfer_assets") - .Add("values", new Dictionary(new[] - { - new KeyValuePair((Text)"sender", _sender.Serialize()), - new KeyValuePair((Text)"recipients", List.Empty.Add(List.Empty.Add(_recipient.Serialize()).Add((_currency * 100).Serialize()))), - new KeyValuePair((Text)"memo", new string(' ', 81).Serialize()), - })); + .Add( + "values", + new Dictionary( + new[] + { + new KeyValuePair((Text)"sender", _sender.Serialize()), + new KeyValuePair((Text)"recipients", List.Empty.Add(List.Empty.Add(_recipient.Serialize()).Add((_currency * 100).Serialize()))), + new KeyValuePair((Text)"memo", new string(' ', 81).Serialize()), + })); Assert.Throws(() => action.LoadPlainValue(plainValue)); } @@ -329,15 +344,17 @@ public void Execute_Throw_ArgumentOutOfRangeException() } var action = new TransferAssets(_sender, recipients); - Assert.Throws(() => - { - action.Execute(new ActionContext() + Assert.Throws( + () => { - PreviousState = new World(MockUtil.MockModernWorldState), - Signer = _sender, - BlockIndex = 1, + action.Execute( + new ActionContext() + { + PreviousState = new World(MockUtil.MockModernWorldState), + Signer = _sender, + BlockIndex = 1, + }); }); - }); } [Fact] @@ -356,12 +373,14 @@ public void Execute_Throw_InvalidTransferCurrencyException() (_recipient, 100 * _currency), } ); - Assert.Throws(() => action.Execute(new ActionContext() - { - PreviousState = prevState, - Signer = _sender, - BlockIndex = TransferAsset3.CrystalTransferringRestrictionStartIndex, - })); + Assert.Throws( + () => action.Execute( + new ActionContext() + { + PreviousState = prevState, + Signer = _sender, + BlockIndex = TransferAsset3.CrystalTransferringRestrictionStartIndex, + })); } [Fact] @@ -377,60 +396,72 @@ public void Execute_Throw_ArgumentException() } ); // 스테이킹 주소에 송금하려고 하면 실패합니다. - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new StakeState(StakeState.DeriveAddress(_recipient), 0).SerializeV2()), - Signer = _sender, - BlockIndex = 1, - })); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new StakeStateV2( - new Contract( - "StakeRegularFixedRewardSheet_V1", - "StakeRegularRewardSheet_V1", - 50400, - 201600), - 0).Serialize()), - Signer = _sender, - BlockIndex = 1, - })); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new MonsterCollectionState( - MonsterCollectionState.DeriveAddress(_sender, 0), - 1, - 0) - .Serialize()), - Signer = _sender, - BlockIndex = 1, - })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new StakeState(StakeState.DeriveAddress(_recipient), 0).SerializeV2()), + Signer = _sender, + BlockIndex = 1, + })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new StakeStateV2( + new Contract( + "StakeRegularFixedRewardSheet_V1", + "StakeRegularRewardSheet_V1", + 50400, + 201600), + 0).Serialize()), + Signer = _sender, + BlockIndex = 1, + })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new MonsterCollectionState( + MonsterCollectionState.DeriveAddress(_sender, 0), + 1, + 0) + .Serialize()), + Signer = _sender, + BlockIndex = 1, + })); var monsterCollectionRewardSheet = new MonsterCollectionRewardSheet(); monsterCollectionRewardSheet.Set( "level,required_gold,reward_id\n1,500,1\n2,1800,2\n3,7200,3\n4,54000,4\n5,270000,5\n6,480000,6\n7,1500000,7\n"); - Assert.Throws("recipient", () => action.Execute(new ActionContext() - { - PreviousState = baseState - .SetLegacyState( - StakeState.DeriveAddress(_recipient), - new MonsterCollectionState0( - MonsterCollectionState.DeriveAddress(_sender, 0), - 1, - 0, - monsterCollectionRewardSheet) - .Serialize()), - Signer = _sender, - BlockIndex = 1, - })); + Assert.Throws( + "recipient", + () => action.Execute( + new ActionContext() + { + PreviousState = baseState + .SetLegacyState( + StakeState.DeriveAddress(_recipient), + new MonsterCollectionState0( + MonsterCollectionState.DeriveAddress(_sender, 0), + 1, + 0, + monsterCollectionRewardSheet) + .Serialize()), + Signer = _sender, + BlockIndex = 1, + })); } } } diff --git a/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs b/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs index 4d1e3cb591..1efd371896 100644 --- a/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs +++ b/.Lib9c.Tests/Action/UnlockEquipmentRecipeTest.cs @@ -145,13 +145,14 @@ Type exc if (exc is null) { - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + }); Assert.True(nextState.TryGetLegacyState(unlockedRecipeIdsAddress, out List rawIds)); @@ -163,13 +164,16 @@ Type exc } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + })); } } diff --git a/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs b/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs index e84973cab6..6650210000 100644 --- a/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs +++ b/.Lib9c.Tests/Action/UnlockRuneSlotTest.cs @@ -114,14 +114,16 @@ public void Execute_InsufficientBalanceException() SlotIndex = 1, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -134,14 +136,16 @@ public void Execute_SlotNotFoundException() SlotIndex = 99, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -154,14 +158,16 @@ public void Execute_MismatchRuneSlotTypeException() SlotIndex = 0, }; - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Fact] @@ -188,14 +194,16 @@ public void Execute_SlotIsAlreadyUnlockedException() state = action.Execute(ctx); - Assert.Throws(() => - action.Execute(new ActionContext() - { - PreviousState = state, - Signer = agentAddress, - RandomSeed = 0, - BlockIndex = blockIndex, - })); + Assert.Throws( + () => + action.Execute( + new ActionContext() + { + PreviousState = state, + Signer = agentAddress, + RandomSeed = 0, + BlockIndex = blockIndex, + })); } [Theory] diff --git a/.Lib9c.Tests/Action/UnlockWorldTest.cs b/.Lib9c.Tests/Action/UnlockWorldTest.cs index 435dcc4bb6..370d82cbf9 100644 --- a/.Lib9c.Tests/Action/UnlockWorldTest.cs +++ b/.Lib9c.Tests/Action/UnlockWorldTest.cs @@ -99,12 +99,14 @@ Type exc { foreach (var wordId in worldIds) { - var row = _tableSheets.WorldUnlockSheet.OrderedList.First(r => - r.WorldIdToUnlock == wordId); + var row = _tableSheets.WorldUnlockSheet.OrderedList.First( + r => + r.WorldIdToUnlock == wordId); var worldRow = _tableSheets.WorldSheet[row.WorldId]; var prevRow = - _tableSheets.WorldUnlockSheet.OrderedList.FirstOrDefault(r => - r.WorldIdToUnlock == row.WorldId); + _tableSheets.WorldUnlockSheet.OrderedList.FirstOrDefault( + r => + r.WorldIdToUnlock == row.WorldId); // Clear prev world. if (!(prevRow is null)) { @@ -145,13 +147,14 @@ Type exc if (exc is null) { - var nextState = action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - }); + var nextState = action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + }); Assert.True(nextState.TryGetLegacyState(unlockedWorldIdsAddress, out List rawIds)); @@ -163,13 +166,16 @@ Type exc } else { - Assert.Throws(exc, () => action.Execute(new ActionContext - { - PreviousState = state, - Signer = _agentAddress, - BlockIndex = 1, - RandomSeed = _random.Seed, - })); + Assert.Throws( + exc, + () => action.Execute( + new ActionContext + { + PreviousState = state, + Signer = _agentAddress, + BlockIndex = 1, + RandomSeed = _random.Seed, + })); } } } diff --git a/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs b/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs index 758b8d6d6f..9856443e6b 100644 --- a/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs +++ b/.Lib9c.Tests/Action/ValidatorSetOperateTest.cs @@ -69,17 +69,18 @@ public void CheckPermission_Throws_PermissionDenied() .SetLegacyState(AdminState.Address, adminState.Serialize()); var action = ValidatorSetOperate.Append(_validator); - var exc1 = Assert.Throws(() => - { - action.Execute( - new ActionContext() - { - BlockIndex = 5, - PreviousState = state, - Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), - } - ); - }); + var exc1 = Assert.Throws( + () => + { + action.Execute( + new ActionContext() + { + BlockIndex = 5, + PreviousState = state, + Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), + } + ); + }); Assert.Equal(new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), exc1.Signer); } @@ -87,11 +88,13 @@ public void CheckPermission_Throws_PermissionDenied() public void Append_Throws_WhenAlreadyExistValidator() { var action = ValidatorSetOperate.Append(_validator); - var exc = Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = _initialState, - })); + var exc = Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = _initialState, + })); Assert.Equal( "Cannot append validator when its already exist.", exc.Message); @@ -102,11 +105,13 @@ public void Update_Throws_WhenDoNotExistValidator() { var state = new World(MockUtil.MockModernWorldState); var action = ValidatorSetOperate.Update(_validator); - var exc = Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = state, - })); + var exc = Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + })); Assert.Equal( "Cannot update validator when its do not exist.", exc.Message); @@ -117,11 +122,13 @@ public void Remove_Throws_WhenDoNotExistValidator() { var state = new World(MockUtil.MockModernWorldState); var action = ValidatorSetOperate.Remove(_validator); - var exc = Assert.Throws(() => - action.Execute(new ActionContext - { - PreviousState = state, - })); + var exc = Assert.Throws( + () => + action.Execute( + new ActionContext + { + PreviousState = state, + })); Assert.Equal( "Cannot remove validator when its do not exist.", exc.Message); @@ -133,10 +140,11 @@ public void Append() var validatorPubKey = new PrivateKey().PublicKey; var validator = new Validator(validatorPubKey, BigInteger.One); var action = ValidatorSetOperate.Append(validator); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + }); var validatorSet = states.GetValidatorSet(); Assert.Equal(2, validatorSet.Validators.Count); @@ -148,10 +156,11 @@ public void Update() { var validator = new Validator(_validator.PublicKey, 10); var action = ValidatorSetOperate.Update(validator); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + }); var validatorSet = states.GetValidatorSet(); Assert.Single(validatorSet.Validators); @@ -162,10 +171,11 @@ public void Update() public void Remove() { var action = ValidatorSetOperate.Remove(_validator); - var states = action.Execute(new ActionContext - { - PreviousState = _initialState, - }); + var states = action.Execute( + new ActionContext + { + PreviousState = _initialState, + }); var validatorSet = states.GetValidatorSet(); Assert.Empty(validatorSet.Validators); diff --git a/.Lib9c.Tests/CrystalCalculatorTest.cs b/.Lib9c.Tests/CrystalCalculatorTest.cs index 2e303fa1c5..e6471b49ce 100644 --- a/.Lib9c.Tests/CrystalCalculatorTest.cs +++ b/.Lib9c.Tests/CrystalCalculatorTest.cs @@ -114,8 +114,9 @@ public void CalculateCombinationCost(int psCrystal, int bpsCrystal, int expected var bps = bpsExist ? new CrystalCostState(default, bpsCrystal * CrystalCalculator.CRYSTAL) : null; - var row = _tableSheets.CrystalFluctuationSheet.Values.First(r => - r.Type == CrystalFluctuationSheet.ServiceType.Combination); + var row = _tableSheets.CrystalFluctuationSheet.Values.First( + r => + r.Type == CrystalFluctuationSheet.ServiceType.Combination); Assert.Equal( expected * CrystalCalculator.CRYSTAL, CrystalCalculator.CalculateCombinationCost(crystal, row, ps, bps) @@ -156,7 +157,7 @@ public void CalculateMaterialCost(int materialId, int materialCount, int expecte private class CalculateCrystalData : IEnumerable { - private readonly List _data = new() + private readonly List _data = new () { // 1 + ((2^0 - 1) * 1) = 1 // enchant level 2 diff --git a/.Lib9c.Tests/CurrenciesTest.cs b/.Lib9c.Tests/CurrenciesTest.cs index c9a2d4e0f6..543e342c0a 100644 --- a/.Lib9c.Tests/CurrenciesTest.cs +++ b/.Lib9c.Tests/CurrenciesTest.cs @@ -131,8 +131,10 @@ public void GetRunes_With_Sheet() Assert.Equal(sheet.Count, currencies.Length); foreach (var currency in currencies) { - Assert.NotNull(sheet.OrderedList!.FirstOrDefault(row => - row.Ticker == currency.Ticker)); + Assert.NotNull( + sheet.OrderedList!.FirstOrDefault( + row => + row.Ticker == currency.Ticker)); } } @@ -191,8 +193,10 @@ public void GetSoulStones_With_Sheet() Assert.Equal(sheet.Count, currencies.Length); foreach (var currency in currencies) { - Assert.NotNull(sheet.OrderedList!.FirstOrDefault(row => - row.SoulStoneTicker == currency.Ticker)); + Assert.NotNull( + sheet.OrderedList!.FirstOrDefault( + row => + row.SoulStoneTicker == currency.Ticker)); } } diff --git a/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs b/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs index 03eb60a8b9..fbcab08f32 100644 --- a/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs @@ -17,8 +17,9 @@ public void Replace_List(int count, int index, bool throwException) var list = new List(new int[count]); if (throwException) { - Assert.Throws(() => - list.Replace(index, (Integer)1)); + Assert.Throws( + () => + list.Replace(index, (Integer)1)); } else { diff --git a/.Lib9c.Tests/Extensions/EquipmentExtensionsTest.cs b/.Lib9c.Tests/Extensions/EquipmentExtensionsTest.cs index 4a01d49654..272e2d6c1a 100644 --- a/.Lib9c.Tests/Extensions/EquipmentExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/EquipmentExtensionsTest.cs @@ -68,10 +68,11 @@ private void CheckAllRecipesIsMadeWithMimisbrunnrRecipeInternal(int randomSeed) false); try { - Assert.False(equipment.IsMadeWithMimisbrunnrRecipe( - recipeSheet, - subRecipeSheet, - equipmentOptionSheet)); + Assert.False( + equipment.IsMadeWithMimisbrunnrRecipe( + recipeSheet, + subRecipeSheet, + equipmentOptionSheet)); } catch { diff --git a/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs b/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs index fbb776b4bd..4e4d49a6a7 100644 --- a/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/EventDungeonExtensionsTest.cs @@ -34,8 +34,9 @@ public void ToEventDungeonStageNumber( public void ToEventDungeonStageNumber_Throw_ArgumentException( int eventDungeonStageId) { - Assert.Throws(() => - eventDungeonStageId.ToEventDungeonStageNumber()); + Assert.Throws( + () => + eventDungeonStageId.ToEventDungeonStageNumber()); } } } diff --git a/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs b/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs index 75e4692ea7..167017a7f9 100644 --- a/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/EventScheduleExtensionsTest.cs @@ -36,8 +36,9 @@ public void ToEventScheduleId( public void ToEventScheduleId_Throw_ArgumentException( int eventDungeonId) { - Assert.Throws(() => - eventDungeonId.ToEventScheduleId()); + Assert.Throws( + () => + eventDungeonId.ToEventScheduleId()); } [Theory] @@ -60,18 +61,19 @@ public void GetDungeonTicketCostV1( long expectedCost) { var scheduleRow = new EventScheduleSheet.Row(); - scheduleRow.Set(new[] - { - "0", - "0", - "0", - "0", - "0", - dungeonTicketPrice.ToString(), - dungeonTicketAdditionalPrice.ToString(), - "0", - "0", - }); + scheduleRow.Set( + new[] + { + "0", + "0", + "0", + "0", + "0", + dungeonTicketPrice.ToString(), + dungeonTicketAdditionalPrice.ToString(), + "0", + "0", + }); var cost = scheduleRow.GetDungeonTicketCostV1(numberOfTicketPurchases); Assert.Equal(expectedCost, cost); } @@ -97,18 +99,19 @@ public void GetDungeonTicketCost( int expectedFractionalDigits) { var scheduleRow = new EventScheduleSheet.Row(); - scheduleRow.Set(new[] - { - "0", - "0", - "0", - "0", - "0", - dungeonTicketPriceOnSheet.ToString(), - dungeonTicketAdditionalPriceOnSheet.ToString(), - "0", - "0", - }); + scheduleRow.Set( + new[] + { + "0", + "0", + "0", + "0", + "0", + dungeonTicketPriceOnSheet.ToString(), + dungeonTicketAdditionalPriceOnSheet.ToString(), + "0", + "0", + }); #pragma warning disable CS0618 // Use of obsolete method Currency.Legacy(): https://github.com/planetarium/lib9c/discussions/1319 var currency = Currency.Legacy("NCG", 2, null); @@ -127,19 +130,21 @@ public void GetDungeonTicketCost( public void GetDungeonTicketCost_Throw_ArgumentException( int numberOfTicketPurchases) { - Assert.Throws(() => - GetDungeonTicketCostV1( - default, - default, - numberOfTicketPurchases, - default)); - Assert.Throws(() => - GetDungeonTicketCost( - default, - default, - numberOfTicketPurchases, - default, - default)); + Assert.Throws( + () => + GetDungeonTicketCostV1( + default, + default, + numberOfTicketPurchases, + default)); + Assert.Throws( + () => + GetDungeonTicketCost( + default, + default, + numberOfTicketPurchases, + default, + default)); } [Theory] @@ -155,18 +160,19 @@ public void GetStageExp( int expected) { var scheduleRow = new EventScheduleSheet.Row(); - scheduleRow.Set(new[] - { - scheduleId.ToString(), - "0", - "0", - "0", - "0", - "0", - "0", - expSeedValue.ToString(), - "0", - }); + scheduleRow.Set( + new[] + { + scheduleId.ToString(), + "0", + "0", + "0", + "0", + "0", + "0", + expSeedValue.ToString(), + "0", + }); var actual = scheduleRow.GetStageExp(stageNumber, multiplier); Assert.Equal(expected, actual); } diff --git a/.Lib9c.Tests/Extensions/SheetsExtensionsTest.cs b/.Lib9c.Tests/Extensions/SheetsExtensionsTest.cs index b556f78a6e..eeb1ade4bf 100644 --- a/.Lib9c.Tests/Extensions/SheetsExtensionsTest.cs +++ b/.Lib9c.Tests/Extensions/SheetsExtensionsTest.cs @@ -76,10 +76,11 @@ internal static void InitSheets( var iSheetType = typeof(ISheet); var sheetNameAndFilesTemp = sheetNameAndFiles; sheetTypes = Assembly.GetAssembly(typeof(ISheet))?.GetTypes() - .Where(type => - iSheetType.IsAssignableFrom(type) && - !type.IsAbstract && - sheetNameAndFilesTemp.ContainsKey(type.Name)) + .Where( + type => + iSheetType.IsAssignableFrom(type) && + !type.IsAbstract && + sheetNameAndFilesTemp.ContainsKey(type.Name)) .ToArray(); Assert.NotNull(sheetTypes); Assert.NotEmpty(sheetTypes); diff --git a/.Lib9c.Tests/Helper/AdventureBossHelperTest.cs b/.Lib9c.Tests/Helper/AdventureBossHelperTest.cs index 49dd8992c1..bec9398cb5 100644 --- a/.Lib9c.Tests/Helper/AdventureBossHelperTest.cs +++ b/.Lib9c.Tests/Helper/AdventureBossHelperTest.cs @@ -34,8 +34,9 @@ public void SeasonToAddressForm(int season, string expectedAddr) public void CalculateWantedReward(int expectedReward) { var ncgRuneRatio = - TableExtensions.ParseDecimal(_tableSheets - .GameConfigSheet["adventure_boss_ncg_rune_ratio"].Value); + TableExtensions.ParseDecimal( + _tableSheets + .GameConfigSheet["adventure_boss_ncg_rune_ratio"].Value); var bountyBoard = new BountyBoard(1); bountyBoard.FixedRewardFavId = 30001; bountyBoard.RandomRewardFavId = 30001; @@ -69,11 +70,13 @@ out var ncgReward public void CalculateExploreReward(bool isReal, bool winner, int expectedNcgReward) { var ncgApRatio = - TableExtensions.ParseDecimal(_tableSheets - .GameConfigSheet["adventure_boss_ncg_ap_ratio"].Value); + TableExtensions.ParseDecimal( + _tableSheets + .GameConfigSheet["adventure_boss_ncg_ap_ratio"].Value); var ncgRuneRatio = - TableExtensions.ParseDecimal(_tableSheets - .GameConfigSheet["adventure_boss_ncg_rune_ratio"].Value); + TableExtensions.ParseDecimal( + _tableSheets + .GameConfigSheet["adventure_boss_ncg_rune_ratio"].Value); var bountyBoard = new BountyBoard(1); bountyBoard.AddOrUpdate(_avatarAddress, _name, 100 * NCG); diff --git a/.Lib9c.Tests/Helper/InventoryExtensionsTest.cs b/.Lib9c.Tests/Helper/InventoryExtensionsTest.cs index a3f667c521..3503a461f9 100644 --- a/.Lib9c.Tests/Helper/InventoryExtensionsTest.cs +++ b/.Lib9c.Tests/Helper/InventoryExtensionsTest.cs @@ -40,8 +40,9 @@ public void UseAp(int ap, int requiredAp, bool chargeAp, bool materialExist, Typ { var avatarAddress = new PrivateKey().Address; var inventory = new Inventory(); - var row = _tableSheets.MaterialItemSheet.Values.First(r => - r.ItemSubType == ItemSubType.ApStone); + var row = _tableSheets.MaterialItemSheet.Values.First( + r => + r.ItemSubType == ItemSubType.ApStone); if (materialExist) { var apStone = ItemFactory.CreateMaterial(row); @@ -63,7 +64,8 @@ public void UseAp(int ap, int requiredAp, bool chargeAp, bool materialExist, Typ else { Assert.Throws( - exc, () => inventory.UseActionPoint(ap, requiredAp, chargeAp, _tableSheets.MaterialItemSheet, 0L) + exc, + () => inventory.UseActionPoint(ap, requiredAp, chargeAp, _tableSheets.MaterialItemSheet, 0L) ); } } diff --git a/.Lib9c.Tests/Helper/PetHelperTest.cs b/.Lib9c.Tests/Helper/PetHelperTest.cs index 686ddb8088..764edd10d5 100644 --- a/.Lib9c.Tests/Helper/PetHelperTest.cs +++ b/.Lib9c.Tests/Helper/PetHelperTest.cs @@ -22,9 +22,10 @@ public void CalculateEnhancementCost() { var row = _petCostSheet.First!; var petId = row.PetId; - var cost = row.Cost.FirstOrDefault(cost => - cost.NcgQuantity > 0 || - cost.SoulStoneQuantity > 0); + var cost = row.Cost.FirstOrDefault( + cost => + cost.NcgQuantity > 0 || + cost.SoulStoneQuantity > 0); Assert.NotNull(cost); PetHelper.CalculateEnhancementCost( _petCostSheet, @@ -36,12 +37,13 @@ public void CalculateEnhancementCost() [Fact] public void CalculateEnhancementCost_Throw_ArgumentNullException() { - Assert.Throws(() => - PetHelper.CalculateEnhancementCost( - null, - 0, - 0, - 1)); + Assert.Throws( + () => + PetHelper.CalculateEnhancementCost( + null, + 0, + 0, + 1)); } [Theory] @@ -55,28 +57,31 @@ public void CalculateEnhancementCost_Throw_ArgumentException_PetId_PetLevel( int targetLevel) { petId ??= _petCostSheet.First!.PetId; - Assert.Throws(() => - PetHelper.CalculateEnhancementCost( - _petCostSheet, - petId.Value, - currentLevel, - targetLevel)); + Assert.Throws( + () => + PetHelper.CalculateEnhancementCost( + _petCostSheet, + petId.Value, + currentLevel, + targetLevel)); } [Fact] public void CalculateEnhancementCost_Throw_ArgumentException_Undefined_PetLevel() { var row = _petCostSheet.First!; - var cost = row.Cost.LastOrDefault(e => - e.NcgQuantity > 0 || - e.SoulStoneQuantity > 0); + var cost = row.Cost.LastOrDefault( + e => + e.NcgQuantity > 0 || + e.SoulStoneQuantity > 0); Assert.NotNull(cost); - Assert.Throws(() => - PetHelper.CalculateEnhancementCost( - _petCostSheet, - row.PetId, - cost.Level, - cost.Level + 1)); + Assert.Throws( + () => + PetHelper.CalculateEnhancementCost( + _petCostSheet, + row.PetId, + cost.Level, + cost.Level + 1)); } } } diff --git a/.Lib9c.Tests/JsonStatesLoaderTest.cs b/.Lib9c.Tests/JsonStatesLoaderTest.cs index 72b793dc7e..96d45c76f9 100644 --- a/.Lib9c.Tests/JsonStatesLoaderTest.cs +++ b/.Lib9c.Tests/JsonStatesLoaderTest.cs @@ -16,10 +16,11 @@ public void Load() { var codec = new Codec(); var barValue = (Text)"bar"; - IFileSystem fileSystem = new MockFileSystem(new Dictionary - { - { "/foo", new MockFileData($"{{\"foo\": \"{Convert.ToBase64String(codec.Encode(barValue))}\"}}") }, - }); + IFileSystem fileSystem = new MockFileSystem( + new Dictionary + { + { "/foo", new MockFileData($"{{\"foo\": \"{Convert.ToBase64String(codec.Encode(barValue))}\"}}") }, + }); var loader = new JsonStatesLoader(fileSystem); var states = loader.Load("/foo"); Assert.Single(states); diff --git a/.Lib9c.Tests/Model/ActivationKeyTest.cs b/.Lib9c.Tests/Model/ActivationKeyTest.cs index b0debd50ab..79ebfd8633 100644 --- a/.Lib9c.Tests/Model/ActivationKeyTest.cs +++ b/.Lib9c.Tests/Model/ActivationKeyTest.cs @@ -13,7 +13,7 @@ public void Create() { var privateKey = new PrivateKey(ByteUtil.ParseHex("ac84ad2eb0bc62c63e8c4e4f22f7c19d283b36e60fdc4eed182d4d7a7bb4c716")); var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; - (var ak, var pending) = ActivationKey.Create(privateKey, nonce); + var (ak, pending) = ActivationKey.Create(privateKey, nonce); Assert.Equal(privateKey, ak.PrivateKey); Assert.Equal(pending.address, ak.PendingAddress); diff --git a/.Lib9c.Tests/Model/AdventureBoss/AdventureBossSimulatorTest.cs b/.Lib9c.Tests/Model/AdventureBoss/AdventureBossSimulatorTest.cs index 262d0cc0a9..4d42fbfdae 100644 --- a/.Lib9c.Tests/Model/AdventureBoss/AdventureBossSimulatorTest.cs +++ b/.Lib9c.Tests/Model/AdventureBoss/AdventureBossSimulatorTest.cs @@ -174,8 +174,9 @@ public void AddBreakthrough(bool simulate, int bossId, int firstFloor, int lastF if (simulate) { - var anotherActions = simulator.Log.events.Where(e => - e.GetType() != typeof(Breakthrough) && e.GetType() != typeof(SpawnPlayer)); + var anotherActions = simulator.Log.events.Where( + e => + e.GetType() != typeof(Breakthrough) && e.GetType() != typeof(SpawnPlayer)); Assert.NotEmpty(anotherActions); Assert.NotEmpty(simulator.Log.OfType()); } diff --git a/.Lib9c.Tests/Model/ArenaSimulatorTest.cs b/.Lib9c.Tests/Model/ArenaSimulatorTest.cs index 397e9f285c..8a741890c6 100644 --- a/.Lib9c.Tests/Model/ArenaSimulatorTest.cs +++ b/.Lib9c.Tests/Model/ArenaSimulatorTest.cs @@ -261,15 +261,17 @@ public void Thorns() avatarState2.inventory.AddItem(equipment2); var arenaAvatarState1 = new ArenaAvatarState(avatarState1); - arenaAvatarState1.UpdateEquipment(new List - { - equipment.ItemId, - }); + arenaAvatarState1.UpdateEquipment( + new List + { + equipment.ItemId, + }); var arenaAvatarState2 = new ArenaAvatarState(avatarState2); - arenaAvatarState2.UpdateEquipment(new List - { - equipment2.ItemId, - }); + arenaAvatarState2.UpdateEquipment( + new List + { + equipment2.ItemId, + }); var simulator = new ArenaSimulator(_random); var myDigest = new ArenaPlayerDigest(avatarState1, arenaAvatarState1); @@ -310,11 +312,12 @@ public void Bleed() var optionInfo = runeRow.LevelOptionMap[89]; var statModifiers = new List(); statModifiers.AddRange( - optionInfo.Stats.Select(x => - new StatModifier( - x.stat.StatType, - x.operationType, - x.stat.TotalValueAsLong))); + optionInfo.Stats.Select( + x => + new StatModifier( + x.stat.StatType, + x.operationType, + x.stat.TotalValueAsLong))); foreach (var modifier in statModifiers) { if (modifier.StatType == StatType.ATK) diff --git a/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs b/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs index 19d93b9a0e..1588042628 100644 --- a/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs +++ b/.Lib9c.Tests/Model/Event/EventDungeonInfoTest.cs @@ -59,12 +59,13 @@ public void Constructor_Throw_ArgumentException( int numberOfTicketPurchases, int clearedStageId) { - Assert.Throws(() => - new EventDungeonInfo( - resetTicketsInterval, - remainingTickets, - numberOfTicketPurchases, - clearedStageId)); + Assert.Throws( + () => + new EventDungeonInfo( + resetTicketsInterval, + remainingTickets, + numberOfTicketPurchases, + clearedStageId)); } [Theory] @@ -121,8 +122,9 @@ public void ResetTickets_Throw_ArgumentException( int tickets) { var eventDungeonInfo = new EventDungeonInfo(); - Assert.Throws(() => - eventDungeonInfo.ResetTickets(resetTicketsInterval, tickets)); + Assert.Throws( + () => + eventDungeonInfo.ResetTickets(resetTicketsInterval, tickets)); } [Theory] @@ -131,8 +133,9 @@ public void ResetTickets_Throw_ArgumentException( public void HasTickets_Throw_ArgumentException(int tickets) { var eventDungeonInfo = new EventDungeonInfo(); - Assert.Throws(() => - eventDungeonInfo.HasTickets(tickets)); + Assert.Throws( + () => + eventDungeonInfo.HasTickets(tickets)); } [Theory] @@ -141,8 +144,9 @@ public void HasTickets_Throw_ArgumentException(int tickets) public void TryUseTickets_Throw_ArgumentException(int tickets) { var eventDungeonInfo = new EventDungeonInfo(); - Assert.Throws(() => - eventDungeonInfo.TryUseTickets(tickets)); + Assert.Throws( + () => + eventDungeonInfo.TryUseTickets(tickets)); } [Theory] @@ -174,13 +178,14 @@ public void IncreaseNumberOfTicketPurchases_Throw_InvalidOperationException( { var eventDungeonInfo = new EventDungeonInfo( numberOfTicketPurchases: initialNumberOfTicketPurchases); - Assert.Throws(() => - { - for (var i = 0; i < numberOfIncrease; i++) + Assert.Throws( + () => { - eventDungeonInfo.IncreaseNumberOfTicketPurchases(); - } - }); + for (var i = 0; i < numberOfIncrease; i++) + { + eventDungeonInfo.IncreaseNumberOfTicketPurchases(); + } + }); } [Theory] diff --git a/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs b/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs index 4f2aa0b435..c368bd752a 100644 --- a/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs +++ b/.Lib9c.Tests/Model/Garages/FungibleItemGarageTest.cs @@ -49,8 +49,9 @@ public void Constructor_Success(int count) [InlineData(int.MaxValue)] public void Constructor_Failure_With_Null_Item(int count) { - Assert.Throws(() => - new FungibleItemGarage(null!, count)); + Assert.Throws( + () => + new FungibleItemGarage(null!, count)); } [Theory] @@ -58,19 +59,23 @@ public void Constructor_Failure_With_Null_Item(int count) [InlineData(-1)] public void Constructor_Failure_With_Negative_Count(int count) { - Assert.Throws(() => - new FungibleItemGarage(_tradableMaterial, count)); - Assert.Throws(() => - new FungibleItemGarage(_tradableMaterial2, count)); + Assert.Throws( + () => + new FungibleItemGarage(_tradableMaterial, count)); + Assert.Throws( + () => + new FungibleItemGarage(_tradableMaterial2, count)); } [Fact] public void Constructor_With_IValue_Failure() { - Assert.Throws(() => - new FungibleItemGarage(null)); - Assert.Throws(() => - new FungibleItemGarage(Null.Value)); + Assert.Throws( + () => + new FungibleItemGarage(null)); + Assert.Throws( + () => + new FungibleItemGarage(Null.Value)); } [Theory] @@ -94,8 +99,9 @@ public void Load_Success(int count1, int count2) public void Load_Failure(int count1, int count2) { var garage = new FungibleItemGarage(_tradableMaterial, count1); - Assert.Throws(() => - garage.Load(count2)); + Assert.Throws( + () => + garage.Load(count2)); } [Theory] @@ -121,8 +127,9 @@ public void Deliver_Failure_With_Invalid_Count(int count1, int count2) { var garage1 = new FungibleItemGarage(_tradableMaterial, count1); var garage2 = new FungibleItemGarage(_tradableMaterial, 0); - Assert.Throws(() => - garage1.Deliver(garage2, count2)); + Assert.Throws( + () => + garage1.Deliver(garage2, count2)); } [Fact] @@ -130,8 +137,9 @@ public void Deliver_Failure_With_Mismatch_Item() { var garage1 = new FungibleItemGarage(_tradableMaterial, 1); var garage2 = new FungibleItemGarage(_tradableMaterial2, 0); - Assert.Throws(() => - garage1.Deliver(garage2, 1)); + Assert.Throws( + () => + garage1.Deliver(garage2, 1)); } [Theory] @@ -154,8 +162,9 @@ public void Unload_Success(int count1, int count2) public void Unload_Failure(int count1, int count2) { var garage = new FungibleItemGarage(_tradableMaterial, count1); - Assert.Throws(() => - garage.Unload(count2)); + Assert.Throws( + () => + garage.Unload(count2)); } private static void AssertSerialization(FungibleItemGarage garage) diff --git a/.Lib9c.Tests/Model/Item/ArmorTest.cs b/.Lib9c.Tests/Model/Item/ArmorTest.cs index 7bd14187c3..f1c92d4bb8 100644 --- a/.Lib9c.Tests/Model/Item/ArmorTest.cs +++ b/.Lib9c.Tests/Model/Item/ArmorTest.cs @@ -13,8 +13,9 @@ public class ArmorTest public ArmorTest() { var tableSheets = new TableSheets(TableSheetsImporter.ImportSheets()); - _armorRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault(row => - row.ItemSubType == ItemSubType.Armor); + _armorRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault( + row => + row.ItemSubType == ItemSubType.Armor); } [Fact] diff --git a/.Lib9c.Tests/Model/Item/BeltTest.cs b/.Lib9c.Tests/Model/Item/BeltTest.cs index f949893ee0..aa51149199 100644 --- a/.Lib9c.Tests/Model/Item/BeltTest.cs +++ b/.Lib9c.Tests/Model/Item/BeltTest.cs @@ -13,8 +13,9 @@ public class BeltTest public BeltTest() { var tableSheets = new TableSheets(TableSheetsImporter.ImportSheets()); - _beltRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault(row => - row.ItemSubType == ItemSubType.Belt); + _beltRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault( + row => + row.ItemSubType == ItemSubType.Belt); } [Fact] diff --git a/.Lib9c.Tests/Model/Item/EquipmentTest.cs b/.Lib9c.Tests/Model/Item/EquipmentTest.cs index f775138c39..a5b7f7542f 100644 --- a/.Lib9c.Tests/Model/Item/EquipmentTest.cs +++ b/.Lib9c.Tests/Model/Item/EquipmentTest.cs @@ -73,7 +73,8 @@ public void LevelUp() public void GetHammerExp() { var costSheet = new EnhancementCostSheetV3(); - costSheet.Set(@"600301,EquipmentMaterial,1,0,0,100,0,0,0,0,0,0,0,0,0 + costSheet.Set( + @"600301,EquipmentMaterial,1,0,0,100,0,0,0,0,0,0,0,0,0 600302,EquipmentMaterial,2,0,0,200,0,0,0,0,0,0,0,0,0 600303,EquipmentMaterial,3,0,0,300,0,0,0,0,0,0,0,0,0 600304,EquipmentMaterial,4,0,0,400,0,0,0,0,0,0,0,0,0 diff --git a/.Lib9c.Tests/Model/Item/NecklaceTest.cs b/.Lib9c.Tests/Model/Item/NecklaceTest.cs index 95c2b291bf..c1e8c63406 100644 --- a/.Lib9c.Tests/Model/Item/NecklaceTest.cs +++ b/.Lib9c.Tests/Model/Item/NecklaceTest.cs @@ -13,8 +13,9 @@ public class NecklaceTest public NecklaceTest() { var tableSheets = new TableSheets(TableSheetsImporter.ImportSheets()); - _necklaceRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault(row => - row.ItemSubType == ItemSubType.Necklace); + _necklaceRow = tableSheets.EquipmentItemSheet.OrderedList.FirstOrDefault( + row => + row.ItemSubType == ItemSubType.Necklace); } [Fact] diff --git a/.Lib9c.Tests/Model/Item/ShopItemTest.cs b/.Lib9c.Tests/Model/Item/ShopItemTest.cs index 06d4aacf7c..6604f2efd6 100644 --- a/.Lib9c.Tests/Model/Item/ShopItemTest.cs +++ b/.Lib9c.Tests/Model/Item/ShopItemTest.cs @@ -78,13 +78,14 @@ public void ThrowArgumentOurOfRangeException() { var equipmentRow = _tableSheets.EquipmentItemSheet.First; var equipment = ItemFactory.CreateItemUsable(equipmentRow, Guid.NewGuid(), 0); - Assert.Throws(() => new ShopItem( - new PrivateKey().Address, - new PrivateKey().Address, - Guid.NewGuid(), - new FungibleAssetValue(_currency, 100, 0), - -1, - (ITradableItem)equipment)); + Assert.Throws( + () => new ShopItem( + new PrivateKey().Address, + new PrivateKey().Address, + Guid.NewGuid(), + new FungibleAssetValue(_currency, 100, 0), + -1, + (ITradableItem)equipment)); } [Fact] diff --git a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs index c32f24f952..591721ee51 100644 --- a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs @@ -20,8 +20,9 @@ public class CustomCraftMailTest public void Serialize() { var row = new EquipmentItemSheet.Row(); - row.Set(new List - { "20151000", "Weapon", "6", "Normal", "0", "ATK", "10", "0", "20160000", "0", }); + row.Set( + new List + { "20151000", "Weapon", "6", "Normal", "0", "ATK", "10", "0", "20160000", "0", }); var equipment = (Equipment)ItemFactory.CreateItemUsable(row, Guid.NewGuid(), 1L); var mail = new CustomCraftMail(1, Guid.NewGuid(), 2, equipment); var serialized = (Dictionary)mail.Serialize(); diff --git a/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs b/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs index bbee6a595a..1dc7fc404d 100644 --- a/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/UnloadFromMyGaragesRecipientMailTest.cs @@ -18,14 +18,15 @@ public class UnloadFromMyGaragesRecipientMailTest { public static IEnumerable Get_Sample_PlainValue() { - return UnloadFromMyGaragesTest.Get_Sample_PlainValue().Select(objects => - new[] - { - // objects[0], This test doesn't need to test recipientAvatarAddr. - objects[1], - objects[2], - objects[3], - }); + return UnloadFromMyGaragesTest.Get_Sample_PlainValue().Select( + objects => + new[] + { + // objects[0], This test doesn't need to test recipientAvatarAddr. + objects[1], + objects[2], + objects[3], + }); } [Theory] @@ -46,9 +47,11 @@ public void Serialize( memo); var mailValue = mail.Serialize(); var de = new UnloadFromMyGaragesRecipientMail((Dictionary)mailValue); - Assert.True(mail.FungibleAssetValues?.SequenceEqual(de.FungibleAssetValues!) ?? + Assert.True( + mail.FungibleAssetValues?.SequenceEqual(de.FungibleAssetValues!) ?? de.FungibleAssetValues is null); - Assert.True(mail.FungibleIdAndCounts?.SequenceEqual(de.FungibleIdAndCounts!) ?? + Assert.True( + mail.FungibleIdAndCounts?.SequenceEqual(de.FungibleIdAndCounts!) ?? de.FungibleIdAndCounts is null); Assert.Equal(mail.Memo, de.Memo); var mailValue2 = de.Serialize(); diff --git a/.Lib9c.Tests/Model/Order/OrderBaseTest.cs b/.Lib9c.Tests/Model/Order/OrderBaseTest.cs index f699bd42f8..1922370082 100644 --- a/.Lib9c.Tests/Model/Order/OrderBaseTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderBaseTest.cs @@ -34,7 +34,9 @@ public void OrderBase(long startedBlockIndex, long expiredBlockIndex, Type exc) } else { - Assert.Throws(exc, () => new OrderBase( + Assert.Throws( + exc, + () => new OrderBase( Guid.NewGuid(), Guid.NewGuid(), startedBlockIndex, diff --git a/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs b/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs index 7f9a244dfb..6509b07e06 100644 --- a/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs +++ b/.Lib9c.Tests/Model/Order/OrderFactoryTest.cs @@ -94,8 +94,9 @@ public void Create(ItemType itemType, long blockIndex, Order.OrderType orderType [InlineData(ItemSubType.NormalMaterial)] public void Create_Throw_InvalidItemTypeException(ItemSubType itemSubType) { - Assert.Throws(() => - OrderFactory.Create(default, default, default, default, default, default, itemSubType, 1)); + Assert.Throws( + () => + OrderFactory.Create(default, default, default, default, default, default, itemSubType, 1)); } [Theory] diff --git a/.Lib9c.Tests/Model/PlayerTest.cs b/.Lib9c.Tests/Model/PlayerTest.cs index b8daf38b22..993ed7f4cf 100644 --- a/.Lib9c.Tests/Model/PlayerTest.cs +++ b/.Lib9c.Tests/Model/PlayerTest.cs @@ -657,7 +657,8 @@ public void Vampiric(int duration, int percent) // force add buff 'Vampiric' // 705000 is ActionBuff id of Vampiric var vampiric = (Vampiric)BuffFactory.GetCustomActionBuff( - new SkillCustomField { BuffDuration = duration, BuffValue = percent, }, actionBuffSheet[705000]); + new SkillCustomField { BuffDuration = duration, BuffValue = percent, }, + actionBuffSheet[705000]); player.AddBuff(vampiric); var row = actionBuffSheet.Values.First(); var bleed = BuffFactory.GetActionBuff(enemy.Stats, row); @@ -705,8 +706,9 @@ public void Vampiric(int duration, int percent) [Fact] public void StatsLayerTest() { - var row = _tableSheets.EquipmentItemSheet.Values.First(r => - r.Stat.StatType == StatType.ATK); + var row = _tableSheets.EquipmentItemSheet.Values.First( + r => + r.Stat.StatType == StatType.ATK); var equipment = (Equipment)ItemFactory.CreateItem(_tableSheets.ItemSheet[row.Id], new TestRandom()); equipment.equipped = true; _avatarState.inventory.AddItem(equipment); @@ -717,8 +719,9 @@ public void StatsLayerTest() // costume.equipped = true; // _avatarState.inventory.AddItem(costume); var foodRow = - _tableSheets.ConsumableItemSheet.Values.First(r => - r.Stats.Any(s => s.StatType == StatType.ATK)); + _tableSheets.ConsumableItemSheet.Values.First( + r => + r.Stats.Any(s => s.StatType == StatType.ATK)); var food = (Consumable)ItemFactory.CreateItem(foodRow, _random); _avatarState.inventory.AddItem(food); var runeId = 10002; @@ -800,9 +803,10 @@ public void StatsLayerTest() // Assert.Equal(3304, player.ATK); // Update skill buff stats - var percentageBuffRow = _tableSheets.StatBuffSheet.Values.First(r => - r.StatType == StatType.ATK && - r.OperationType == StatModifier.OperationType.Percentage); + var percentageBuffRow = _tableSheets.StatBuffSheet.Values.First( + r => + r.StatType == StatType.ATK && + r.OperationType == StatModifier.OperationType.Percentage); var percentageBuff = new StatBuff(percentageBuffRow); statBuffs.Add(percentageBuff); var percentageModifier = percentageBuff.GetModifier(); @@ -830,8 +834,9 @@ public void StatsLayerTest() [Fact] public void IncreaseHpForArena() { - var row = _tableSheets.EquipmentItemSheet.Values.First(r => - r.Stat.StatType == StatType.HP); + var row = _tableSheets.EquipmentItemSheet.Values.First( + r => + r.Stat.StatType == StatType.HP); var equipment = (Equipment)ItemFactory.CreateItem(_tableSheets.ItemSheet[row.Id], new TestRandom()); equipment.equipped = true; _avatarState.inventory.AddItem(equipment); @@ -842,8 +847,9 @@ public void IncreaseHpForArena() costume.equipped = true; _avatarState.inventory.AddItem(costume); var foodRow = - _tableSheets.ConsumableItemSheet.Values.First(r => - r.Stats.Any(s => s.StatType == StatType.HP)); + _tableSheets.ConsumableItemSheet.Values.First( + r => + r.Stats.Any(s => s.StatType == StatType.HP)); var food = (Consumable)ItemFactory.CreateItem(foodRow, _random); _avatarState.inventory.AddItem(food); @@ -860,10 +866,11 @@ public void IncreaseHpForArena() var equipmentLayerHp = player.HP; // Update consumable stats - player.Use(new List - { - food.ItemId, - }); + player.Use( + new List + { + food.ItemId, + }); Assert.Equal(equipmentLayerHp + food.Stats.Where(s => s.StatType == StatType.HP).Sum(s => s.BaseValueAsLong), player.HP); // ConsumableStats 29 // Assert.Equal(359, player.HP); @@ -915,9 +922,10 @@ public void IncreaseHpForArena() var arenaHp = player.HP; var statBuffs = new List(); - var percentageBuffRow = _tableSheets.StatBuffSheet.Values.First(r => - r.StatType == StatType.HP && - r.OperationType == StatModifier.OperationType.Percentage); + var percentageBuffRow = _tableSheets.StatBuffSheet.Values.First( + r => + r.StatType == StatType.HP && + r.OperationType == StatModifier.OperationType.Percentage); var percentageBuff = new StatBuff(percentageBuffRow); statBuffs.Add(percentageBuff); var percentageModifier = percentageBuff.GetModifier(); diff --git a/.Lib9c.Tests/Model/QuestListTest.cs b/.Lib9c.Tests/Model/QuestListTest.cs index 37eb352596..1068df9617 100644 --- a/.Lib9c.Tests/Model/QuestListTest.cs +++ b/.Lib9c.Tests/Model/QuestListTest.cs @@ -197,13 +197,14 @@ public void UpdateList_Throw_UpdateListVersionException(int listVersion) ); Assert.Equal(1, questList.ListVersion); - Assert.Throws(() => - questList.UpdateListV1( - listVersion, - _tableSheets.QuestSheet, - _tableSheets.QuestRewardSheet, - _tableSheets.QuestItemRewardSheet, - _tableSheets.EquipmentItemRecipeSheet)); + Assert.Throws( + () => + questList.UpdateListV1( + listVersion, + _tableSheets.QuestSheet, + _tableSheets.QuestRewardSheet, + _tableSheets.QuestItemRewardSheet, + _tableSheets.EquipmentItemRecipeSheet)); } [Fact] @@ -218,13 +219,14 @@ public void UpdateList_Throw_UpdateListQuestsCountException() ); Assert.Equal(1, questList.ListVersion); - Assert.Throws(() => - questList.UpdateListV1( - 2, - _tableSheets.QuestSheet, - _tableSheets.QuestRewardSheet, - _tableSheets.QuestItemRewardSheet, - _tableSheets.EquipmentItemRecipeSheet)); + Assert.Throws( + () => + questList.UpdateListV1( + 2, + _tableSheets.QuestSheet, + _tableSheets.QuestRewardSheet, + _tableSheets.QuestItemRewardSheet, + _tableSheets.EquipmentItemRecipeSheet)); } [Fact] diff --git a/.Lib9c.Tests/Model/QuestRewardTest.cs b/.Lib9c.Tests/Model/QuestRewardTest.cs index 4902acadff..8d075e46e2 100644 --- a/.Lib9c.Tests/Model/QuestRewardTest.cs +++ b/.Lib9c.Tests/Model/QuestRewardTest.cs @@ -12,11 +12,12 @@ public class QuestRewardTest [Fact] public void Serialize() { - var reward = new QuestReward(new Dictionary() - { - [2] = 1, - [1] = 1, - }); + var reward = new QuestReward( + new Dictionary() + { + [2] = 1, + [1] = 1, + }); var expected = new[] { diff --git a/.Lib9c.Tests/Model/SimulatorTest.cs b/.Lib9c.Tests/Model/SimulatorTest.cs index 4b0498de3b..dca9cae80e 100644 --- a/.Lib9c.Tests/Model/SimulatorTest.cs +++ b/.Lib9c.Tests/Model/SimulatorTest.cs @@ -25,15 +25,16 @@ public SimulatorTest() public void SetRewardAll() { var row = new StageSheet.Row(); - row.Set(new List - { - "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "1", - "1", "303000", "0.01", "1", "1", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "2", "2", - }); + row.Set( + new List + { + "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "1", + "1", "303000", "0.01", "1", "1", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "2", "2", + }); var itemSelector = StageSimulatorV1.SetItemSelector(row, _random); var reward = Simulator.SetReward(itemSelector, _random.Next(2, 2), _random, _materialItemSheet); Assert.Equal(2, reward.Count); @@ -45,15 +46,16 @@ public void SetRewardAll() public void SetRewardDuplicateItem() { var row = new StageSheet.Row(); - row.Set(new List - { - "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "2", - "2", "303000", "0.01", "2", "2", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "2", "2", - }); + row.Set( + new List + { + "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "2", + "2", "303000", "0.01", "2", "2", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "2", "2", + }); var itemSelector = StageSimulatorV1.SetItemSelector(row, _random); var reward = Simulator.SetReward(itemSelector, _random.Next(2, 2), _random, _materialItemSheet); Assert.Equal(2, reward.Count); @@ -65,15 +67,16 @@ public void SetRewardDuplicateItem() public void SetRewardLimitByStageDrop() { var row = new StageSheet.Row(); - row.Set(new List - { - "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "2", - "2", "303000", "0.01", "2", "2", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "1", "1", - }); + row.Set( + new List + { + "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "2", + "2", "303000", "0.01", "2", "2", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "1", "1", + }); var itemSelector = StageSimulatorV1.SetItemSelector(row, _random); var reward = Simulator.SetReward(itemSelector, _random.Next(1, 1), _random, _materialItemSheet); Assert.Single(reward); @@ -83,15 +86,16 @@ public void SetRewardLimitByStageDrop() public void SetRewardLimitByItemDrop() { var row = new StageSheet.Row(); - row.Set(new List - { - "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "1", - "1", "303000", "0.01", "1", "1", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, - string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "1", "4", - }); + row.Set( + new List + { + "1", "5", "100", "0", "0", "0", "0", "0", "0", "chapter_1_1", "bgm_stage_green", "306043", "1", "1", + "1", "303000", "0.01", "1", "1", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, + string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, "1", "4", + }); var itemSelector = StageSimulatorV1.SetItemSelector(row, _random); var reward = Simulator.SetReward(itemSelector, _random.Next(1, 4), _random, _materialItemSheet); Assert.True(reward.Count <= 2); diff --git a/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs b/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs index 909afb9abb..6032c52bdf 100644 --- a/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs +++ b/.Lib9c.Tests/Model/Skill/Adventure/ShatterStrikeTest.cs @@ -78,11 +78,12 @@ public void Use(int enemyHp, int ratioBp, bool expectedEnemyDead, bool copyChara var player = new Player(avatarState, simulator); var enemyRow = _tableSheets.CharacterSheet.OrderedList .FirstOrDefault(e => e.Id > 200000); - enemyRow.Set(new[] - { - "201000", "XS", "2", enemyHp.ToString(), "16", "6", "4", "90", "15", "3.2", "0.64", - "0.24", "0", "3.6", "0.6", "0.8", "1.2", - }); + enemyRow.Set( + new[] + { + "201000", "XS", "2", enemyHp.ToString(), "16", "6", "4", "90", "15", "3.2", "0.64", + "0.24", "0", "3.6", "0.6", "0.8", "1.2", + }); Assert.NotNull(enemyRow); var enemy = new Enemy(player, enemyRow, 1); @@ -158,11 +159,12 @@ public void Use_MaxDamage(bool copyCharacter) var player = new Player(avatarState, simulator); var enemyRow = _tableSheets.CharacterSheet.OrderedList .FirstOrDefault(e => e.Id > 200000); - enemyRow.Set(new[] - { - "201000", "XS", "2", "100", "16", "0", "4", "90", "15", "3.2", "0.64", - "0.24", "0", "3.6", "0.6", "0.8", "1.2", - }); + enemyRow.Set( + new[] + { + "201000", "XS", "2", "100", "16", "0", "4", "90", "15", "3.2", "0.64", + "0.24", "0", "3.6", "0.6", "0.8", "1.2", + }); Assert.NotNull(enemyRow); var enemy = new Enemy(player, enemyRow, 1); diff --git a/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs b/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs index 3692faebf0..7361379a36 100644 --- a/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs +++ b/.Lib9c.Tests/Model/Skill/Arena/ArenaCombatTest.cs @@ -84,14 +84,18 @@ public void DispelOnUse(int dispelId, int[] debuffIdList) .BuffIds.First() ); var dispel = new ArenaBuffSkill(skillRow, 0, 100, 0, StatType.NONE); - dispel.Use(challenger, challenger, simulator.Turn, BuffFactory.GetBuffs( - challenger.Stats, - dispel, - _tableSheets.SkillBuffSheet, - _tableSheets.StatBuffSheet, - _tableSheets.SkillActionBuffSheet, - _tableSheets.ActionBuffSheet - )); + dispel.Use( + challenger, + challenger, + simulator.Turn, + BuffFactory.GetBuffs( + challenger.Stats, + dispel, + _tableSheets.SkillBuffSheet, + _tableSheets.StatBuffSheet, + _tableSheets.SkillActionBuffSheet, + _tableSheets.ActionBuffSheet + )); Assert.Single(challenger.Buffs); Assert.Equal(dispelRow.GroupId, challenger.Buffs.First().Value.BuffInfo.GroupId); } diff --git a/.Lib9c.Tests/Model/Skill/Arena/ArenaNormalAttackTest.cs b/.Lib9c.Tests/Model/Skill/Arena/ArenaNormalAttackTest.cs index 01e645b86d..4cd55faa78 100644 --- a/.Lib9c.Tests/Model/Skill/Arena/ArenaNormalAttackTest.cs +++ b/.Lib9c.Tests/Model/Skill/Arena/ArenaNormalAttackTest.cs @@ -86,10 +86,12 @@ public void FocusSkill() challenger = new ArenaCharacter(simulator, myDigest, arenaSheets, simulator.HpModifier, new List()); enemy = new ArenaCharacter(simulator, enemyDigest, arenaSheets, simulator.HpModifier, new List()); - challenger.AddBuff(new Focus( - _tableSheets.ActionBuffSheet.OrderedList.First(s => - s.ActionBuffType == ActionBuffType.Focus) - )); + challenger.AddBuff( + new Focus( + _tableSheets.ActionBuffSheet.OrderedList.First( + s => + s.ActionBuffType == ActionBuffType.Focus) + )); Assert.Single(challenger.ActionBuffs); skill = new ArenaNormalAttack(skillRow, 100, 100, 0, StatType.NONE); diff --git a/.Lib9c.Tests/Model/StageSimulatorTest.cs b/.Lib9c.Tests/Model/StageSimulatorTest.cs index 5230301593..846b365296 100644 --- a/.Lib9c.Tests/Model/StageSimulatorTest.cs +++ b/.Lib9c.Tests/Model/StageSimulatorTest.cs @@ -93,9 +93,10 @@ public void Simulate() var filtered = simulator.Log .Select(e => e.GetType()) - .Where(type => - type != typeof(GetReward) || - type != typeof(DropBox)); + .Where( + type => + type != typeof(GetReward) || + type != typeof(DropBox)); Assert.Equal(typeof(WaveTurnEnd), filtered.Last()); Assert.Equal(1, simulator.Log.OfType().First().TurnNumber); } diff --git a/.Lib9c.Tests/Model/Stake/ContractTest.cs b/.Lib9c.Tests/Model/Stake/ContractTest.cs index 739c8b83e4..8e32e684b4 100644 --- a/.Lib9c.Tests/Model/Stake/ContractTest.cs +++ b/.Lib9c.Tests/Model/Stake/ContractTest.cs @@ -77,11 +77,12 @@ public void Constructor_Throws_ArgumentException( long rewardInterval, long lockupInterval) { - Assert.Throws(() => new Contract( - stakeRegularFixedRewardSheetTableName, - stakeRegularRewardSheetTableName, - rewardInterval, - lockupInterval)); + Assert.Throws( + () => new Contract( + stakeRegularFixedRewardSheetTableName, + stakeRegularRewardSheetTableName, + rewardInterval, + lockupInterval)); } [Theory] @@ -111,11 +112,12 @@ public void Constructor_Throws_ArgumentOutOfRangeException( long rewardInterval, long lockupInterval) { - Assert.Throws(() => new Contract( - stakeRegularFixedRewardSheetTableName, - stakeRegularRewardSheetTableName, - rewardInterval, - lockupInterval)); + Assert.Throws( + () => new Contract( + stakeRegularFixedRewardSheetTableName, + stakeRegularRewardSheetTableName, + rewardInterval, + lockupInterval)); } [Fact] diff --git a/.Lib9c.Tests/Model/Stake/StakeStateUtilsTest.cs b/.Lib9c.Tests/Model/Stake/StakeStateUtilsTest.cs index 37626bee61..065e99a350 100644 --- a/.Lib9c.Tests/Model/Stake/StakeStateUtilsTest.cs +++ b/.Lib9c.Tests/Model/Stake/StakeStateUtilsTest.cs @@ -19,8 +19,9 @@ public class StakeStateUtilsTest [Fact] public void TryMigrate_Throw_NullReferenceException_When_IAccountDelta_Null() { - Assert.Throws(() => - StakeStateUtils.TryMigrate((IWorld)null, default, out _)); + Assert.Throws( + () => + StakeStateUtils.TryMigrate((IWorld)null, default, out _)); } [Fact] diff --git a/.Lib9c.Tests/Model/Stake/StakeStateV2Test.cs b/.Lib9c.Tests/Model/Stake/StakeStateV2Test.cs index e2470170eb..4db820f2aa 100644 --- a/.Lib9c.Tests/Model/Stake/StakeStateV2Test.cs +++ b/.Lib9c.Tests/Model/Stake/StakeStateV2Test.cs @@ -39,8 +39,9 @@ public void Constructor_Throw_ArgumentNullException( long startedBlockIndex, long receivedBlockIndex) { - Assert.Throws(() => - new StakeStateV2(null, startedBlockIndex, receivedBlockIndex)); + Assert.Throws( + () => + new StakeStateV2(null, startedBlockIndex, receivedBlockIndex)); } [Theory] @@ -51,8 +52,9 @@ public void Constructor_Throw_ArgumentOutOfRangeException( long startedBlockIndex, long receivedBlockIndex) { - Assert.Throws(() => - new StakeStateV2(null, startedBlockIndex, receivedBlockIndex)); + Assert.Throws( + () => + new StakeStateV2(null, startedBlockIndex, receivedBlockIndex)); } [Theory] diff --git a/.Lib9c.Tests/Model/State/AvatarStateTest.cs b/.Lib9c.Tests/Model/State/AvatarStateTest.cs index 0b57bb7ce7..b66e98db3c 100644 --- a/.Lib9c.Tests/Model/State/AvatarStateTest.cs +++ b/.Lib9c.Tests/Model/State/AvatarStateTest.cs @@ -393,8 +393,9 @@ public void EquipItems() Assert.False(equippableItem.Equipped); } - avatarState.EquipItems(equippableItems.OfType() - .Select(nonFungibleItem => nonFungibleItem.NonFungibleId)); + avatarState.EquipItems( + equippableItems.OfType() + .Select(nonFungibleItem => nonFungibleItem.NonFungibleId)); foreach (var equippableItem in equippableItems) { diff --git a/.Lib9c.Tests/Model/State/PetStateTest.cs b/.Lib9c.Tests/Model/State/PetStateTest.cs index 38e1a050ad..77bf31e465 100644 --- a/.Lib9c.Tests/Model/State/PetStateTest.cs +++ b/.Lib9c.Tests/Model/State/PetStateTest.cs @@ -42,8 +42,9 @@ public void LevelUp(int initialLevel, bool shouldThrow) Assert.Equal(initialLevel, state.Level); if (shouldThrow) { - Assert.Throws(() => - state.LevelUp()); + Assert.Throws( + () => + state.LevelUp()); } else { diff --git a/.Lib9c.Tests/Model/State/RankingState1Test.cs b/.Lib9c.Tests/Model/State/RankingState1Test.cs index 98e99ce568..59484e2943 100644 --- a/.Lib9c.Tests/Model/State/RankingState1Test.cs +++ b/.Lib9c.Tests/Model/State/RankingState1Test.cs @@ -76,8 +76,9 @@ public void UpdateRankingMapThrowRankingExceededException() state.UpdateRankingMap(address.Derive(i.ToString())); } - var exec = Assert.Throws(() => - state.UpdateRankingMap(address.Derive((max + 1).ToString()))); + var exec = Assert.Throws( + () => + state.UpdateRankingMap(address.Derive((max + 1).ToString()))); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); @@ -91,18 +92,23 @@ public void UpdateRankingMapThrowRankingExceededException() private static IValue SerializeV1_With_Deterministic_Problem(RankingState1 rankingState) { #pragma warning disable LAA1002 - return new Dictionary(new Dictionary - { - [(Text)"ranking_map"] = new Dictionary(rankingState.RankingMap.Select(kv => - new KeyValuePair( - (Binary)kv.Key.Serialize(), - new List(kv.Value.Select(a => a.Serialize())) - ) - )), - }.Union(new Dictionary(new Dictionary - { - [(Text)LegacyAddressKey] = rankingState.address.Serialize(), - }))); + return new Dictionary( + new Dictionary + { + [(Text)"ranking_map"] = new Dictionary( + rankingState.RankingMap.Select( + kv => + new KeyValuePair( + (Binary)kv.Key.Serialize(), + new List(kv.Value.Select(a => a.Serialize())) + ) + )), + }.Union( + new Dictionary( + new Dictionary + { + [(Text)LegacyAddressKey] = rankingState.address.Serialize(), + }))); #pragma warning restore LAA1002 } } diff --git a/.Lib9c.Tests/Model/State/RankingStateTest.cs b/.Lib9c.Tests/Model/State/RankingStateTest.cs index 36f02b1e9e..062796b5ca 100644 --- a/.Lib9c.Tests/Model/State/RankingStateTest.cs +++ b/.Lib9c.Tests/Model/State/RankingStateTest.cs @@ -98,8 +98,9 @@ public void UpdateRankingMapThrowRankingExceededException() state.UpdateRankingMap(address.Derive(i.ToString())); } - var exec = Assert.Throws(() => - state.UpdateRankingMap(address.Derive((max + 1).ToString()))); + var exec = Assert.Throws( + () => + state.UpdateRankingMap(address.Derive((max + 1).ToString()))); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); @@ -113,18 +114,23 @@ public void UpdateRankingMapThrowRankingExceededException() private static IValue SerializeV1_With_Deterministic_Problem(RankingState rankingState) { #pragma warning disable LAA1002 - return new Dictionary(new Dictionary - { - [(Text)"ranking_map"] = new Dictionary(rankingState.RankingMap.Select(kv => - new KeyValuePair( - (Binary)kv.Key.Serialize(), - new List(kv.Value.Select(a => a.Serialize())) - ) - )), - }.Union(new Dictionary(new Dictionary - { - [(Text)LegacyAddressKey] = rankingState.address.Serialize(), - }))); + return new Dictionary( + new Dictionary + { + [(Text)"ranking_map"] = new Dictionary( + rankingState.RankingMap.Select( + kv => + new KeyValuePair( + (Binary)kv.Key.Serialize(), + new List(kv.Value.Select(a => a.Serialize())) + ) + )), + }.Union( + new Dictionary( + new Dictionary + { + [(Text)LegacyAddressKey] = rankingState.address.Serialize(), + }))); #pragma warning restore LAA1002 } } diff --git a/.Lib9c.Tests/Model/State/ShopStateTest.cs b/.Lib9c.Tests/Model/State/ShopStateTest.cs index bc27bb9180..0f7027ebd7 100644 --- a/.Lib9c.Tests/Model/State/ShopStateTest.cs +++ b/.Lib9c.Tests/Model/State/ShopStateTest.cs @@ -19,10 +19,11 @@ public void Serialization() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), @@ -55,10 +56,11 @@ public void Register() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), @@ -89,10 +91,11 @@ public void RegisterThrowShopStateAlreadyContainsException() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), @@ -121,10 +124,11 @@ public void Unregister() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), @@ -145,8 +149,9 @@ public void Unregister() Assert.Equal(0, shopState.Products.Count); - Assert.Throws(() => - shopState.Unregister(shopItem)); + Assert.Throws( + () => + shopState.Unregister(shopItem)); } [Fact] @@ -157,10 +162,11 @@ public void TryUnregister() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), @@ -178,15 +184,17 @@ public void TryUnregister() shopState.Register(shopItem); - Assert.True(shopState.TryUnregister( - shopItem.ProductId, - out var unregisteredItem)); + Assert.True( + shopState.TryUnregister( + shopItem.ProductId, + out var unregisteredItem)); Assert.Equal(shopItem, unregisteredItem); Assert.Equal(0, shopState.Products.Count); - Assert.Throws(() => - shopState.Unregister(shopItem)); + Assert.Throws( + () => + shopState.Unregister(shopItem)); } [Fact] @@ -197,10 +205,11 @@ public void TryGet() var avatarAddress = new PrivateKey().Address; var productId = Guid.NewGuid(); var weaponRow = new EquipmentItemSheet.Row(); - weaponRow.Set(new[] - { - "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", - }); + weaponRow.Set( + new[] + { + "10100000", "Weapon", "0", "Normal", "0", "ATK", "1", "2", "10100000", + }); var itemUsable = new Weapon( weaponRow, Guid.NewGuid(), diff --git a/.Lib9c.Tests/Model/State/StakeStateTest.cs b/.Lib9c.Tests/Model/State/StakeStateTest.cs index 82cb4366ef..99bcaf60f8 100644 --- a/.Lib9c.Tests/Model/State/StakeStateTest.cs +++ b/.Lib9c.Tests/Model/State/StakeStateTest.cs @@ -13,20 +13,22 @@ public class StakeStateTest [Fact] public void IsClaimable() { - Assert.False(new StakeState( - default, - 0, - RewardInterval + 1, - LockupInterval, - new StakeAchievements()) - .IsClaimable(RewardInterval * 2)); - Assert.True(new StakeState( - default, - ActionObsoleteConfig.V100290ObsoleteIndex - 100, - ActionObsoleteConfig.V100290ObsoleteIndex - 100 + RewardInterval + 1, - ActionObsoleteConfig.V100290ObsoleteIndex - 100 + LockupInterval, - new StakeAchievements()) - .IsClaimable(ActionObsoleteConfig.V100290ObsoleteIndex - 100 + RewardInterval * 2)); + Assert.False( + new StakeState( + default, + 0, + RewardInterval + 1, + LockupInterval, + new StakeAchievements()) + .IsClaimable(RewardInterval * 2)); + Assert.True( + new StakeState( + default, + ActionObsoleteConfig.V100290ObsoleteIndex - 100, + ActionObsoleteConfig.V100290ObsoleteIndex - 100 + RewardInterval + 1, + ActionObsoleteConfig.V100290ObsoleteIndex - 100 + LockupInterval, + new StakeAchievements()) + .IsClaimable(ActionObsoleteConfig.V100290ObsoleteIndex - 100 + RewardInterval * 2)); } [Fact] diff --git a/.Lib9c.Tests/Model/State/WeeklyArenaStateTest.cs b/.Lib9c.Tests/Model/State/WeeklyArenaStateTest.cs index 6d83c8cadb..ddfe109d36 100644 --- a/.Lib9c.Tests/Model/State/WeeklyArenaStateTest.cs +++ b/.Lib9c.Tests/Model/State/WeeklyArenaStateTest.cs @@ -69,11 +69,12 @@ public void SerializeWithDotNetAPI() public void ArenaInfoGetRewardCount(int minScore, int maxScore, int expected) { var score = new Random().Next(minScore, maxScore); - var serialized = new Dictionary(new Dictionary - { - [(Text)"score"] = score.Serialize(), - [(Text)"receive"] = false.Serialize(), - }); + var serialized = new Dictionary( + new Dictionary + { + [(Text)"score"] = score.Serialize(), + [(Text)"receive"] = false.Serialize(), + }); var info = new ArenaInfo(serialized); Assert.Equal(expected, info.GetRewardCount()); } @@ -143,8 +144,9 @@ public void GetArenaInfosByFirstRankAndCountThrow(int infoCount, int firstRank) new ArenaInfo(avatarState, characterSheet, new CostumeStatSheet(), true)); } - Assert.Throws(() => - weeklyArenaState.GetArenaInfos(firstRank, 100)); + Assert.Throws( + () => + weeklyArenaState.GetArenaInfos(firstRank, 100)); } [Theory] diff --git a/.Lib9c.Tests/Policy/BlockPolicyTest.cs b/.Lib9c.Tests/Policy/BlockPolicyTest.cs index 539cc75b30..8523a63611 100644 --- a/.Lib9c.Tests/Policy/BlockPolicyTest.cs +++ b/.Lib9c.Tests/Policy/BlockPolicyTest.cs @@ -195,7 +195,7 @@ public void MustNotIncludeBlockActionAtTransaction() var adminAddress = adminPrivateKey.Address; var authorizedMinerPrivateKey = new PrivateKey(); - (var ak, var ps) = ActivationKey.Create( + var (ak, ps) = ActivationKey.Create( new PrivateKey(), new byte[] { 0x00, 0x01, } ); @@ -235,9 +235,11 @@ public void MustNotIncludeBlockActionAtTransaction() ); var unloadableAction = blockChain.MakeTransaction( - adminPrivateKey, new ActionBase[] { new RewardGold(), }).Actions[0]; - Assert.Throws(() => - actionLoader.LoadAction(blockChain.Tip.Index, unloadableAction)); + adminPrivateKey, + new ActionBase[] { new RewardGold(), }).Actions[0]; + Assert.Throws( + () => + actionLoader.LoadAction(blockChain.Tip.Index, unloadableAction)); } [Fact] @@ -247,7 +249,7 @@ public void EarnMiningGoldWhenSuccessMining() var adminAddress = adminPrivateKey.Address; var authorizedMinerPrivateKey = new PrivateKey(); - (var ak, var ps) = ActivationKey.Create( + var (ak, ps) = ActivationKey.Create( new PrivateKey(), new byte[] { 0x00, 0x01, } ); @@ -345,14 +347,15 @@ List GenerateTransactions(int count) var list = new List(); for (var i = 0; i < count; i++) { - list.Add(Transaction.Create( - nonce++, - adminPrivateKey, - genesis.Hash, - Array.Empty(), - gasLimit: 1, - maxGasPrice: new FungibleAssetValue(Currencies.Mead, 0, 0) - )); + list.Add( + Transaction.Create( + nonce++, + adminPrivateKey, + genesis.Hash, + Array.Empty(), + gasLimit: 1, + maxGasPrice: new FungibleAssetValue(Currencies.Mead, 0, 0) + )); } return list; @@ -460,14 +463,15 @@ List GenerateTransactions(int count) var list = new List(); for (var i = 0; i < count; i++) { - list.Add(Transaction.Create( - nonce++, - adminPrivateKey, - genesis.Hash, - Array.Empty(), - gasLimit: 1, - maxGasPrice: new FungibleAssetValue(Currencies.Mead, 0, 0) - )); + list.Add( + Transaction.Create( + nonce++, + adminPrivateKey, + genesis.Hash, + Array.Empty(), + gasLimit: 1, + maxGasPrice: new FungibleAssetValue(Currencies.Mead, 0, 0) + )); } return list; @@ -545,14 +549,15 @@ private BlockCommit GenerateBlockCommit(Block block, PrivateKey key) block.Index, 0, block.Hash, - ImmutableArray.Empty.Add(new VoteMetadata( - block.Index, - 0, - block.Hash, - DateTimeOffset.UtcNow, - privateKey.PublicKey, - null, - VoteFlag.PreCommit).Sign(privateKey))) + ImmutableArray.Empty.Add( + new VoteMetadata( + block.Index, + 0, + block.Hash, + DateTimeOffset.UtcNow, + privateKey.PublicKey, + null, + VoteFlag.PreCommit).Sign(privateKey))) : null; } @@ -569,7 +574,7 @@ private Block MakeGenesisBlock( if (pendingActivations is null) { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(_privateKey, nonce); pendingActivations = new[] { pendingActivation, }; } diff --git a/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs b/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs index 023194c9ef..c5600acd98 100644 --- a/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs +++ b/.Lib9c.Tests/Policy/ConcreteSubPolicyTest.cs @@ -59,22 +59,25 @@ public void Constructor() Assert.Equal(19, genericSubPolicy.SpannedSubPolicies.First().EndIndex); // Out of order addition should not work. - Assert.Throws(() => ConcreteSubPolicy - .Create(false) - .Add(fourth) - .Add(third)); - Assert.Throws(() => ConcreteSubPolicy - .Create(false) - .Add(first) - .Add(badSecond)); + Assert.Throws( + () => ConcreteSubPolicy + .Create(false) + .Add(fourth) + .Add(third)); + Assert.Throws( + () => ConcreteSubPolicy + .Create(false) + .Add(first) + .Add(badSecond)); // Create using AddRange(). genericSubPolicy = ConcreteSubPolicy .Create(false) .AddRange(new List>() { first, second, third, fourth, }.ToImmutableList()); - Assert.Throws(() => ConcreteSubPolicy - .Create(false) - .AddRange(new List>() { second, first, }.ToImmutableList())); + Assert.Throws( + () => ConcreteSubPolicy + .Create(false) + .AddRange(new List>() { second, first, }.ToImmutableList())); // Type check Assert.IsType>(genericSubPolicy); diff --git a/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs b/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs index d544ec2d85..15fa485249 100644 --- a/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs +++ b/.Lib9c.Tests/Policy/SpannedSubPolicyTest.cs @@ -19,32 +19,51 @@ public void Constructor() var indices = Enumerable.Range(0, 100).Select(i => (long)i).ToList(); // Bad start index - Assert.Throws(() => - new SpannedSubPolicy(-1, null, null, 1)); + Assert.Throws( + () => + new SpannedSubPolicy(-1, null, null, 1)); // Bad end index - Assert.Throws(() => - new SpannedSubPolicy(10, 9, null, 1)); + Assert.Throws( + () => + new SpannedSubPolicy(10, 9, null, 1)); // Same start index and end index should be fine spannedSubPolicy = new SpannedSubPolicy(10, 10, null, 1); // Count indices in range - Assert.Equal(11, indices.Where(i => - new SpannedSubPolicy(10, 20, index => index % 30 == 0, 1).IsTargetRange(i)).Count()); + Assert.Equal( + 11, + indices.Where( + i => + new SpannedSubPolicy(10, 20, index => index % 30 == 0, 1).IsTargetRange(i)).Count()); // No index in range satisfies predicate - Assert.False(indices.Where(i => - new SpannedSubPolicy(10, 20, index => index % 30 == 0, 1).IsTargetIndex(i)).Any()); + Assert.False( + indices.Where( + i => + new SpannedSubPolicy(10, 20, index => index % 30 == 0, 1).IsTargetIndex(i)).Any()); // Predicate of null counts everything in range - Assert.Equal(11, indices.Where(i => - new SpannedSubPolicy(10, 20, null, 1).IsTargetIndex(i)).Count()); + Assert.Equal( + 11, + indices.Where( + i => + new SpannedSubPolicy(10, 20, null, 1).IsTargetIndex(i)).Count()); // Count target indices - Assert.Equal(3, indices.Where(i => - new SpannedSubPolicy(10, 20, index => index % 5 == 0, 1).IsTargetIndex(i)).Count()); + Assert.Equal( + 3, + indices.Where( + i => + new SpannedSubPolicy(10, 20, index => index % 5 == 0, 1).IsTargetIndex(i)).Count()); // Count indices in range for indefinite case - Assert.Equal(90, indices.Where(i => - new SpannedSubPolicy(10, null, index => index % 5 == 0, 1).IsTargetRange(i)).Count()); + Assert.Equal( + 90, + indices.Where( + i => + new SpannedSubPolicy(10, null, index => index % 5 == 0, 1).IsTargetRange(i)).Count()); // Count target indices for indefinite case - Assert.Equal(18, indices.Where(i => - new SpannedSubPolicy(10, null, index => index % 5 == 0, 1).IsTargetIndex(i)).Count()); + Assert.Equal( + 18, + indices.Where( + i => + new SpannedSubPolicy(10, null, index => index % 5 == 0, 1).IsTargetIndex(i)).Count()); } } } diff --git a/.Lib9c.Tests/PolicyAction/Tx/Begin/AutoJoinGuildTest.cs b/.Lib9c.Tests/PolicyAction/Tx/Begin/AutoJoinGuildTest.cs index d88fca8fde..a67a1165f3 100644 --- a/.Lib9c.Tests/PolicyAction/Tx/Begin/AutoJoinGuildTest.cs +++ b/.Lib9c.Tests/PolicyAction/Tx/Begin/AutoJoinGuildTest.cs @@ -22,11 +22,12 @@ public class AutoJoinGuildTest [Fact] public void RunAsPolicyActionOnly() { - Assert.Throws(() => new AutoJoinGuild().Execute( - new ActionContext - { - IsPolicyAction = false, - })); + Assert.Throws( + () => new AutoJoinGuild().Execute( + new ActionContext + { + IsPolicyAction = false, + })); } [Fact] @@ -39,19 +40,22 @@ public void Execute_When_WithPledgeContract() var world = new World(MockUtil.MockModernWorldState) .MakeGuild(guildAddress, guildMasterAddress) .JoinGuild(guildAddress, guildMasterAddress) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(agentAddress)); var action = new AutoJoinGuild(); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - IsPolicyAction = true, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + IsPolicyAction = true, + }); var joinedGuildAddress = Assert.IsType(world.GetJoinedGuild(agentAddress)); Assert.True(world.TryGetGuild(joinedGuildAddress, out var guild)); @@ -70,12 +74,13 @@ public void Execute_When_WithoutPledgeContract() Assert.Null(world.GetJoinedGuild(agentAddress)); var action = new AutoJoinGuild(); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - IsPolicyAction = true, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + IsPolicyAction = true, + }); Assert.Null(world.GetJoinedGuild(agentAddress)); } @@ -86,19 +91,22 @@ public void Execute_When_WithoutGuildYet() var agentAddress = AddressUtil.CreateAgentAddress(); var pledgeAddress = agentAddress.GetPledgeAddress(); var world = new World(MockUtil.MockModernWorldState) - .SetLegacyState(pledgeAddress, new List( - MeadConfig.PatronAddress.Serialize(), - true.Serialize(), - RequestPledge.DefaultRefillMead.Serialize())); + .SetLegacyState( + pledgeAddress, + new List( + MeadConfig.PatronAddress.Serialize(), + true.Serialize(), + RequestPledge.DefaultRefillMead.Serialize())); Assert.Null(world.GetJoinedGuild(agentAddress)); var action = new AutoJoinGuild(); - world = action.Execute(new ActionContext - { - PreviousState = world, - Signer = agentAddress, - IsPolicyAction = true, - }); + world = action.Execute( + new ActionContext + { + PreviousState = world, + Signer = agentAddress, + IsPolicyAction = true, + }); Assert.Null(world.GetJoinedGuild(agentAddress)); } diff --git a/.Lib9c.Tests/SerializeKeysTest.cs b/.Lib9c.Tests/SerializeKeysTest.cs index 92afed63ad..fa0101c615 100644 --- a/.Lib9c.Tests/SerializeKeysTest.cs +++ b/.Lib9c.Tests/SerializeKeysTest.cs @@ -12,7 +12,8 @@ public class SerializeKeysTest public void Keys_Duplicate() { var type = typeof(SerializeKeys); - var fields = type.GetFields(BindingFlags.Public + var fields = type.GetFields( + BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); var keyMap = new Dictionary(); diff --git a/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossContributionRewardSheetTest.cs b/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossContributionRewardSheetTest.cs index 30d1c8f8b2..63ae375d04 100644 --- a/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossContributionRewardSheetTest.cs +++ b/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossContributionRewardSheetTest.cs @@ -9,16 +9,20 @@ public class AdventureBossContributionRewardSheetTest [Theory] [InlineData( @"id,adventure_boss_id,reward_1_type,reward_1_id,reward_1_ratio,reward_2_type,reward_2_id,reward_2_ratio,reward_3_type,reward_3_id,reward_3_ratio,reward_4_type,reward_4_id,reward_4_ratio -1,1,Material,600201,5,,,,,,,,,", 1)] +1,1,Material,600201,5,,,,,,,,,", + 1)] [InlineData( @"id,adventure_boss_id,reward_1_type,reward_1_id,reward_1_ratio,reward_2_type,reward_2_id,reward_2_ratio,reward_3_type,reward_3_id,reward_3_ratio,reward_4_type,reward_4_id,reward_4_ratio -1,1,Material,600201,5,Rune,30001,5,,,,,,", 2)] +1,1,Material,600201,5,Rune,30001,5,,,,,,", + 2)] [InlineData( @"id,adventure_boss_id,reward_1_type,reward_1_id,reward_1_ratio,reward_2_type,reward_2_id,reward_2_ratio,reward_3_type,reward_3_id,reward_3_ratio,reward_4_type,reward_4_id,reward_4_ratio -1,1,Material,600201,5,Rune,30001,5,Material,600202,5,,,", 3)] +1,1,Material,600201,5,Rune,30001,5,Material,600202,5,,,", + 3)] [InlineData( @"id,adventure_boss_id,reward_1_type,reward_1_id,reward_1_ratio,reward_2_type,reward_2_id,reward_2_ratio,reward_3_type,reward_3_id,reward_3_ratio,reward_4_type,reward_4_id,reward_4_ratio -1,1,Material,600201,5,Rune,30001,5,Material,600202,5,Rune,20001,5", 4)] +1,1,Material,600201,5,Rune,30001,5,Material,600202,5,Rune,20001,5", + 4)] public void Set(string csv, int expectedRewardCount) { var sheet = new AdventureBossContributionRewardSheet(); diff --git a/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossWantedRewardSheetTest.cs b/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossWantedRewardSheetTest.cs index f6c58530a8..f7d9d3cba1 100644 --- a/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossWantedRewardSheetTest.cs +++ b/.Lib9c.Tests/TableData/AdventureBoss/AdventureBossWantedRewardSheetTest.cs @@ -9,16 +9,20 @@ public class AdventureBossWantedRewardSheetTest [Theory] [InlineData( @"id,adventure_boss_id,fixed_type,fixed_id,random_1_type,random_1_id,random_1_ratio,random_2_type,random_2_id,random_2_ratio,random_3_type,random_3_id,random_3_ratio,random_4_type,random_4_id,random_4_ratio -1,1,Material,600201,Rune,30001,50,,,,,,,,,", 1)] +1,1,Material,600201,Rune,30001,50,,,,,,,,,", + 1)] [InlineData( @"id,adventure_boss_id,fixed_type,fixed_id,random_1_type,random_1_id,random_1_ratio,random_2_type,random_2_id,random_2_ratio,random_3_type,random_3_id,random_3_ratio,random_4_type,random_4_id,random_4_ratio -1,1,Material,600201,Rune,30001,50,Material,600201,60,,,,,,", 2)] +1,1,Material,600201,Rune,30001,50,Material,600201,60,,,,,,", + 2)] [InlineData( @"id,adventure_boss_id,fixed_type,fixed_id,random_1_type,random_1_id,random_1_ratio,random_2_type,random_2_id,random_2_ratio,random_3_type,random_3_id,random_3_ratio,random_4_type,random_4_id,random_4_ratio -1,1,Material,600201,Rune,30001,50,Material,600201,60,Rune,20001,40,,,", 3)] +1,1,Material,600201,Rune,30001,50,Material,600201,60,Rune,20001,40,,,", + 3)] [InlineData( @"id,adventure_boss_id,fixed_type,fixed_id,random_1_type,random_1_id,random_1_ratio,random_2_type,random_2_id,random_2_ratio,random_3_type,random_3_id,random_3_ratio,random_4_type,random_4_id,random_4_ratio -1,1,Material,600201,Rune,30001,50,Material,600201,60,Rune,20001,40,Material,600202,40", 4)] +1,1,Material,600201,Rune,30001,50,Material,600201,60,Rune,20001,40,Material,600202,40", + 4)] public void Set(string csv, int expectedRandomRewardCount) { var sheet = new AdventureBossWantedRewardSheet(); diff --git a/.Lib9c.Tests/TableData/ArenaSheetTest.cs b/.Lib9c.Tests/TableData/ArenaSheetTest.cs index cf805b22f8..152d63f745 100644 --- a/.Lib9c.Tests/TableData/ArenaSheetTest.cs +++ b/.Lib9c.Tests/TableData/ArenaSheetTest.cs @@ -180,8 +180,9 @@ public void GetRowByBlockIndexTest() var lastRound = _arenaSheet.OrderedList[^1].Round[^1]; blockIndex = lastRound.EndBlockIndex + 1; - Assert.Throws(() => - _arenaSheet.GetRowByBlockIndex(blockIndex)); + Assert.Throws( + () => + _arenaSheet.GetRowByBlockIndex(blockIndex)); } [Fact] @@ -205,8 +206,9 @@ public void GetRoundByBlockIndexTest() var lastRound = _arenaSheet.OrderedList[^1].Round[^1]; blockIndex = lastRound.EndBlockIndex + 1; - Assert.Throws(() => - _arenaSheet.GetRoundByBlockIndex(blockIndex)); + Assert.Throws( + () => + _arenaSheet.GetRoundByBlockIndex(blockIndex)); } } } diff --git a/.Lib9c.Tests/TableData/Crystal/CrystalMaterialCostSheetTest.cs b/.Lib9c.Tests/TableData/Crystal/CrystalMaterialCostSheetTest.cs index 785f08aaed..399cd67503 100644 --- a/.Lib9c.Tests/TableData/Crystal/CrystalMaterialCostSheetTest.cs +++ b/.Lib9c.Tests/TableData/Crystal/CrystalMaterialCostSheetTest.cs @@ -18,7 +18,8 @@ public void Constructor() public void Set() { var sheet = new CrystalMaterialCostSheet(); - sheet.Set(@"item_id,crystal + sheet.Set( + @"item_id,crystal 301000,100"); Assert.Single(sheet.Values); diff --git a/.Lib9c.Tests/TableData/Crystal/CrystalRandomBuffSheetTest.cs b/.Lib9c.Tests/TableData/Crystal/CrystalRandomBuffSheetTest.cs index 66641840a1..e463e70783 100644 --- a/.Lib9c.Tests/TableData/Crystal/CrystalRandomBuffSheetTest.cs +++ b/.Lib9c.Tests/TableData/Crystal/CrystalRandomBuffSheetTest.cs @@ -18,7 +18,8 @@ public void Constructor() public void Set() { var sheet = new CrystalRandomBuffSheet(); - sheet.Set(@"id,rank,skill_id,ratio + sheet.Set( + @"id,rank,skill_id,ratio 1,SS,400000,0.11"); Assert.Single(sheet.Values); diff --git a/.Lib9c.Tests/TableData/Crystal/CrystalStageBuffGachaSheetTest.cs b/.Lib9c.Tests/TableData/Crystal/CrystalStageBuffGachaSheetTest.cs index adbcd127ed..b897065c69 100644 --- a/.Lib9c.Tests/TableData/Crystal/CrystalStageBuffGachaSheetTest.cs +++ b/.Lib9c.Tests/TableData/Crystal/CrystalStageBuffGachaSheetTest.cs @@ -18,7 +18,8 @@ public void Constructor() public void Set() { var sheet = new CrystalStageBuffGachaSheet(); - sheet.Set(@"stage_id,max_star,normal_cost,advanced_cost + sheet.Set( + @"stage_id,max_star,normal_cost,advanced_cost 1,5,10,30"); Assert.Single(sheet.Values); diff --git a/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs b/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs index 8b0b89b8be..82705de5a7 100644 --- a/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs +++ b/.Lib9c.Tests/TableData/Garages/LoadIntoMyGaragesCostSheetTest.cs @@ -203,16 +203,18 @@ public void GetGarageCost() { var currency = Currencies.GetMinterlessCurrency("RUNE_GOLDENLEAF"); var favTuples = Enumerable.Range(1, 10) - .Select(i => ( - fav: new FungibleAssetValue(currency, i, 0), - expect: i * 10m)) + .Select( + i => ( + fav: new FungibleAssetValue(currency, i, 0), + expect: i * 10m)) .ToArray(); var fungibleIdAndCountTuples = Enumerable.Range(1, 10) - .Select(i => ( - fungibleId: HashDigest.FromString( - "00dfffe23964af9b284d121dae476571b7836b8d9e2e5f510d92a840fecc64fe"), - count: i, - expect: i * 0.16m)) + .Select( + i => ( + fungibleId: HashDigest.FromString( + "00dfffe23964af9b284d121dae476571b7836b8d9e2e5f510d92a840fecc64fe"), + count: i, + expect: i * 0.16m)) .ToArray(); var expect = favTuples.Select(t => t.expect).Sum() + fungibleIdAndCountTuples.Select(t => t.expect).Sum(); diff --git a/.Lib9c.Tests/TableData/Stake/StakePolicySheetTest.cs b/.Lib9c.Tests/TableData/Stake/StakePolicySheetTest.cs index 9b38014b9e..410b274f3a 100644 --- a/.Lib9c.Tests/TableData/Stake/StakePolicySheetTest.cs +++ b/.Lib9c.Tests/TableData/Stake/StakePolicySheetTest.cs @@ -38,8 +38,9 @@ public void Set_Throw_SheetRowValidateException(string row) var sb = new StringBuilder(); sb.AppendLine("attr_name,value"); sb.AppendLine(row); - Assert.Throws(() => - new StakePolicySheet().Set(sb.ToString())); + Assert.Throws( + () => + new StakePolicySheet().Set(sb.ToString())); } [Fact] diff --git a/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs b/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs index 6be19aab92..a700c1bcf1 100644 --- a/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs +++ b/.Lib9c.Tests/TableData/WorldAndStage/WorldUnlockSheetTest.cs @@ -8,10 +8,12 @@ public class WorldUnlockSheetTest [Theory] [InlineData( @"id,world_id,stage_id,world_id_to_unlock -1,1,50,2", 0)] +1,1,50,2", + 0)] [InlineData( @"id,world_id,stage_id,world_id_to_unlock,required_crystal -1,1,50,2,500", 500)] +1,1,50,2,500", + 500)] public void Set(string csv, int expected) { var sheet = new WorldUnlockSheet(); diff --git a/.Lib9c.Tests/TableData/WorldBossListSheetTest.cs b/.Lib9c.Tests/TableData/WorldBossListSheetTest.cs index 36ceeda8a8..23f9d34864 100644 --- a/.Lib9c.Tests/TableData/WorldBossListSheetTest.cs +++ b/.Lib9c.Tests/TableData/WorldBossListSheetTest.cs @@ -51,8 +51,9 @@ public void FindPreviousRaidIdByBlockIndex() Assert.Equal(1, sheet.FindPreviousRaidIdByBlockIndex(150)); Assert.Equal(2, sheet.FindPreviousRaidIdByBlockIndex(350)); - Assert.Throws(() => - sheet.FindPreviousRaidIdByBlockIndex(100)); + Assert.Throws( + () => + sheet.FindPreviousRaidIdByBlockIndex(100)); } } } diff --git a/.Lib9c.Tests/TestHelper/BencodexHelper.cs b/.Lib9c.Tests/TestHelper/BencodexHelper.cs index 227afac5bb..797b09c363 100644 --- a/.Lib9c.Tests/TestHelper/BencodexHelper.cs +++ b/.Lib9c.Tests/TestHelper/BencodexHelper.cs @@ -43,8 +43,9 @@ public static void AssertEquals(IValue expected, IValue actual) var diff = string.Join( Environment.NewLine, - diffModel.Lines.Select(line => - (prefixes.TryGetValue(line.Type, out var prefix) ? prefix : " ") + line.Text + diffModel.Lines.Select( + line => + (prefixes.TryGetValue(line.Type, out var prefix) ? prefix : " ") + line.Text ) ); throw new XunitException( diff --git a/.Lib9c.Tests/TestHelper/BlockChainHelper.cs b/.Lib9c.Tests/TestHelper/BlockChainHelper.cs index 663d761e92..bb36ab426c 100644 --- a/.Lib9c.Tests/TestHelper/BlockChainHelper.cs +++ b/.Lib9c.Tests/TestHelper/BlockChainHelper.cs @@ -67,7 +67,7 @@ public static Block MakeGenesisBlock( if (pendingActivations is null) { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03, }; - (var activationKey, var pendingActivation) = + var (activationKey, pendingActivation) = ActivationKey.Create(privateKey, nonce); pendingActivations = new[] { pendingActivation, }; } @@ -151,12 +151,13 @@ public static MakeInitialStateResult MakeInitialState() { weeklyArenaAddress = weeklyArenaAddress, }; - var nextState = action.Execute(new ActionContext() - { - BlockIndex = 0, - PreviousState = initialState, - RandomSeed = 0, - }); + var nextState = action.Execute( + new ActionContext() + { + BlockIndex = 0, + PreviousState = initialState, + RandomSeed = 0, + }); return new MakeInitialStateResult( nextState, diff --git a/.Lib9c.Tests/Types/BencodexTypesListTest.cs b/.Lib9c.Tests/Types/BencodexTypesListTest.cs index a688476d84..28e6cf69c1 100644 --- a/.Lib9c.Tests/Types/BencodexTypesListTest.cs +++ b/.Lib9c.Tests/Types/BencodexTypesListTest.cs @@ -18,22 +18,24 @@ public class BencodexTypesListTest public BencodexTypesListTest() { - _integerList = new Bencodex.Types.List(new List - { - 1.Serialize(), - 2.Serialize(), - 3.Serialize(), - }); + _integerList = new Bencodex.Types.List( + new List + { + 1.Serialize(), + 2.Serialize(), + 3.Serialize(), + }); _descendingIntegerList = (Bencodex.Types.List)_integerList .OrderByDescending(element => element.ToInteger()) .Serialize(); - _addressList = new Bencodex.Types.List(new List - { - new PrivateKey().Address.Serialize(), - new PrivateKey().Address.Serialize(), - new PrivateKey().Address.Serialize(), - }); + _addressList = new Bencodex.Types.List( + new List + { + new PrivateKey().Address.Serialize(), + new PrivateKey().Address.Serialize(), + new PrivateKey().Address.Serialize(), + }); _descendingAddressList = (Bencodex.Types.List)_addressList .OrderByDescending(element => element.ToAddress()) .Serialize(); From e12badfb76f42ecd127ed592819eddfd042dc11b Mon Sep 17 00:00:00 2001 From: eugene-hong <58686228+eugene-doobu@users.noreply.github.com> Date: Tue, 22 Oct 2024 11:54:22 +0900 Subject: [PATCH 3/3] sorting namespace order --- .Lib9c.Tests/Action/JoinArenaTest.cs | 2 +- .Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.Lib9c.Tests/Action/JoinArenaTest.cs b/.Lib9c.Tests/Action/JoinArenaTest.cs index 04d3d9f672..34ed4dc2fb 100644 --- a/.Lib9c.Tests/Action/JoinArenaTest.cs +++ b/.Lib9c.Tests/Action/JoinArenaTest.cs @@ -4,10 +4,10 @@ namespace Lib9c.Tests.Action using System.Collections.Generic; using System.Linq; using Bencodex.Types; + using Lib9c.Tests.Util; using Libplanet.Action.State; using Libplanet.Crypto; using Libplanet.Types.Assets; - using Lib9c.Tests.Util; using Nekoyume.Action; using Nekoyume.Arena; using Nekoyume.Model.Arena; diff --git a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs index 591721ee51..f348dba12b 100644 --- a/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs +++ b/.Lib9c.Tests/Model/Mail/CustomCraftMailTest.cs @@ -3,11 +3,11 @@ namespace Lib9c.Tests.Model.Mail using System; using System.Collections.Generic; using Bencodex.Types; + using Libplanet.Types.Assets; using Nekoyume.Model.Item; using Nekoyume.Model.Mail; using Nekoyume.TableData; using Xunit; - using Libplanet.Types.Assets; public class CustomCraftMailTest {