From ac364f4791172633eeb2dbd4f514c9bb710bb004 Mon Sep 17 00:00:00 2001 From: s2quake Date: Thu, 19 Dec 2024 10:40:56 +0900 Subject: [PATCH] refactor: Remove migration-related test code(except for MigrateDelegationHeight) --- .../Actions/MigrateDelegation.cs | 128 ----- .../FixToRefundFromNonValidatorTest.cs | 81 --- .../Guild/Migration/MigrateDelegationTest.cs | 122 ----- .../Migration/MigratePlanetariumGuildTest.cs | 65 --- .../MigratePlanetariumValidatorTest.cs | 116 ----- .../Migration/LegacyTestDelegatee.cs | 471 ------------------ .../Migration/LegacyTestDelegator.cs | 228 --------- .../Migration/RewardBaseMigrationTest.cs | 138 ----- .../Migration/FixToRefundFromNonValidator.cs | 98 ---- .../GuildMigrationFailedException.cs | 14 - .../Migration/LegacyModels/LegacyGuild.cs | 64 --- .../LegacyModels/LegacyGuildParticipant.cs | 64 --- .../Guild/Migration/MigrateDelegation.cs | 149 ------ .../Migration/MigratePlanetariumGuild.cs | 83 --- .../Migration/MigratePlanetariumValidator.cs | 85 ---- .../lib9c/src/actions/migrate_delegation.ts | 25 - .../src/actions/migrate_planetarium_guild.ts | 10 - .../@planetarium/lib9c/src/index.ts | 5 - 18 files changed, 1946 deletions(-) delete mode 100644 .Lib9c.Benchmarks/Actions/MigrateDelegation.cs delete mode 100644 .Lib9c.Tests/Action/Guild/Migration/FixToRefundFromNonValidatorTest.cs delete mode 100644 .Lib9c.Tests/Action/Guild/Migration/MigrateDelegationTest.cs delete mode 100644 .Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumGuildTest.cs delete mode 100644 .Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumValidatorTest.cs delete mode 100644 .Lib9c.Tests/Delegation/Migration/LegacyTestDelegatee.cs delete mode 100644 .Lib9c.Tests/Delegation/Migration/LegacyTestDelegator.cs delete mode 100644 .Lib9c.Tests/Delegation/Migration/RewardBaseMigrationTest.cs delete mode 100644 Lib9c/Action/Guild/Migration/FixToRefundFromNonValidator.cs delete mode 100644 Lib9c/Action/Guild/Migration/GuildMigrationFailedException.cs delete mode 100644 Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuild.cs delete mode 100644 Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuildParticipant.cs delete mode 100644 Lib9c/Action/Guild/Migration/MigrateDelegation.cs delete mode 100644 Lib9c/Action/Guild/Migration/MigratePlanetariumGuild.cs delete mode 100644 Lib9c/Action/Guild/Migration/MigratePlanetariumValidator.cs delete mode 100644 integrations/javascript/@planetarium/lib9c/src/actions/migrate_delegation.ts delete mode 100644 integrations/javascript/@planetarium/lib9c/src/actions/migrate_planetarium_guild.ts diff --git a/.Lib9c.Benchmarks/Actions/MigrateDelegation.cs b/.Lib9c.Benchmarks/Actions/MigrateDelegation.cs deleted file mode 100644 index 01610e9d14..0000000000 --- a/.Lib9c.Benchmarks/Actions/MigrateDelegation.cs +++ /dev/null @@ -1,128 +0,0 @@ -using BenchmarkDotNet.Attributes; -using Bencodex.Types; -using Lib9c.Tests.Action; -using Lib9c.Tests.Util; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Libplanet.Mocks; -using Nekoyume; -using Nekoyume.Action.Guild; -using Nekoyume.Action.Guild.Migration; -using Nekoyume.Action.Guild.Migration.LegacyModels; -using Nekoyume.Extensions; -using Nekoyume.TypedAddress; - -namespace Lib9c.Benchmarks.Actions; - -public class MigrateDelegation -{ - private GuildAddress planetariumGuild = AddressUtil.CreateGuildAddress(); - private AgentAddress target = AddressUtil.CreateAgentAddress(); - private AgentAddress signer = AddressUtil.CreateAgentAddress(); - private IWorld worldEmpty; - private IWorld worldBeforeGuildMigration; - private IWorld worldBeforeParticipantMigration; - private IWorld worldAfterMigration; - - [GlobalSetup] - public void Setup() - { - worldEmpty = new World(MockUtil.MockModernWorldState); - var legacyPlanetariumGuild = new LegacyGuild(GuildConfig.PlanetariumGuildOwner); - var legacyPlanetariumGuildParticipant = new LegacyGuildParticipant(planetariumGuild); - worldBeforeGuildMigration = worldEmpty - .MutateAccount( - Addresses.Guild, - account => account.SetState(planetariumGuild, legacyPlanetariumGuild.Bencoded)) - .MutateAccount( - Addresses.GuildParticipant, - account => account.SetState(GuildConfig.PlanetariumGuildOwner, legacyPlanetariumGuildParticipant.Bencoded)) - .MutateAccount( - Addresses.GuildParticipant, - account => account.SetState(target, legacyPlanetariumGuildParticipant.Bencoded)) - .MutateAccount( - Addresses.GuildMemberCounter, - account => account.SetState(planetariumGuild, (Integer)2)); - worldBeforeParticipantMigration = new MigratePlanetariumGuild().Execute(new ActionContext - { - PreviousState = worldBeforeGuildMigration, - Signer = new PrivateKey().Address, - }); - } - - [Benchmark] - public void Execute_Empty() - { - var action = new Nekoyume.Action.Guild.Migration.MigrateDelegation(target); - try - { - action.Execute(new ActionContext - { - IsPolicyAction = false, - PreviousState = worldEmpty, - Signer = signer, - }); - } - catch - { - // Do nothing. - } - } - - [Benchmark] - public void Execute_Before_Guild_Migration() - { - var action = new Nekoyume.Action.Guild.Migration.MigrateDelegation(target); - try - { - action.Execute(new ActionContext - { - IsPolicyAction = false, - PreviousState = worldBeforeGuildMigration, - Signer = signer, - }); - } - catch - { - // Do nothing. - } - } - - [Benchmark] - public void Execute_Before_Participant_Migration() - { - var action = new Nekoyume.Action.Guild.Migration.MigrateDelegation(target); - try - { - action.Execute(new ActionContext - { - IsPolicyAction = false, - PreviousState = worldBeforeParticipantMigration, - Signer = signer, - }); - } - catch - { - // Do nothing. - } - } - - [Benchmark] - public void Execute_After_Migration() - { - var action = new Nekoyume.Action.Guild.Migration.MigrateDelegation(target); - try - { - action.Execute(new ActionContext - { - IsPolicyAction = false, - PreviousState = worldAfterMigration, - Signer = signer, - }); - } - catch - { - // Do nothing. - } - } -} diff --git a/.Lib9c.Tests/Action/Guild/Migration/FixToRefundFromNonValidatorTest.cs b/.Lib9c.Tests/Action/Guild/Migration/FixToRefundFromNonValidatorTest.cs deleted file mode 100644 index bf5217d27b..0000000000 --- a/.Lib9c.Tests/Action/Guild/Migration/FixToRefundFromNonValidatorTest.cs +++ /dev/null @@ -1,81 +0,0 @@ -namespace Lib9c.Tests.Action.Guild.Migration -{ - using System; - using System.Linq; - using Libplanet.Action.State; - using Libplanet.Crypto; - using Nekoyume; - using Nekoyume.Action; - using Nekoyume.Action.Guild.Migration; - using Nekoyume.Model.Stake; - using Nekoyume.Model.State; - using Nekoyume.Module; - using Xunit; - - // TODO: Remove this test class after the migration is completed. - public class FixToRefundFromNonValidatorTest : GuildTestBase - { - private IWorld _world; - private Address _adminAddress; - - public FixToRefundFromNonValidatorTest() - { - _adminAddress = new PrivateKey().Address; - var adminState = new AdminState(_adminAddress, 100L); - _world = World - .SetLegacyState(Addresses.Admin, adminState.Serialize()) - .MintAsset(new ActionContext { }, Addresses.NonValidatorDelegatee, Currencies.GuildGold * 500); - } - - [Fact] - public void PlainValue() - { - var targets = Enumerable.Range(0, 5).Select(i => (new PrivateKey().Address, (i + 1) * 10)).ToList(); - var plainValue = new FixToRefundFromNonValidator(targets).PlainValue; - - var recon = new FixToRefundFromNonValidator(); - recon.LoadPlainValue(plainValue); - Assert.Equal(targets, recon.Targets); - } - - [Fact] - public void Execute() - { - var targets = Enumerable.Range(0, 5).Select(i => (new PrivateKey().Address, (i + 1) * 10)).ToList(); - - var world = new FixToRefundFromNonValidator(targets).Execute(new ActionContext - { - PreviousState = _world, - Signer = _adminAddress, - BlockIndex = 2L, - }); - - foreach (var item in targets) - { - Assert.Equal( - Currencies.GuildGold * item.Item2, - world.GetBalance(StakeState.DeriveAddress(item.Item1), Currencies.GuildGold)); - } - - Assert.Equal( - Currencies.GuildGold * (500 - targets.Select(t => t.Item2).Sum()), - world.GetBalance(Addresses.NonValidatorDelegatee, Currencies.GuildGold)); - } - - [Fact] - public void AssertWhenExecutedByNonAdmin() - { - var targets = Enumerable.Range(0, 5).Select(i => (new PrivateKey().Address, (i + 1) * 10)).ToList(); - - Assert.Throws(() => - { - new FixToRefundFromNonValidator(targets).Execute(new ActionContext - { - PreviousState = _world, - Signer = new PrivateKey().Address, - BlockIndex = 2L, - }); - }); - } - } -} diff --git a/.Lib9c.Tests/Action/Guild/Migration/MigrateDelegationTest.cs b/.Lib9c.Tests/Action/Guild/Migration/MigrateDelegationTest.cs deleted file mode 100644 index aa42c37100..0000000000 --- a/.Lib9c.Tests/Action/Guild/Migration/MigrateDelegationTest.cs +++ /dev/null @@ -1,122 +0,0 @@ -namespace Lib9c.Tests.Action.Guild.Migration -{ - using System; - using System.Linq; - using System.Numerics; - using Bencodex.Types; - using Lib9c.Tests.Util; - using Libplanet.Action.State; - using Libplanet.Crypto; - using Nekoyume; - using Nekoyume.Action; - using Nekoyume.Action.Guild; - using Nekoyume.Action.Guild.Migration; - using Nekoyume.Action.Guild.Migration.LegacyModels; - using Nekoyume.Extensions; - using Nekoyume.Model.Guild; - using Nekoyume.TypedAddress; - using Xunit; - - // TODO: Remove this test class after the migration is completed. - public class MigrateDelegationTest : GuildTestBase - { - [Fact] - public void Execute() - { - var guildAddress = AddressUtil.CreateGuildAddress(); - var world = EnsureLegacyPlanetariumGuild(World, guildAddress); - var guildMemberCount = 10; - var migratedGuildMemberCount = 5; - var guildMemberAddresses = Enumerable.Range(0, guildMemberCount).Select( - _ => AddressUtil.CreateAgentAddress()).ToList(); - for (var i = 0; i < guildMemberCount; i++) - { - world = EnsureJoinLegacyPlanetariumGuild(world, guildMemberAddresses[i]); - } - - world = EnsureMigratedPlanetariumGuild(world); - - for (var i = 0; i < migratedGuildMemberCount; i++) - { - var action = new MigrateDelegation(guildMemberAddresses[i]); - var actionContext = new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }; - world = action.Execute(actionContext); - } - - var repo = new GuildRepository(world, new ActionContext()); - var guild = repo.GetGuild(guildAddress); - - for (var i = 0; i < migratedGuildMemberCount; i++) - { - repo.GetGuildParticipant(guildMemberAddresses[i]); - } - - for (var i = migratedGuildMemberCount; i < guildMemberCount; i++) - { - Assert.Throws(() => repo.GetGuildParticipant(guildMemberAddresses[i])); - } - } - - private static IWorld EnsureLegacyPlanetariumGuild(IWorld world, GuildAddress guildAddress) - { - var legacyPlanetariumGuild = new LegacyGuild(GuildConfig.PlanetariumGuildOwner); - var legacyPlanetariumGuildParticipant = new LegacyGuildParticipant(guildAddress); - - return world - .MutateAccount( - Addresses.Guild, - account => account.SetState(guildAddress, legacyPlanetariumGuild.Bencoded)) - .MutateAccount( - Addresses.GuildParticipant, - account => account.SetState(GuildConfig.PlanetariumGuildOwner, legacyPlanetariumGuildParticipant.Bencoded)) - .MutateAccount( - Addresses.GuildMemberCounter, - account => - { - BigInteger count = account.GetState(guildAddress) switch - { - Integer i => i.Value, - null => 0, - _ => throw new InvalidCastException(), - }; - - return account.SetState(guildAddress, (Integer)(count + 1)); - }); - } - - private static IWorld EnsureJoinLegacyPlanetariumGuild(IWorld world, AgentAddress guildParticipantAddress) - { - var planetariumGuildAddress - = new LegacyGuildParticipant( - world.GetAccount(Addresses.GuildParticipant).GetState(GuildConfig.PlanetariumGuildOwner) as List).GuildAddress; - var legacyParticipant = new LegacyGuildParticipant(planetariumGuildAddress); - - return world - .MutateAccount(Addresses.GuildParticipant, account => account.SetState(guildParticipantAddress, legacyParticipant.Bencoded)) - .MutateAccount( - Addresses.GuildMemberCounter, - account => - { - BigInteger count = account.GetState(planetariumGuildAddress) switch - { - Integer i => i.Value, - null => 0, - _ => throw new InvalidCastException(), - }; - - return account.SetState(planetariumGuildAddress, (Integer)(count + 1)); - }); - } - - private static IWorld EnsureMigratedPlanetariumGuild(IWorld world) - => new MigratePlanetariumGuild().Execute(new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }); - } -} diff --git a/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumGuildTest.cs b/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumGuildTest.cs deleted file mode 100644 index 6f5686bd34..0000000000 --- a/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumGuildTest.cs +++ /dev/null @@ -1,65 +0,0 @@ -namespace Lib9c.Tests.Action.Guild.Migration -{ - using Lib9c.Tests.Util; - using Libplanet.Action.State; - using Libplanet.Crypto; - using Nekoyume; - using Nekoyume.Action; - using Nekoyume.Action.Guild; - using Nekoyume.Action.Guild.Migration; - using Nekoyume.Action.Guild.Migration.LegacyModels; - using Nekoyume.Extensions; - using Nekoyume.Model.Guild; - using Nekoyume.TypedAddress; - using Xunit; - - // TODO: Remove this test class after the migration is completed. - public class MigratePlanetariumGuildTest : GuildTestBase - { - [Fact] - public void Execute() - { - var guildAddress = AddressUtil.CreateGuildAddress(); - var world = EnsureLegacyPlanetariumGuild(World, guildAddress); - var repo = new GuildRepository(world, new ActionContext()); - - Assert.Throws(() => repo.GetGuild(guildAddress)); - Assert.Throws(() => repo.GetGuildParticipant(GuildConfig.PlanetariumGuildOwner)); - - var action = new MigratePlanetariumGuild(); - var actionContext = new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }; - world = action.Execute(actionContext); - - repo.UpdateWorld(world); - - var guild = repo.GetGuild(guildAddress); - var guildOwner = repo.GetGuildParticipant(GuildConfig.PlanetariumGuildOwner); - } - - private static IWorld EnsureLegacyPlanetariumGuild(IWorld world, GuildAddress guildAddress) - { - var legacyPlanetariumGuild = new LegacyGuild(GuildConfig.PlanetariumGuildOwner); - var legacyPlanetariumGuildParticipant = new LegacyGuildParticipant(guildAddress); - var guildAccount = world.GetAccount(Addresses.Guild); - var guildParticipantAccount = world.GetAccount(Addresses.GuildParticipant); - return world - .MutateAccount( - Addresses.Guild, - account => account.SetState(guildAddress, legacyPlanetariumGuild.Bencoded)) - .MutateAccount( - Addresses.GuildParticipant, - account => account.SetState(GuildConfig.PlanetariumGuildOwner, legacyPlanetariumGuildParticipant.Bencoded)); - } - - private static IWorld EnsureMigratedPlanetariumGuild(IWorld world) - => new MigratePlanetariumGuild().Execute(new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }); - } -} diff --git a/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumValidatorTest.cs b/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumValidatorTest.cs deleted file mode 100644 index cd15015166..0000000000 --- a/.Lib9c.Tests/Action/Guild/Migration/MigratePlanetariumValidatorTest.cs +++ /dev/null @@ -1,116 +0,0 @@ -namespace Lib9c.Tests.Action.Guild.Migration -{ - using System; - using System.Collections.Generic; - using System.Numerics; - using Lib9c.Tests.Util; - using Libplanet.Action.State; - using Libplanet.Crypto; - using Libplanet.Types.Assets; - using Libplanet.Types.Consensus; - using Nekoyume.Action.Guild; - using Nekoyume.Action.Guild.Migration; - using Nekoyume.Action.Guild.Migration.LegacyModels; - using Nekoyume.Action.ValidatorDelegation; - using Nekoyume.Model.Guild; - using Nekoyume.Model.Stake; - using Nekoyume.TypedAddress; - using Nekoyume.ValidatorDelegation; - using Xunit; - - // TODO: Remove this test class after the migration is completed. - public class MigratePlanetariumValidatorTest : GuildTestBase - { - [Fact] - public void Execute() - { - var guildAddress = AddressUtil.CreateGuildAddress(); - var validatorKey = new PrivateKey().PublicKey; - var validatorAddress = validatorKey.Address; - var power = 10_000_000_000_000_000_000; - var guildGold = Currencies.GuildGold; - var delegated = FungibleAssetValue.FromRawValue(guildGold, power); - - var world = EnsureLegacyPlanetariumValidator( - World, guildAddress, validatorKey, power); - - var guildRepository = new GuildRepository(world, new ActionContext { }); - var validatorRepository = new ValidatorRepository(world, new ActionContext { }); - var guildDelegatee = guildRepository.GetGuildDelegatee(validatorAddress); - var validatorDelegatee = validatorRepository.GetValidatorDelegatee(validatorAddress); - - Assert.False(validatorDelegatee.IsActive); - Assert.Equal(ValidatorDelegatee.InactiveDelegationPoolAddress, guildDelegatee.DelegationPoolAddress); - Assert.Equal(ValidatorDelegatee.InactiveDelegationPoolAddress, validatorDelegatee.DelegationPoolAddress); - Assert.Equal(delegated, world.GetBalance(ValidatorDelegatee.InactiveDelegationPoolAddress, Currencies.GuildGold)); - Assert.Equal(guildGold * 0, world.GetBalance(ValidatorDelegatee.ActiveDelegationPoolAddress, Currencies.GuildGold)); - - var action = new MigratePlanetariumValidator(); - var actionContext = new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }; - world = action.Execute(actionContext); - - guildRepository = new GuildRepository(world, new ActionContext { }); - validatorRepository = new ValidatorRepository(world, new ActionContext { }); - guildDelegatee = guildRepository.GetGuildDelegatee(validatorAddress); - validatorDelegatee = validatorRepository.GetValidatorDelegatee(validatorAddress); - - Assert.True(validatorRepository.GetValidatorDelegatee(validatorAddress).IsActive); - Assert.Equal(ValidatorDelegatee.ActiveDelegationPoolAddress, guildDelegatee.DelegationPoolAddress); - Assert.Equal(ValidatorDelegatee.ActiveDelegationPoolAddress, validatorDelegatee.DelegationPoolAddress); - Assert.Equal(delegated, world.GetBalance(ValidatorDelegatee.ActiveDelegationPoolAddress, Currencies.GuildGold)); - Assert.Equal(guildGold * 0, world.GetBalance(ValidatorDelegatee.InactiveDelegationPoolAddress, Currencies.GuildGold)); - - Assert.Throws(() => - { - var actionContext = new ActionContext - { - PreviousState = world, - Signer = new PrivateKey().Address, - }; - - world = action.Execute(actionContext); - }); - } - - private static IWorld EnsureLegacyPlanetariumValidator( - IWorld world, GuildAddress guildAddress, PublicKey validatorKey, BigInteger power) - { - world = world.SetDelegationMigrationHeight(0L); - - var toDelegate = FungibleAssetValue.FromRawValue(Currencies.GuildGold, power); - world = world - .MintAsset( - new ActionContext { }, - StakeState.DeriveAddress(validatorKey.Address), - toDelegate) - .MintAsset( - new ActionContext { }, - validatorKey.Address, - Currencies.Mead * 1); - - world = new PromoteValidator(validatorKey, toDelegate).Execute(new ActionContext - { - PreviousState = world, - Signer = validatorKey.Address, - }); - - world = new MakeGuild(validatorKey.Address).Execute(new ActionContext - { - PreviousState = world, - Signer = GuildConfig.PlanetariumGuildOwner, - }); - - world = world.SetValidatorSet(new ValidatorSet( - new List - { - new Validator(validatorKey, power), - })); - - return world; - } - } -} diff --git a/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegatee.cs b/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegatee.cs deleted file mode 100644 index ef76cd00bc..0000000000 --- a/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegatee.cs +++ /dev/null @@ -1,471 +0,0 @@ -#nullable enable -namespace Lib9c.Tests.Delegation.Migration -{ - using System; - using System.Collections.Generic; - using System.Collections.Immutable; - using System.Linq; - using System.Numerics; - using Bencodex.Types; - using Libplanet.Crypto; - using Libplanet.Types.Assets; - using Nekoyume.Delegation; - - public class LegacyTestDelegatee : IDelegatee - { - public LegacyTestDelegatee( - Address address, - Address accountAddress, - Currency delegationCurrency, - IEnumerable rewardCurrencies, - Address delegationPoolAddress, - Address rewardPoolAddress, - Address rewardRemainderPoolAddress, - Address slashedPoolAddress, - long unbondingPeriod, - int maxUnbondLockInEntries, - int maxRebondGraceEntries, - IDelegationRepository repository) - : this( - new DelegateeMetadata( - address, - accountAddress, - delegationCurrency, - rewardCurrencies, - delegationPoolAddress, - rewardPoolAddress, - rewardRemainderPoolAddress, - slashedPoolAddress, - unbondingPeriod, - maxUnbondLockInEntries, - maxRebondGraceEntries), - repository) - { - } - - public LegacyTestDelegatee( - Address address, - IDelegationRepository repository) - : this(repository.GetDelegateeMetadata(address), repository) - { - } - - private LegacyTestDelegatee(DelegateeMetadata metadata, IDelegationRepository repository) - { - Metadata = metadata; - Repository = repository; - } - - public event EventHandler? DelegationChanged; - - public event EventHandler? Enjailed; - - public event EventHandler? Unjailed; - - public DelegateeMetadata Metadata { get; } - - public IDelegationRepository Repository { get; } - - public Address Address => Metadata.DelegateeAddress; - - public Address AccountAddress => Metadata.DelegateeAccountAddress; - - public Address MetadataAddress => Metadata.Address; - - public Currency DelegationCurrency => Metadata.DelegationCurrency; - - public ImmutableSortedSet RewardCurrencies => Metadata.RewardCurrencies; - - public Address DelegationPoolAddress => Metadata.DelegationPoolAddress; - - public Address RewardPoolAddress => Metadata.RewardPoolAddress; - - public Address RewardRemainderPoolAddress => Metadata.RewardRemainderPoolAddress; - - public Address SlashedPoolAddress => Metadata.SlashedPoolAddress; - - public long UnbondingPeriod => Metadata.UnbondingPeriod; - - public int MaxUnbondLockInEntries => Metadata.MaxUnbondLockInEntries; - - public int MaxRebondGraceEntries => Metadata.MaxRebondGraceEntries; - - public FungibleAssetValue TotalDelegated => Metadata.TotalDelegatedFAV; - - public BigInteger TotalShares => Metadata.TotalShares; - - public bool Jailed => Metadata.Jailed; - - public long JailedUntil => Metadata.JailedUntil; - - public bool Tombstoned => Metadata.Tombstoned; - - public List MetadataBencoded => Metadata.Bencoded; - - public BigInteger ShareFromFAV(FungibleAssetValue fav) - => Metadata.ShareFromFAV(fav); - - public FungibleAssetValue FAVFromShare(BigInteger share) - => Metadata.FAVFromShare(share); - - public BigInteger Bond(IDelegator delegator, FungibleAssetValue fav, long height) - => Bond((LegacyTestDelegator)delegator, fav, height); - - public FungibleAssetValue Unbond(IDelegator delegator, BigInteger share, long height) - => Unbond((LegacyTestDelegator)delegator, share, height); - - public void DistributeReward(IDelegator delegator, long height) - => DistributeReward((LegacyTestDelegator)delegator, height); - - public void Jail(long releaseHeight) - { - Metadata.JailedUntil = releaseHeight; - Metadata.Jailed = true; - Repository.SetDelegateeMetadata(Metadata); - Enjailed?.Invoke(this, EventArgs.Empty); - } - - public void Unjail(long height) - { - if (!Jailed) - { - throw new InvalidOperationException("Cannot unjail non-jailed delegatee."); - } - - if (Tombstoned) - { - throw new InvalidOperationException("Cannot unjail tombstoned delegatee."); - } - - if (JailedUntil >= height) - { - throw new InvalidOperationException("Cannot unjail before jailed until."); - } - - Metadata.JailedUntil = -1L; - Metadata.Jailed = false; - Repository.SetDelegateeMetadata(Metadata); - Unjailed?.Invoke(this, EventArgs.Empty); - } - - public void Tombstone() - { - Jail(long.MaxValue); - Metadata.Tombstoned = true; - Repository.SetDelegateeMetadata(Metadata); - } - - public Address BondAddress(Address delegatorAddress) - => Metadata.BondAddress(delegatorAddress); - - public Address UnbondLockInAddress(Address delegatorAddress) - => Metadata.UnbondLockInAddress(delegatorAddress); - - public Address RebondGraceAddress(Address delegatorAddress) - => Metadata.RebondGraceAddress(delegatorAddress); - - public Address CurrentLumpSumRewardsRecordAddress() - => Metadata.CurrentLumpSumRewardsRecordAddress(); - - public Address LumpSumRewardsRecordAddress(long height) - => Metadata.LumpSumRewardsRecordAddress(height); - - public Address CurrentRewardBaseAddress() => throw new NotImplementedException(); - - public Address RewardBaseAddress(long height) => throw new NotImplementedException(); - - public BigInteger Bond(LegacyTestDelegator delegator, FungibleAssetValue fav, long height) - { - DistributeReward(delegator, height); - - if (!fav.Currency.Equals(DelegationCurrency)) - { - throw new InvalidOperationException( - "Cannot bond with invalid currency."); - } - - if (Tombstoned) - { - throw new InvalidOperationException( - "Cannot bond to tombstoned delegatee."); - } - - Bond bond = Repository.GetBond(this, delegator.Address); - BigInteger share = ShareFromFAV(fav); - bond = bond.AddShare(share); - Metadata.AddShare(share); - Metadata.AddDelegatedFAV(fav); - Repository.SetBond(bond); - StartNewRewardPeriod(height); - Repository.SetDelegateeMetadata(Metadata); - DelegationChanged?.Invoke(this, height); - - return share; - } - - BigInteger IDelegatee.Bond(IDelegator delegator, FungibleAssetValue fav, long height) - => Bond((LegacyTestDelegator)delegator, fav, height); - - public FungibleAssetValue Unbond(LegacyTestDelegator delegator, BigInteger share, long height) - { - DistributeReward(delegator, height); - if (TotalShares.IsZero || TotalDelegated.RawValue.IsZero) - { - throw new InvalidOperationException( - "Cannot unbond without bonding."); - } - - Bond bond = Repository!.GetBond(this, delegator.Address); - FungibleAssetValue fav = FAVFromShare(share); - bond = bond.SubtractShare(share); - if (bond.Share.IsZero) - { - bond = bond.ClearLastDistributeHeight(); - } - - Metadata.RemoveShare(share); - Metadata.RemoveDelegatedFAV(fav); - Repository.SetBond(bond); - StartNewRewardPeriod(height); - Repository.SetDelegateeMetadata(Metadata); - DelegationChanged?.Invoke(this, height); - - return fav; - } - - FungibleAssetValue IDelegatee.Unbond(IDelegator delegator, BigInteger share, long height) - => Unbond((LegacyTestDelegator)delegator, share, height); - - public void DistributeReward(LegacyTestDelegator delegator, long height) - { - Bond bond = Repository.GetBond(this, delegator.Address); - BigInteger share = bond.Share; - - if (!share.IsZero && bond.LastDistributeHeight.HasValue) - { - IEnumerable lumpSumRewardsRecords - = GetLumpSumRewardsRecords(bond.LastDistributeHeight); - - foreach (LumpSumRewardsRecord record in lumpSumRewardsRecords) - { - TransferReward(delegator, share, record); - // TransferRemainders(newRecord); - Repository.SetLumpSumRewardsRecord(record); - } - } - - if (bond.LastDistributeHeight != height) - { - bond = bond.UpdateLastDistributeHeight(height); - } - - Repository.SetBond(bond); - } - - void IDelegatee.DistributeReward(IDelegator delegator, long height) - => DistributeReward((LegacyTestDelegator)delegator, height); - - public void CollectRewards(long height) - { - var rewards = RewardCurrencies.Select(c => Repository.GetBalance(RewardPoolAddress, c)); - LumpSumRewardsRecord record = Repository.GetCurrentLumpSumRewardsRecord(this) - ?? new LumpSumRewardsRecord( - CurrentLumpSumRewardsRecordAddress(), - height, - TotalShares, - RewardCurrencies); - record = record.AddLumpSumRewards(rewards); - - foreach (var rewardsEach in rewards) - { - if (rewardsEach.Sign > 0) - { - Repository.TransferAsset(RewardPoolAddress, record.Address, rewardsEach); - } - } - - Repository.SetLumpSumRewardsRecord(record); - } - - public virtual void Slash(BigInteger slashFactor, long infractionHeight, long height) - { - FungibleAssetValue slashed = TotalDelegated.DivRem(slashFactor, out var rem); - if (rem.Sign > 0) - { - slashed += FungibleAssetValue.FromRawValue(rem.Currency, 1); - } - - if (slashed > Metadata.TotalDelegatedFAV) - { - slashed = Metadata.TotalDelegatedFAV; - } - - Metadata.RemoveDelegatedFAV(slashed); - - foreach (var item in Metadata.UnbondingRefs) - { - var unbonding = UnbondingFactory.GetUnbondingFromRef(item, Repository); - - unbonding = unbonding.Slash(slashFactor, infractionHeight, height, out var slashedFAV); - - if (slashedFAV.HasValue) - { - slashed += slashedFAV.Value; - } - - if (unbonding.IsEmpty) - { - Metadata.RemoveUnbondingRef(item); - } - - switch (unbonding) - { - case UnbondLockIn unbondLockIn: - Repository.SetUnbondLockIn(unbondLockIn); - break; - case RebondGrace rebondGrace: - Repository.SetRebondGrace(rebondGrace); - break; - default: - throw new InvalidOperationException("Invalid unbonding type."); - } - } - - var delegationBalance = Repository.GetBalance(DelegationPoolAddress, DelegationCurrency); - if (delegationBalance < slashed) - { - slashed = delegationBalance; - } - - if (slashed > DelegationCurrency * 0) - { - Repository.TransferAsset(DelegationPoolAddress, SlashedPoolAddress, slashed); - } - - Repository.SetDelegateeMetadata(Metadata); - DelegationChanged?.Invoke(this, height); - } - - void IDelegatee.Slash(BigInteger slashFactor, long infractionHeight, long height) - => Slash(slashFactor, infractionHeight, height); - - public void AddUnbondingRef(UnbondingRef reference) - => Metadata.AddUnbondingRef(reference); - - public void RemoveUnbondingRef(UnbondingRef reference) - => Metadata.RemoveUnbondingRef(reference); - - public ImmutableDictionary CalculateReward( - BigInteger share, - IEnumerable lumpSumRewardsRecords) - { - ImmutableDictionary reward - = RewardCurrencies.ToImmutableDictionary(c => c, c => c * 0); - - foreach (LumpSumRewardsRecord record in lumpSumRewardsRecords) - { - var rewardDuringPeriod = record.RewardsDuringPeriod(share); - reward = rewardDuringPeriod.Aggregate(reward, (acc, pair) - => acc.SetItem(pair.Key, acc[pair.Key] + pair.Value)); - } - - return reward; - } - - private void StartNewRewardPeriod(long height) - { - LumpSumRewardsRecord? currentRecord = Repository.GetCurrentLumpSumRewardsRecord(this); - long? lastStartHeight = null; - if (currentRecord is LumpSumRewardsRecord lastRecord) - { - lastStartHeight = lastRecord.StartHeight; - if (lastStartHeight == height) - { - currentRecord = new ( - currentRecord.Address, - currentRecord.StartHeight, - TotalShares, - RewardCurrencies, - currentRecord.LastStartHeight); - - Repository.SetLumpSumRewardsRecord(currentRecord); - return; - } - - Address archiveAddress = LumpSumRewardsRecordAddress(lastRecord.StartHeight); - - foreach (var rewardCurrency in RewardCurrencies) - { - FungibleAssetValue reward = Repository.GetBalance(lastRecord.Address, rewardCurrency); - if (reward.Sign > 0) - { - Repository.TransferAsset(lastRecord.Address, archiveAddress, reward); - } - } - - lastRecord = lastRecord.MoveAddress(archiveAddress); - Repository.SetLumpSumRewardsRecord(lastRecord); - } - - LumpSumRewardsRecord newRecord = new ( - CurrentLumpSumRewardsRecordAddress(), - height, - TotalShares, - RewardCurrencies, - lastStartHeight); - - Repository.SetLumpSumRewardsRecord(newRecord); - } - - private List GetLumpSumRewardsRecords(long? lastRewardHeight) - { - List records = new (); - if (lastRewardHeight is null - || !(Repository.GetCurrentLumpSumRewardsRecord(this) is LumpSumRewardsRecord record)) - { - return records; - } - - while (record.StartHeight >= lastRewardHeight) - { - records.Add(record); - - if (!(record.LastStartHeight is long lastStartHeight)) - { - break; - } - - record = Repository.GetLumpSumRewardsRecord(this, lastStartHeight) - ?? throw new InvalidOperationException( - $"Lump sum rewards record for #{lastStartHeight} is missing"); - } - - return records; - } - - private void TransferReward(LegacyTestDelegator delegator, BigInteger share, LumpSumRewardsRecord record) - { - ImmutableSortedDictionary reward = record.RewardsDuringPeriod(share); - foreach (var rewardEach in reward) - { - if (rewardEach.Value.Sign > 0) - { - Repository.TransferAsset(record.Address, delegator.RewardAddress, rewardEach.Value); - } - } - } - - private void TransferRemainders(LumpSumRewardsRecord record) - { - foreach (var rewardCurrency in RewardCurrencies) - { - FungibleAssetValue remainder = Repository.GetBalance(record.Address, rewardCurrency); - - if (remainder.Sign > 0) - { - Repository.TransferAsset(record.Address, RewardRemainderPoolAddress, remainder); - } - } - } - } -} diff --git a/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegator.cs b/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegator.cs deleted file mode 100644 index a2ab3ade94..0000000000 --- a/.Lib9c.Tests/Delegation/Migration/LegacyTestDelegator.cs +++ /dev/null @@ -1,228 +0,0 @@ -#nullable enable -namespace Lib9c.Tests.Delegation.Migration -{ - using System; - using System.Collections.Immutable; - using System.Numerics; - using Bencodex.Types; - using Libplanet.Crypto; - using Libplanet.Types.Assets; - using Nekoyume.Delegation; - - public class LegacyTestDelegator : IDelegator - { - public LegacyTestDelegator( - Address address, - Address accountAddress, - Address delegationPoolAddress, - Address rewardAddress, - IDelegationRepository repository) - : this( - new DelegatorMetadata( - address, - accountAddress, - delegationPoolAddress, - rewardAddress), - repository) - { - } - - public LegacyTestDelegator( - Address address, - IDelegationRepository repository) - : this(repository.GetDelegatorMetadata(address), repository) - { - } - - private LegacyTestDelegator(DelegatorMetadata metadata, IDelegationRepository repository) - { - Metadata = metadata; - Repository = repository; - } - - public DelegatorMetadata Metadata { get; } - - public IDelegationRepository Repository { get; } - - public Address Address => Metadata.DelegatorAddress; - - public Address AccountAddress => Metadata.DelegatorAccountAddress; - - public Address MetadataAddress => Metadata.Address; - - public Address DelegationPoolAddress => Metadata.DelegationPoolAddress; - - public Address RewardAddress => Metadata.RewardAddress; - - public ImmutableSortedSet
Delegatees => Metadata.Delegatees; - - public List MetadataBencoded => Metadata.Bencoded; - - public void Delegate( - LegacyTestDelegatee delegatee, FungibleAssetValue fav, long height) - { - if (fav.Sign <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(fav), fav, "Fungible asset value must be positive."); - } - - if (delegatee.Tombstoned) - { - throw new InvalidOperationException("Delegatee is tombstoned."); - } - - delegatee.Bond(this, fav, height); - Metadata.AddDelegatee(delegatee.Address); - Repository.TransferAsset(DelegationPoolAddress, delegatee.DelegationPoolAddress, fav); - Repository.SetDelegatorMetadata(Metadata); - } - - void IDelegator.Delegate( - IDelegatee delegatee, FungibleAssetValue fav, long height) - => Delegate((LegacyTestDelegatee)delegatee, fav, height); - - public void Undelegate( - LegacyTestDelegatee delegatee, BigInteger share, long height) - { - if (share.Sign <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(share), share, "Share must be positive."); - } - - if (height <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(height), height, "Height must be positive."); - } - - UnbondLockIn unbondLockIn = Repository.GetUnbondLockIn(delegatee, Address); - - if (unbondLockIn.IsFull) - { - throw new InvalidOperationException("Undelegation is full."); - } - - FungibleAssetValue fav = delegatee.Unbond(this, share, height); - unbondLockIn = unbondLockIn.LockIn( - fav, height, height + delegatee.UnbondingPeriod); - - if (Repository.GetBond(delegatee, Address).Share.IsZero) - { - Metadata.RemoveDelegatee(delegatee.Address); - } - - delegatee.AddUnbondingRef(UnbondingFactory.ToReference(unbondLockIn)); - - Repository.SetUnbondLockIn(unbondLockIn); - Repository.SetUnbondingSet( - Repository.GetUnbondingSet().SetUnbonding(unbondLockIn)); - Repository.SetDelegatorMetadata(Metadata); - } - - void IDelegator.Undelegate( - IDelegatee delegatee, BigInteger share, long height) - => Undelegate((LegacyTestDelegatee)delegatee, share, height); - - public void Redelegate( - LegacyTestDelegatee srcDelegatee, LegacyTestDelegatee dstDelegatee, BigInteger share, long height) - { - if (share.Sign <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(share), share, "Share must be positive."); - } - - if (height <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(height), height, "Height must be positive."); - } - - if (dstDelegatee.Tombstoned) - { - throw new InvalidOperationException("Destination delegatee is tombstoned."); - } - - FungibleAssetValue fav = srcDelegatee.Unbond( - this, share, height); - dstDelegatee.Bond( - this, fav, height); - RebondGrace srcRebondGrace = Repository.GetRebondGrace(srcDelegatee, Address).Grace( - dstDelegatee.Address, - fav, - height, - height + srcDelegatee.UnbondingPeriod); - - if (Repository.GetBond(srcDelegatee, Address).Share.IsZero) - { - Metadata.RemoveDelegatee(srcDelegatee.Address); - } - - Metadata.AddDelegatee(dstDelegatee.Address); - - srcDelegatee.AddUnbondingRef(UnbondingFactory.ToReference(srcRebondGrace)); - - Repository.SetRebondGrace(srcRebondGrace); - Repository.SetUnbondingSet( - Repository.GetUnbondingSet().SetUnbonding(srcRebondGrace)); - Repository.SetDelegatorMetadata(Metadata); - } - - void IDelegator.Redelegate( - IDelegatee srcDelegatee, IDelegatee dstDelegatee, BigInteger share, long height) - => Redelegate((LegacyTestDelegatee)srcDelegatee, (LegacyTestDelegatee)dstDelegatee, share, height); - - public void CancelUndelegate( - LegacyTestDelegatee delegatee, FungibleAssetValue fav, long height) - { - if (fav.Sign <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(fav), fav, "Fungible asset value must be positive."); - } - - if (height <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(height), height, "Height must be positive."); - } - - UnbondLockIn unbondLockIn = Repository.GetUnbondLockIn(delegatee, Address); - - if (unbondLockIn.IsFull) - { - throw new InvalidOperationException("Undelegation is full."); - } - - delegatee.Bond(this, fav, height); - unbondLockIn = unbondLockIn.Cancel(fav, height); - Metadata.AddDelegatee(delegatee.Address); - - if (unbondLockIn.IsEmpty) - { - delegatee.RemoveUnbondingRef(UnbondingFactory.ToReference(unbondLockIn)); - } - - Repository.SetUnbondLockIn(unbondLockIn); - Repository.SetUnbondingSet( - Repository.GetUnbondingSet().SetUnbonding(unbondLockIn)); - Repository.SetDelegatorMetadata(Metadata); - } - - void IDelegator.CancelUndelegate( - IDelegatee delegatee, FungibleAssetValue fav, long height) - => CancelUndelegate((LegacyTestDelegatee)delegatee, fav, height); - - public void ClaimReward( - LegacyTestDelegatee delegatee, long height) - { - delegatee.DistributeReward(this, height); - Repository.SetDelegatorMetadata(Metadata); - } - - void IDelegator.ClaimReward(IDelegatee delegatee, long height) - => ClaimReward((LegacyTestDelegatee)delegatee, height); - } -} diff --git a/.Lib9c.Tests/Delegation/Migration/RewardBaseMigrationTest.cs b/.Lib9c.Tests/Delegation/Migration/RewardBaseMigrationTest.cs deleted file mode 100644 index 3dcca62e6c..0000000000 --- a/.Lib9c.Tests/Delegation/Migration/RewardBaseMigrationTest.cs +++ /dev/null @@ -1,138 +0,0 @@ -#nullable enable -namespace Lib9c.Tests.Delegation.Migration -{ - using System.Linq; - using Nekoyume.Delegation; - using Nekoyume.Extensions; - using Xunit; - - public class RewardBaseMigrationTest - { - private readonly DelegationFixture _fixture; - - public RewardBaseMigrationTest() - { - _fixture = new DelegationFixture(); - } - - public LegacyTestDelegatee LegacyDelegatee - => new LegacyTestDelegatee( - _fixture.TestDelegatee1.Address, - _fixture.TestRepository); - - public LegacyTestDelegator LegacyDelegator1 - => new LegacyTestDelegator( - _fixture.TestDelegator1.Address, - _fixture.TestRepository); - - public LegacyTestDelegator LegacyDelegator2 - => new LegacyTestDelegator( - _fixture.TestDelegator2.Address, - _fixture.TestRepository); - - [Fact] - public void Migrate() - { - var repo = _fixture.TestRepository; - - var delegatorInitialBalance = LegacyDelegatee.DelegationCurrency * 2000; - repo.MintAsset(LegacyDelegator1.Address, delegatorInitialBalance); - repo.MintAsset(LegacyDelegator2.Address, delegatorInitialBalance); - - var rewards = LegacyDelegatee.RewardCurrencies.Select(r => r * 100); - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(7L); - - var delegatingFAV = LegacyDelegatee.DelegationCurrency * 100; - LegacyDelegator1.Delegate(LegacyDelegatee, delegatingFAV, 10L); - - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(13L); - - var delegatingFAV1 = LegacyDelegatee.DelegationCurrency * 100; - LegacyDelegator2.Delegate(LegacyDelegatee, delegatingFAV1, 15L); - - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(17L); - var delegatingFAV2 = LegacyDelegatee.DelegationCurrency * 200; - LegacyDelegator2.Delegate(LegacyDelegatee, delegatingFAV2, 20L); - - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(23L); - var delegatingFAV3 = LegacyDelegatee.DelegationCurrency * 300; - LegacyDelegator2.Delegate(LegacyDelegatee, delegatingFAV3, 25L); - - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(27L); - var delegatingFAV4 = LegacyDelegatee.DelegationCurrency * 400; - LegacyDelegator2.Delegate(LegacyDelegatee, delegatingFAV4, 30L); - - foreach (var reward in rewards) - { - repo.MintAsset(LegacyDelegatee.RewardPoolAddress, reward); - } - - LegacyDelegatee.CollectRewards(23L); - - _fixture.TestRepository.UpdateWorld(_fixture.TestRepository.World.MutateAccount( - _fixture.TestRepository.DelegateeMetadataAccountAddress, - a => a.SetState(LegacyDelegatee.MetadataAddress, LegacyDelegatee.MetadataBencoded))); - _fixture.TestRepository.UpdateWorld(_fixture.TestRepository.World.MutateAccount( - _fixture.TestRepository.DelegatorMetadataAccountAddress, - a => a.SetState(LegacyDelegatee.Metadata.Address, LegacyDelegatee.Metadata.Bencoded))); - _fixture.TestRepository.UpdateWorld(_fixture.TestRepository.World.MutateAccount( - _fixture.TestRepository.DelegatorMetadataAccountAddress, - a => a.SetState(LegacyDelegatee.Metadata.Address, LegacyDelegatee.Metadata.Bencoded))); - - var delegator1 = _fixture.TestRepository.GetDelegator(_fixture.TestDelegator1.Address); - var delegator2 = _fixture.TestRepository.GetDelegator(_fixture.TestDelegator2.Address); - var delegatee = _fixture.TestRepository.GetDelegatee(_fixture.TestDelegatee1.Address); - - var delegatingFAV5 = delegatee.DelegationCurrency * 500; - delegator2.Delegate(delegatee, delegatingFAV5, 35L); - - foreach (var reward in rewards) - { - repo.MintAsset(delegatee.RewardPoolAddress, reward); - } - - delegatee.CollectRewards(37); - - var delegator1RewardBeforeDelegate = repo.GetBalance(delegator1.RewardAddress, DelegationFixture.TestRewardCurrency); - Assert.Equal(DelegationFixture.TestRewardCurrency * 0, delegator1RewardBeforeDelegate); - - delegator1.Delegate(delegatee, delegatingFAV5, 40L); - - var delegator1Reward = repo.GetBalance(delegator1.RewardAddress, DelegationFixture.TestRewardCurrency); - - var expectedReward = DelegationFixture.TestRewardCurrency * 100 - + (DelegationFixture.TestRewardCurrency * 100 * 100).DivRem(200).Quotient - + (DelegationFixture.TestRewardCurrency * 100 * 100).DivRem(400).Quotient - + (DelegationFixture.TestRewardCurrency * 100 * 100).DivRem(700).Quotient - + (DelegationFixture.TestRewardCurrency * 100 * 100).DivRem(1100).Quotient - + (DelegationFixture.TestRewardCurrency * 100 * 100).DivRem(1600).Quotient; - - Assert.Equal(expectedReward.MajorUnit, delegator1Reward.MajorUnit); - } - } -} diff --git a/Lib9c/Action/Guild/Migration/FixToRefundFromNonValidator.cs b/Lib9c/Action/Guild/Migration/FixToRefundFromNonValidator.cs deleted file mode 100644 index 16e613d35e..0000000000 --- a/Lib9c/Action/Guild/Migration/FixToRefundFromNonValidator.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Bencodex.Types; -using Lib9c; -using Libplanet.Action; -using Libplanet.Action.State; -using Libplanet.Crypto; -using Nekoyume.Model.Stake; -using Nekoyume.Model.State; - -namespace Nekoyume.Action.Guild.Migration -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// An action to fix refund from non-validator. - /// - [ActionType(TypeIdentifier)] - public class FixToRefundFromNonValidator : ActionBase - { - public const string TypeIdentifier = "fix_to_refund_from_non_validator"; - - private const string TargetsKey = "t"; - - public List<(Address Address, int Amount)> Targets { get; private set; } - - public FixToRefundFromNonValidator() - { - } - - public FixToRefundFromNonValidator( - IEnumerable<(Address, int)> targets) - { - Targets = targets.ToList(); - } - - public override IValue PlainValue => Dictionary.Empty - .Add("type_id", TypeIdentifier) - .Add("values", Dictionary.Empty - .Add( - TargetsKey, - new List(Targets.Select(t => - new List(t.Item1.Bencoded, (Integer)t.Item2))))); - - public override void LoadPlainValue(IValue plainValue) - { - if (plainValue is not Dictionary root || - !root.TryGetValue((Text)"values", out var rawValues) || - rawValues is not Dictionary values || - !values.TryGetValue((Text)TargetsKey, out var rawTarget) || - rawTarget is not List targets) - { - throw new InvalidCastException(); - } - - Targets = targets.Select( - t => ( - new Address(((List)t)[0]), - (int)(Integer)((List)t)[1])).ToList(); - } - - public override IWorld Execute(IActionContext context) - { - GasTracer.UseGas(1); - - var world = context.PreviousState; - - if (!TryGetAdminState(context, out AdminState adminState)) - { - throw new InvalidOperationException("Couldn't find admin state"); - } - - if (context.Signer != adminState.AdminAddress) - { - throw new PermissionDeniedException(adminState, context.Signer); - } - - foreach (var ta in Targets) - { - world = RefundFromNonValidator(context, world, ta); - } - - return world; - } - - private IWorld RefundFromNonValidator(IActionContext context, IWorld world, (Address, int) ta) - { - var (target, amount) = ta; - var stakeStateAddress = StakeState.DeriveAddress(target); - - return world.TransferAsset( - context, - Addresses.NonValidatorDelegatee, - stakeStateAddress, - Currencies.GuildGold * amount); - } - } -} diff --git a/Lib9c/Action/Guild/Migration/GuildMigrationFailedException.cs b/Lib9c/Action/Guild/Migration/GuildMigrationFailedException.cs deleted file mode 100644 index 118fd7e7f9..0000000000 --- a/Lib9c/Action/Guild/Migration/GuildMigrationFailedException.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Nekoyume.Action.Guild.Migration -{ - /// - /// An exception to be thrown when guild migration failed. - /// - public class GuildMigrationFailedException : InvalidOperationException - { - public GuildMigrationFailedException(string message) : base(message) - { - } - } -} diff --git a/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuild.cs b/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuild.cs deleted file mode 100644 index da7e83b982..0000000000 --- a/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuild.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using Bencodex; -using Bencodex.Types; -using Nekoyume.TypedAddress; - -namespace Nekoyume.Action.Guild.Migration.LegacyModels -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// The legacy model for Guild. - /// - public class LegacyGuild : IEquatable, IBencodable - { - private const string StateTypeName = "guild"; - private const long StateVersion = 1; - - public readonly AgentAddress GuildMasterAddress; - - public LegacyGuild(AgentAddress guildMasterAddress) - { - GuildMasterAddress = guildMasterAddress; - } - - public LegacyGuild(List list) : this(new AgentAddress(list[2])) - { - if (list[0] is not Text text || text != StateTypeName || list[1] is not Integer integer) - { - throw new InvalidCastException(); - } - - if (integer > StateVersion) - { - throw new FailedLoadStateException("Un-deserializable state."); - } - } - - public List Bencoded => List.Empty - .Add(StateTypeName) - .Add(StateVersion) - .Add(GuildMasterAddress.Bencoded); - - IValue IBencodable.Bencoded => Bencoded; - - public bool Equals(LegacyGuild other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return GuildMasterAddress.Equals(other.GuildMasterAddress); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((LegacyGuild)obj); - } - - public override int GetHashCode() - { - return GuildMasterAddress.GetHashCode(); - } - } -} diff --git a/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuildParticipant.cs b/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuildParticipant.cs deleted file mode 100644 index f3724c86a6..0000000000 --- a/Lib9c/Action/Guild/Migration/LegacyModels/LegacyGuildParticipant.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using Bencodex; -using Bencodex.Types; -using Nekoyume.TypedAddress; - -namespace Nekoyume.Action.Guild.Migration.LegacyModels -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// The legacy model for GuildParticipant. - /// - public class LegacyGuildParticipant : IBencodable, IEquatable - { - private const string StateTypeName = "guild_participant"; - private const long StateVersion = 1; - - public readonly GuildAddress GuildAddress; - - public LegacyGuildParticipant(GuildAddress guildAddress) - { - GuildAddress = guildAddress; - } - - public LegacyGuildParticipant(List list) : this(new GuildAddress(list[2])) - { - if (list[0] is not Text text || text != StateTypeName || list[1] is not Integer integer) - { - throw new InvalidCastException(); - } - - if (integer > StateVersion) - { - throw new FailedLoadStateException("Un-deserializable state."); - } - } - - public List Bencoded => List.Empty - .Add(StateTypeName) - .Add(StateVersion) - .Add(GuildAddress.Bencoded); - - IValue IBencodable.Bencoded => Bencoded; - - public bool Equals(LegacyGuildParticipant other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return GuildAddress.Equals(other.GuildAddress); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((LegacyGuildParticipant)obj); - } - - public override int GetHashCode() - { - return GuildAddress.GetHashCode(); - } - } -} diff --git a/Lib9c/Action/Guild/Migration/MigrateDelegation.cs b/Lib9c/Action/Guild/Migration/MigrateDelegation.cs deleted file mode 100644 index 1f383fd908..0000000000 --- a/Lib9c/Action/Guild/Migration/MigrateDelegation.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System; -using Bencodex.Types; -using Lib9c; -using Libplanet.Action.State; -using Libplanet.Action; -using Nekoyume.Model.Guild; -using Nekoyume.TypedAddress; -using Nekoyume.Action.Guild.Migration.LegacyModels; -using Nekoyume.Module.Guild; -using Nekoyume.Model.Stake; -using Nekoyume.Model.State; -using Nekoyume.Module; -using Libplanet.Crypto; - -namespace Nekoyume.Action.Guild.Migration -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// An action to migrate guild delegation. - /// After migration is done, guild participant now have delegation with - /// validator. - /// - [ActionType(TypeIdentifier)] - public class MigrateDelegation : ActionBase - { - public const string TypeIdentifier = "migrate_delegation"; - - private const string TargetKey = "t"; - - public AgentAddress Target { get; private set; } - - [Obsolete("Don't call in code.", error: false)] - public MigrateDelegation() - { - } - - public MigrateDelegation(AgentAddress target) - { - Target = target; - } - - public override IValue PlainValue => Dictionary.Empty - .Add("type_id", TypeIdentifier) - .Add("values", Dictionary.Empty - .Add(TargetKey, Target.Bencoded)); - - public override void LoadPlainValue(IValue plainValue) - { - if (plainValue is not Dictionary root || - !root.TryGetValue((Text)"values", out var rawValues) || - rawValues is not Dictionary values || - !values.TryGetValue((Text)TargetKey, out var rawTarget) || - rawTarget is not Binary target) - { - throw new InvalidCastException(); - } - - Target = new AgentAddress(target); - } - - public override IWorld Execute(IActionContext context) - { - GasTracer.UseGas(1); - - var world = context.PreviousState; - - // Migrate stake state from v2 to v3 (Mint guild gold for staking) - var stakeStateAddr = LegacyStakeState.DeriveAddress(Target); - if (world.TryGetStakeState(Target, out var stakeState) - && stakeState.StateVersion == 2) - { - if (!StakeStateUtils.TryMigrateV2ToV3( - context, - world, - StakeState.DeriveAddress(Target), - stakeState, out var result)) - { - throw new InvalidOperationException( - "Failed to migrate stake state. Unexpected situation."); - } - - world = result.Value.world; - } - - - // Migrate guild participant state from legacy to new - var value = world.GetAccountState(Addresses.GuildParticipant).GetState(Target) as List; - - var repository = new GuildRepository(world, context); - if (repository.GetJoinedGuild(GuildConfig.PlanetariumGuildOwner) is not { } planetariumGuildAddress) - { - throw new NullReferenceException("Planetarium guild is not found."); - } - - if (!repository.TryGetGuild(planetariumGuildAddress, out var planetariumGuild)) - { - throw new GuildMigrationFailedException("Planetarium guild is not found."); - } - - if (planetariumGuild.GuildMasterAddress != GuildConfig.PlanetariumGuildOwner) - { - throw new GuildMigrationFailedException("Unexpected guild master."); - } - - try - { - var legacyGuildParticipant = new LegacyGuildParticipant(value); - var guildParticipant = new GuildParticipant( - Target, - legacyGuildParticipant.GuildAddress, - repository); - repository.SetGuildParticipant(guildParticipant); - - // Migrate delegation - var guild = repository.GetGuild(guildParticipant.GuildAddress); - var guildGold = repository.GetBalance(guildParticipant.DelegationPoolAddress, Currencies.GuildGold); - if (guildGold.RawValue > 0) - { - repository.Delegate(guildParticipant.Address, guildGold); - } - - return repository.World; - } - catch (Exception e) - { - if (e is FailedLoadStateException || e is NullReferenceException) - { - var pledgeAddress = ((Address)Target).GetPledgeAddress(); - - // Patron contract structure: - // [0] = PatronAddress - // [1] = IsApproved - // [2] = Mead amount to refill. - if (!world.TryGetLegacyState(pledgeAddress, out List list) || list.Count < 3 || - list[0] is not Binary || list[0].ToAddress() != MeadConfig.PatronAddress || - list[1] is not Bencodex.Types.Boolean approved || !approved) - { - throw new GuildMigrationFailedException("Unexpected pledge structure."); - } - - repository.JoinGuild(planetariumGuildAddress, Target); - return repository.World; - } - - throw; - } - } - } -} diff --git a/Lib9c/Action/Guild/Migration/MigratePlanetariumGuild.cs b/Lib9c/Action/Guild/Migration/MigratePlanetariumGuild.cs deleted file mode 100644 index 57e1b72de0..0000000000 --- a/Lib9c/Action/Guild/Migration/MigratePlanetariumGuild.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using Bencodex.Types; -using Libplanet.Action.State; -using Libplanet.Action; -using Nekoyume.Model.Guild; -using Nekoyume.Action.Guild.Migration.LegacyModels; -using Lib9c; -using Nekoyume.Module.Guild; - -namespace Nekoyume.Action.Guild.Migration -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// An action to migrate the planetarium guild. - /// After migration, the planetarium guild now has a validator to delegate. - /// - [ActionType(TypeIdentifier)] - public class MigratePlanetariumGuild : ActionBase - { - public const string TypeIdentifier = "migrate_planetarium_guild"; - - public MigratePlanetariumGuild() - { - } - - public override IValue PlainValue => Dictionary.Empty - .Add("type_id", TypeIdentifier) - .Add("values", Null.Value); - - public override void LoadPlainValue(IValue plainValue) - { - if (plainValue is not Dictionary root || - !root.TryGetValue((Text)"values", out var rawValues) || - rawValues is not Null) - { - throw new InvalidCastException(); - } - } - - public override IWorld Execute(IActionContext context) - { - GasTracer.UseGas(1); - - var world = context.PreviousState; - var repository = new GuildRepository(world, context); - - // Get Guild address - var guildMasterValue = world - .GetAccountState(Addresses.GuildParticipant) - .GetState(GuildConfig.PlanetariumGuildOwner) as List; - var legacyGuildMaster = new LegacyGuildParticipant(guildMasterValue); - var guildAddress = legacyGuildMaster.GuildAddress; - - // MigratePlanetariumGuild - var guildValue = world - .GetAccountState(Addresses.Guild) - .GetState(guildAddress) as List; - var legacyGuild = new LegacyGuild(guildValue); - var guild = new Model.Guild.Guild( - guildAddress, - legacyGuild.GuildMasterAddress, - context.Miner, - repository); - repository.SetGuild(guild); - - // MigratePlanetariumGuildMaster - var guildParticipant = new GuildParticipant( - GuildConfig.PlanetariumGuildOwner, - guildAddress, - repository); - repository.SetGuildParticipant(guildParticipant); - - // Migrate delegation - var guildGold = repository.GetBalance(guildParticipant.DelegationPoolAddress, Currencies.GuildGold); - if (guildGold.RawValue > 0) - { - repository.Delegate(guildParticipant.Address, guildGold); - } - - return repository.World; - } - } -} diff --git a/Lib9c/Action/Guild/Migration/MigratePlanetariumValidator.cs b/Lib9c/Action/Guild/Migration/MigratePlanetariumValidator.cs deleted file mode 100644 index 98ef4ee0f4..0000000000 --- a/Lib9c/Action/Guild/Migration/MigratePlanetariumValidator.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Action.State; -using Nekoyume.Model.Guild; -using Nekoyume.Module.Guild; -using Nekoyume.ValidatorDelegation; - -namespace Nekoyume.Action.Guild.Migration -{ - // TODO: [GuildMigration] Remove this class when the migration is done. - /// - /// An action to migrate the planetarium validator. - /// With this migration, planetarium validator is now active, - /// and bonded FAVs are moved to active address. - /// - [ActionType(TypeIdentifier)] - public class MigratePlanetariumValidator : ActionBase - { - public const string TypeIdentifier = "migrate_planetarium_validator"; - - public MigratePlanetariumValidator() - { - } - - public override IValue PlainValue => Dictionary.Empty - .Add("type_id", TypeIdentifier) - .Add("values", Null.Value); - - public override void LoadPlainValue(IValue plainValue) - { - if (plainValue is not Dictionary root || - !root.TryGetValue((Text)"values", out var rawValues) || - rawValues is not Null) - { - throw new InvalidCastException(); - } - } - - public override IWorld Execute(IActionContext context) - { - GasTracer.UseGas(1); - - var world = context.PreviousState; - var guildRepository = new GuildRepository(world, context); - var guildAddress = guildRepository.GetJoinedGuild(GuildConfig.PlanetariumGuildOwner); - if (guildAddress is not { } planetariumGuildAddress) - { - throw new InvalidOperationException("The planetarium guild not exists"); - } - - var planetariumGuild = guildRepository.GetGuild( - planetariumGuildAddress); - - var validatorRepository = new ValidatorRepository(guildRepository); - var validatorDelegatee = validatorRepository.GetValidatorDelegatee( - planetariumGuild.ValidatorAddress); - - var validatorSet = world.GetValidatorSet(); - - if (!validatorSet.ContainsPublicKey(validatorDelegatee.PublicKey)) - { - throw new InvalidOperationException( - "The planetarium validator is not in the validator set."); - } - - if (validatorDelegatee.IsActive) - { - throw new InvalidOperationException( - "The planetarium validator is already active."); - } - - validatorDelegatee.Activate(); - validatorRepository.SetValidatorDelegatee(validatorDelegatee); - - guildRepository.UpdateWorld(validatorRepository.World); - var guildDelegatee = guildRepository.GetGuildDelegatee( - planetariumGuild.ValidatorAddress); - guildDelegatee.Activate(); - guildRepository.SetGuildDelgatee(guildDelegatee); - - return guildRepository.World; - } - } -} diff --git a/integrations/javascript/@planetarium/lib9c/src/actions/migrate_delegation.ts b/integrations/javascript/@planetarium/lib9c/src/actions/migrate_delegation.ts deleted file mode 100644 index 4eec55ee3b..0000000000 --- a/integrations/javascript/@planetarium/lib9c/src/actions/migrate_delegation.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { Address } from "@planetarium/account"; -import { BencodexDictionary, type Value } from "@planetarium/bencodex"; -import { PolymorphicAction } from "./common.js"; - -export type MigrateDelegationArgs = { - target: Address; -}; - -export class MigrateDelegation extends PolymorphicAction { - protected readonly type_id: string = "migrate_delegation"; - - private readonly target: Address; - - constructor({ target }: MigrateDelegationArgs) { - super(); - - this.target = target; - } - - protected plain_value(): Value { - const targetKey = "t" as const; - - return new BencodexDictionary([[targetKey, this.target.toBytes()]]); - } -} diff --git a/integrations/javascript/@planetarium/lib9c/src/actions/migrate_planetarium_guild.ts b/integrations/javascript/@planetarium/lib9c/src/actions/migrate_planetarium_guild.ts deleted file mode 100644 index f8a772c07e..0000000000 --- a/integrations/javascript/@planetarium/lib9c/src/actions/migrate_planetarium_guild.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Value } from "@planetarium/bencodex"; -import { PolymorphicAction } from "./common.js"; - -export class MigratePlanetariumGuild extends PolymorphicAction { - protected readonly type_id: string = "migrate_planetarium_guild"; - - protected plain_value(): Value { - return null; - } -} diff --git a/integrations/javascript/@planetarium/lib9c/src/index.ts b/integrations/javascript/@planetarium/lib9c/src/index.ts index b2b3cbdc85..557a195ae0 100644 --- a/integrations/javascript/@planetarium/lib9c/src/index.ts +++ b/integrations/javascript/@planetarium/lib9c/src/index.ts @@ -63,11 +63,6 @@ export { MakeGuild, type MakeGuildArgs, } from "./actions/make_guild.js"; -export { MigratePlanetariumGuild } from "./actions/migrate_planetarium_guild.js"; -export { - MigrateDelegation, - type MigrateDelegationArgs, -} from "./actions/migrate_delegation.js"; export { MintAssets, type MintAssetsArgs,