public override void Render(IActionContext context, IAccountStateDelta nextStates) { var agent = Agent.instance; var count = (long?)nextStates.GetState(context.Signer) ?? 0; var rankingState = (RankingState)nextStates.GetState(RankingState.Address) ?? new RankingState(); agent.RunOnMainThread(() => { Game.OnCountUpdated.Invoke(count); }); agent.RunOnMainThread(() => { Game.OnRankUpdated.Invoke(rankingState); }); }
public static bool TryGetAvatarState( this IAccountStateDelta states, Address agentAddress, Address avatarAddress, out AvatarState avatarState ) { avatarState = null; var value = states.GetState(avatarAddress); if (value is null) { return(false); } try { var serializedAvatar = (Dictionary)value; if (serializedAvatar["agentAddress"].ToAddress() != agentAddress) { return(false); } avatarState = new AvatarState(serializedAvatar); return(true); } catch (InvalidCastException) { return(false); } catch (KeyNotFoundException) { return(false); } }
public static CombinationSlotState GetCombinationSlotState(this IAccountStateDelta states, Address avatarAddress, int index) { var address = avatarAddress.Derive( string.Format( CultureInfo.InvariantCulture, CombinationSlotState.DeriveFormat, index ) ); var value = states.GetState(address); if (value is null) { Log.Warning("No combination slot state ({0})", address.ToHex()); return(null); } try { return(new CombinationSlotState((Dictionary)value)); } catch (Exception e) { Log.Error(e, $"Unexpected error occurred during {nameof(GetCombinationSlotState)}()"); throw; } }
public static AvatarState GetAvatarState(this IAccountStateDelta states, Address address) { var serializedAvatar = states.GetState(address); if (serializedAvatar is null) { Log.Warning("No avatar state ({AvatarAddress})", address.ToHex()); return(null); } try { return(new AvatarState((Bencodex.Types.Dictionary)serializedAvatar)); } catch (InvalidCastException e) { Log.Error( e, "Invalid avatar state ({AvatarAddress}): {SerializedAvatar}", address.ToHex(), serializedAvatar ); return(null); } }
public static AgentState GetAgentState(this IAccountStateDelta states, Address address) { var serializedAgent = states.GetState(address); if (serializedAgent is null) { Log.Warning("No agent state ({0})", address.ToHex()); return(null); } try { return(new AgentState((Bencodex.Types.Dictionary)serializedAgent)); } catch (InvalidCastException e) { Log.Error( e, "Invalid agent state ({0}): {1}", address.ToHex(), serializedAgent ); return(null); } }
private void SetStates( Block <T> block, IReadOnlyList <ActionEvaluation <T> > actionEvaluations) { HashDigest <SHA256> blockHash = block.Hash; IAccountStateDelta lastStates = actionEvaluations.Count > 0 ? actionEvaluations[actionEvaluations.Count - 1].OutputStates : null; ImmutableHashSet <Address> updatedAddresses = actionEvaluations.Select( a => a.OutputStates.UpdatedAddresses ).Aggregate( ImmutableHashSet <Address> .Empty, (a, b) => a.Union(b) ); ImmutableDictionary <Address, object> totalDelta = updatedAddresses.Select( a => new KeyValuePair <Address, object>( a, lastStates?.GetState(a) ) ).ToImmutableDictionary(); Store.SetBlockStates( blockHash, new AddressStateMap(totalDelta) ); var chainId = Id.ToString(); Store.StoreStateReference(chainId, updatedAddresses, block); Store.IncreaseTxNonce(chainId, block); }
internal void SetStates( Block <T> block, IReadOnlyList <ActionEvaluation> actionEvaluations, bool buildStateReferences ) { HashDigest <SHA256> blockHash = block.Hash; IAccountStateDelta lastStates = actionEvaluations.Count > 0 ? actionEvaluations[actionEvaluations.Count - 1].OutputStates : null; ImmutableHashSet <Address> updatedAddresses = actionEvaluations.Select( a => a.OutputStates.UpdatedAddresses ).Aggregate( ImmutableHashSet <Address> .Empty, (a, b) => a.Union(b) ); ImmutableDictionary <Address, object> totalDelta = updatedAddresses.Select( a => new KeyValuePair <Address, object>( a, lastStates?.GetState(a) ) ).ToImmutableDictionary(); Store.SetBlockStates( blockHash, new AddressStateMap(totalDelta) ); if (buildStateReferences) { Store.StoreStateReference(Id, updatedAddresses, block.Hash, block.Index); } }
public static bool TryGetAvatarStateV2( this IAccountStateDelta states, Address agentAddress, Address avatarAddress, out AvatarState avatarState ) { avatarState = null; if (states.GetState(avatarAddress) is Dictionary serializedAvatar) { try { if (serializedAvatar[AgentAddressKey].ToAddress() != agentAddress) { return(false); } avatarState = GetAvatarStateV2(states, avatarAddress); return(true); } catch (Exception e) { // BackWardCompatible. if (e is KeyNotFoundException || e is FailedLoadStateException) { return(states.TryGetAvatarState(agentAddress, avatarAddress, out avatarState)); } return(false); } } return(false); }
public static WeeklyArenaState GetWeeklyArenaState(this IAccountStateDelta states, Address address) { var iValue = states.GetState(address); if (iValue is null) { Log.Warning("No weekly arena state ({0})", address.ToHex()); return(null); } try { return(new WeeklyArenaState(iValue)); } catch (InvalidCastException e) { Log.Error( e, "Invalid weekly arena state ({0}): {1}", address.ToHex(), iValue ); return(null); } }
public override void Render(IActionContext ctx, IAccountStateDelta nextStates) { var agent = Agent.instance; var count = (long)((Integer)nextStates.GetState(ctx.Signer)); var rankingState = new RankingState( (Bencodex.Types.Dictionary)nextStates.GetState(RankingState.Address) ); agent.RunOnMainThread(() => { Game.OnCountUpdated.Invoke(count); }); agent.RunOnMainThread(() => { Game.OnRankUpdated.Invoke(rankingState); }); }
public IAccountStateDelta Execute(IActionContext ctx) { IAccountStateDelta states = ctx.PreviousStates; int previousReward = (int?)states?.GetState(ctx.Miner) ?? 0; int reward = previousReward + Reward; return(states.SetState(ctx.Miner, reward)); }
public static ShopState GetShopState(this IAccountStateDelta states) { var value = states.GetState(Addresses.Shop); if (value is null) { throw new FailedLoadStateException(nameof(ShopState)); } return(new ShopState((Dictionary)value)); }
public static AvatarState GetAvatarStateV2(this IAccountStateDelta states, Address address) { if (!(states.GetState(address) is Dictionary serializedAvatar)) { Log.Warning("No avatar state ({AvatarAddress})", address.ToHex()); return(null); } string[] keys = { LegacyInventoryKey, LegacyWorldInformationKey, LegacyQuestListKey, }; foreach (var key in keys) { var keyAddress = address.Derive(key); var serialized = states.GetState(keyAddress); if (serialized is null) { throw new FailedLoadStateException($"failed to load {key}."); } serializedAvatar = serializedAvatar.SetItem(key, serialized); } try { return(new AvatarState(serializedAvatar)); } catch (InvalidCastException e) { Log.Error( e, "Invalid avatar state ({AvatarAddress}): {SerializedAvatar}", address.ToHex(), serializedAvatar ); return(null); } }
public static RankingState0 GetRankingState0(this IAccountStateDelta states) { var value = states.GetState(Addresses.Ranking); if (value is null) { throw new FailedLoadStateException(nameof(RankingState0)); } return(new RankingState0((Dictionary)value)); }
// TODO: This method should be a part of IAccountStateDelta interface // and the current implementation should be its default implementation // (when C# 8 comes out). Although the current implementation is // an only way using only generic methods/properties that // the IAccountStateDelta interface exposes, it is quite inefficient // when an implementing class maintains their own dirty dictionary. // (See also AccountStateDeltaImpl.UpdatedStates field.) public static IImmutableDictionary <Address, object> GetUpdatedStates( this IAccountStateDelta delta ) { return(delta.UpdatedAddresses.Select(address => new KeyValuePair <Address, object>( address, delta.GetState(address) ) ).ToImmutableDictionary()); }
internal static IImmutableDictionary <Address, IValue?> GetUpdatedStates( this IAccountStateDelta delta ) { return(delta.StateUpdatedAddresses.Select(address => new KeyValuePair <Address, IValue?>( address, delta.GetState(address) ) ).ToImmutableDictionary()); }
public void GetSetState() { IAccountStateDelta init = new AccountStateDeltaImpl(GetState); IAccountStateDelta a = init.SetState(_addr[0], "A"); Assert.Equal("A", a.GetState(_addr[0])); Assert.Equal("a", init.GetState(_addr[0])); Assert.Equal("b", a.GetState(_addr[1])); Assert.Equal("b", init.GetState(_addr[1])); Assert.Null(a.GetState(_addr[2])); Assert.Null(init.GetState(_addr[2])); Assert.Equal( new[] { _addr[0] }.ToImmutableHashSet(), a.UpdatedAddresses ); Assert.Empty(init.UpdatedAddresses); IAccountStateDelta b = a.SetState(_addr[0], "z"); Assert.Equal("z", b.GetState(_addr[0])); Assert.Equal("A", a.GetState(_addr[0])); Assert.Equal("a", init.GetState(_addr[0])); Assert.Equal("b", b.GetState(_addr[1])); Assert.Equal("b", a.GetState(_addr[1])); Assert.Null(b.GetState(_addr[2])); Assert.Null(a.GetState(_addr[2])); Assert.Equal( new[] { _addr[0] }.ToImmutableHashSet(), a.UpdatedAddresses ); Assert.Empty(init.UpdatedAddresses); IAccountStateDelta c = b.SetState(_addr[0], "a"); Assert.Equal("a", c.GetState(_addr[0])); Assert.Equal("z", b.GetState(_addr[0])); Assert.Empty(c.UpdatedAddresses); Assert.Empty(init.UpdatedAddresses); }
public IAccountStateDelta WeeklyArenaRankingBoard2(IActionContext ctx, IAccountStateDelta states) { var gameConfigState = states.GetGameConfigState(); var index = Math.Max((int)ctx.BlockIndex / gameConfigState.WeeklyArenaInterval, 0); var weeklyAddress = WeeklyArenaState.DeriveAddress(index); var rawWeekly = (Dictionary)states.GetState(weeklyAddress); var nextIndex = index + 1; var nextWeekly = states.GetWeeklyArenaState(nextIndex); if (nextWeekly is null) { nextWeekly = new WeeklyArenaState(nextIndex); states = states.SetState(nextWeekly.address, nextWeekly.Serialize()); } var resetIndex = rawWeekly["resetIndex"].ToLong(); // Beginning block of a new weekly arena. if (ctx.BlockIndex % gameConfigState.WeeklyArenaInterval == 0 && index > 0) { var prevWeeklyAddress = WeeklyArenaState.DeriveAddress(index - 1); var rawPrevWeekly = (Dictionary)states.GetState(prevWeeklyAddress); if (!rawPrevWeekly["ended"].ToBoolean()) { rawPrevWeekly = rawPrevWeekly.SetItem("ended", true.Serialize()); var weekly = new WeeklyArenaState(rawWeekly); var prevWeekly = new WeeklyArenaState(rawPrevWeekly); weekly.Update(prevWeekly, ctx.BlockIndex); states = states.SetState(prevWeeklyAddress, rawPrevWeekly); states = states.SetState(weeklyAddress, weekly.Serialize()); } } else if (ctx.BlockIndex - resetIndex >= gameConfigState.DailyArenaInterval) { var weekly = new WeeklyArenaState(rawWeekly); weekly.ResetCount(ctx.BlockIndex); states = states.SetState(weeklyAddress, weekly.Serialize()); } return(states); }
public static bool TryGetState <T>(this IAccountStateDelta states, Address address, out T result) where T : IValue { IValue raw = states.GetState(address); if (raw is T v) { result = v; return(true); } result = default; return(false); }
public IAccountStateDelta Execute(IActionContext ctx) { IAccountStateDelta states = ctx.PreviousStates; string rewardRecord = (string)states.GetState(RewardRecordAddress); rewardRecord = rewardRecord is null ? ctx.Miner.ToString() : $"{rewardRecord},{ctx.Miner}"; states = states.SetState(RewardRecordAddress, rewardRecord); int previousReward = (int?)states?.GetState(ctx.Miner) ?? 0; int reward = previousReward + Reward; return(states.SetState(ctx.Miner, reward)); }
public IAccountStateDelta Execute(IActionContext ctx) { IAccountStateDelta states = ctx.PreviousStates; string rewardRecord = (Text?)states.GetState(RewardRecordAddress); rewardRecord = rewardRecord is null ? ctx.Miner.ToString() : $"{rewardRecord},{ctx.Miner}"; states = states.SetState(RewardRecordAddress, (Text)rewardRecord); IValue tempQualifier1 = states?.GetState(ctx.Miner); int previousReward = tempQualifier1 is Integer i ? (int)i.Value : 0; int reward = previousReward + Reward; return(states.SetState(ctx.Miner, (Integer)reward)); }
public override IAccountStateDelta Execute(IActionContext context) { IAccountStateDelta state = context.PreviousStates; var address = Address.Derive(ActivationKey.DeriveKey); if (context.Rehearsal) { return(state .SetState(address, MarkChanged)); } if (!(state.GetState(address) is null)) { throw new AlreadyActivatedException($"{address} is already activated."); } CheckPermission(context); return(state.SetState(address, true.Serialize())); }
public static RedeemCodeState GetRedeemCodeState(this IAccountStateDelta states) { var value = states.GetState(RedeemCodeState.Address); if (value is null) { Log.Warning("RedeemCodeState is null. ({0})", RedeemCodeState.Address.ToHex()); return(null); } try { return(new RedeemCodeState((Dictionary)value)); } catch (Exception e) { Log.Error(e, $"Unexpected error occurred during {nameof(GetCombinationSlotState)}()"); throw; } }
public override IAccountStateDelta Execute(IActionContext context) { IImmutableSet <string> usedWeapons = ImmutableHashSet <string> .Empty; IImmutableSet <string> targets = ImmutableHashSet <string> .Empty; IAccountStateDelta previousStates = context.PreviousStates; object value = previousStates.GetState(TargetAddress); if (!ReferenceEquals(value, null)) { var previousResult = BattleResult.FromBencodex((Bencodex.Types.Dictionary)value); usedWeapons = previousResult.UsedWeapons; targets = previousResult.Targets; } usedWeapons = usedWeapons.Add(Weapon); targets = targets.Add(Target); var result = new BattleResult(usedWeapons, targets); return(previousStates.SetState(TargetAddress, result.ToBencodex())); }
public static bool TryGetState <T>(this IAccountStateDelta states, Address address, out T result) where T : IValue { IValue raw = states.GetState(address); if (raw is T v) { result = v; return(true); } Log.Error( "Expected a {0}, but got invalid state ({1}): ({2}) {3}", typeof(T).Name, address.ToHex(), raw?.GetType().Name, raw ); result = default; return(false); }
public static string GetSheetCsv <T>(this IAccountStateDelta states) where T : ISheet, new() { var address = Addresses.GetSheetAddress <T>(); var value = states.GetState(address); if (value is null) { Log.Warning($"{nameof(T)} is null ({0})", address.ToHex()); throw new FailedLoadStateException(nameof(T)); } try { return(value.ToDotnetString()); } catch (Exception e) { Log.Error(e, $"Unexpected error occurred during {nameof(T)}()"); throw; } }
public IAccountStateDelta ResetChallengeCount(IActionContext ctx, IAccountStateDelta states) { var gameConfigState = states.GetGameConfigState(); var index = Math.Max((int)ctx.BlockIndex / gameConfigState.WeeklyArenaInterval, 0); var weeklyAddress = WeeklyArenaState.DeriveAddress(index); var rawWeekly = (Dictionary)states.GetState(weeklyAddress); var resetIndex = rawWeekly["resetIndex"].ToLong(); if (ctx.BlockIndex - resetIndex >= gameConfigState.DailyArenaInterval) { var weekly = new WeeklyArenaState(rawWeekly); if (resetIndex >= RankingBattle.UpdateTargetBlockIndex) { // Reset count each ArenaInfo. weekly.ResetIndex = ctx.BlockIndex; var listAddress = weeklyAddress.Derive("address_list"); if (states.TryGetState(listAddress, out List rawList)) { var addressList = rawList.ToList(StateExtensions.ToAddress); foreach (var address in addressList) { var infoAddress = weeklyAddress.Derive(address.ToByteArray()); if (states.TryGetState(infoAddress, out Dictionary rawInfo)) { var info = new ArenaInfo(rawInfo); info.ResetCount(); states = states.SetState(infoAddress, info.Serialize()); } } } } else { // Run legacy ResetCount. weekly.ResetCount(ctx.BlockIndex); } states = states.SetState(weeklyAddress, weekly.Serialize()); } return(states); }
public static IEnumerable <GoldDistribution> GetGoldDistribution( this IAccountStateDelta states) { var value = states.GetState(Addresses.GoldDistribution); if (value is null) { Log.Warning($"{nameof(GoldDistribution)} is null ({0})", Addresses.GoldDistribution.ToHex()); return(null); } try { var goldDistributions = (Bencodex.Types.List)value; return(goldDistributions.Select(v => new GoldDistribution(v))); } catch (Exception e) { Log.Error(e, $"Unexpected error occurred during {nameof(GetGoldDistribution)}()"); throw; } }
private void EvaluateActions(Block <T> block) { HashDigest <SHA256>?prevHash = block.PreviousHash; IAccountStateDelta[] deltas = block.EvaluateActions(address => { IImmutableDictionary <Address, object> result = GetStates(new[] { address }, prevHash); try { return(result[address]); } catch (KeyNotFoundException) { return(null); } }).ToArray(); IAccountStateDelta lastStates = deltas.LastOrDefault(); ImmutableHashSet <Address> updatedAddresses = deltas.Select(d => d.UpdatedAddresses).Aggregate( ImmutableHashSet <Address> .Empty, (a, b) => a.Union(b) ); IImmutableDictionary <Address, object> totalDelta = updatedAddresses.Select( a => new KeyValuePair <Address, object>( a, lastStates?.GetState(a) ) ).ToImmutableDictionary(); Store.SetBlockStates( block.Hash, new AddressStateMap(totalDelta) ); }
public override IAccountStateDelta Execute(IActionContext context) { IAccountStateDelta state = context.PreviousStates; Address activatedAddress = context.Signer.Derive(ActivationKey.DeriveKey); if (context.Rehearsal) { return(state .SetState(activatedAddress, MarkChanged) .SetState(PendingAddress, MarkChanged)); } if (!(state.GetState(activatedAddress) is null)) { throw new AlreadyActivatedException($"{context.Signer} already activated."); } if (!state.TryGetState(PendingAddress, out Dictionary pendingAsDict)) { throw new PendingActivationDoesNotExistsException(PendingAddress); } var pending = new PendingActivationState(pendingAsDict); if (pending.Verify(this)) { // We left this log message to track activation history. // Please delete it if we have an API for evaluation results on the Libplanet side. Log.Information("{pendingAddress} is activated by {signer} now.", pending.address, context.Signer); return(state .SetState(activatedAddress, true.Serialize()) .SetState(pending.address, new Bencodex.Types.Null())); } else { throw new InvalidSignatureException(pending, Signature); } }