From 5077e4226932acfc86dd1428808ad051fa3a0d38 Mon Sep 17 00:00:00 2001 From: Jiri Date: Tue, 15 Oct 2024 13:24:23 +0200 Subject: [PATCH 01/11] Changes --- app/export.go | 2 +- app/upgrade_0_11_4_reconciliation.go | 6 +- app/upgrade_cudos.go | 250 +++++++++++++-------------- app/upgrade_cudos_distribution.go | 8 +- app/upgrade_v_11_4_manifest.go | 4 +- app/upgrade_v_11_4_network_config.go | 18 +- app/utils.go | 2 +- cmd/fetchd/cmd/cudos_merge.go | 72 ++++++++ 8 files changed, 217 insertions(+), 145 deletions(-) diff --git a/app/export.go b/app/export.go index a744e5496..4af90b043 100644 --- a/app/export.go +++ b/app/export.go @@ -54,7 +54,7 @@ func (app *App) ExportAppStateAndValidators( func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false - // check if there is a allowed address list + // check if there is a allowed Address list if len(jailAllowedAddrs) > 0 { applyAllowedAddrs = true } diff --git a/app/upgrade_0_11_4_reconciliation.go b/app/upgrade_0_11_4_reconciliation.go index ba93ba118..464b6967c 100644 --- a/app/upgrade_0_11_4_reconciliation.go +++ b/app/upgrade_0_11_4_reconciliation.go @@ -205,7 +205,7 @@ func (app *App) WithdrawReconciliationBalances(ctx types.Context, networkInfo *N } if !app.AccountKeeper.HasAccount(ctx, landingAddr) { - return fmt.Errorf("landing address does not exist") + return fmt.Errorf("landing Address does not exist") } transfers := UpgradeReconciliationTransfers{} @@ -480,11 +480,11 @@ func (app *App) DeleteContractStates(ctx types.Context, networkInfo *NetworkConf return nil } -// getContractData returns the contract address, info, and states for a given contract address +// getContractData returns the contract Address, info, and states for a given contract Address func (app *App) getContractData(ctx types.Context, contractAddr string) (*types.AccAddress, *types.KVStore, *prefix.Store, error) { addr, err := types.AccAddressFromBech32(contractAddr) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid contract address: %v", err) + return nil, nil, nil, fmt.Errorf("invalid contract Address: %v", err) } store := ctx.KVStore(app.keys[wasmTypes.StoreKey]) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index 780eedc0a..c53f60a4a 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -243,9 +243,9 @@ func GetAccPrefix(jsonData map[string]interface{}) (string, error) { continue } - prefix, _, err := bech32.DecodeAndConvert(accountInfo.address) + prefix, _, err := bech32.DecodeAndConvert(accountInfo.Address) if err != nil { - lastErr = fmt.Errorf("failed to decode address %s: %w", accountInfo.address, err) + lastErr = fmt.Errorf("failed to decode Address %s: %w", accountInfo.Address, err) continue } @@ -360,19 +360,19 @@ func ParseGenesisData(jsonData map[string]interface{}, genDoc *tmtypes.GenesisDo type AccountInfo struct { // Base - pubkey cryptotypes.PubKey - address string - rawAddress sdk.AccAddress + Pubkey cryptotypes.PubKey + Address string + RawAddress sdk.AccAddress // Bank - balance sdk.Coins + Balance sdk.Coins // Module - name string + Name string // BaseVesting - endTime int64 - originalVesting sdk.Coins + EndTime int64 + OriginalVesting sdk.Coins //delegated_free //delegated_vesting @@ -380,24 +380,24 @@ type AccountInfo struct { // -- // ContinuousVesting - startTime int64 + StartTime int64 // Custom - accountType AccountType - migrated bool + AccountType AccountType + Migrated bool - rawAccData map[string]interface{} + RawAccData map[string]interface{} } func parseGenesisBaseVesting(baseVestingAccData map[string]interface{}, accountInfo *AccountInfo) error { // Parse specific base vesting account types - accountInfo.endTime = cast.ToInt64(baseVestingAccData["end_time"].(string)) + accountInfo.EndTime = cast.ToInt64(baseVestingAccData["end_time"].(string)) originalVesting, err := getCoinsFromInterfaceSlice(baseVestingAccData["original_vesting"].([]interface{})) if err != nil { return err } - accountInfo.originalVesting = originalVesting + accountInfo.OriginalVesting = originalVesting // Parse inner base account baseAccData := baseVestingAccData["base_account"].(map[string]interface{}) @@ -410,9 +410,9 @@ func parseGenesisBaseVesting(baseVestingAccData map[string]interface{}, accountI } func parseGenesisBaseAccount(baseAccData map[string]interface{}, accountInfo *AccountInfo) error { - accountInfo.address = baseAccData["address"].(string) + accountInfo.Address = baseAccData["address"].(string) - // Parse pubkey + // Parse Pubkey var AccPubKey cryptotypes.PubKey var err error if pk, ok := baseAccData["pub_key"]; ok { @@ -423,12 +423,12 @@ func parseGenesisBaseAccount(baseAccData map[string]interface{}, accountInfo *Ac } } } - accountInfo.pubkey = AccPubKey + accountInfo.Pubkey = AccPubKey - // Get raw address - _, accRawAddr, err := bech32.DecodeAndConvert(accountInfo.address) + // Get raw Address + _, accRawAddr, err := bech32.DecodeAndConvert(accountInfo.Address) - accountInfo.rawAddress = accRawAddr + accountInfo.RawAddress = accRawAddr if err != nil { return err } @@ -452,7 +452,7 @@ func parseGenesisDelayedVestingAccount(accMap map[string]interface{}, accountInf func parseGenesisContinuousVestingAccount(accMap map[string]interface{}, accountInfo *AccountInfo) error { // Specific continuous vesting stuff - accountInfo.startTime = cast.ToInt64(accMap["start_time"].(string)) + accountInfo.StartTime = cast.ToInt64(accMap["start_time"].(string)) baseVestingAccData := accMap["base_vesting_account"].(map[string]interface{}) err := parseGenesisBaseVesting(baseVestingAccData, accountInfo) @@ -475,7 +475,7 @@ func parseGenesisPermanentLockedAccount(accMap map[string]interface{}, accountIn func parseGenesisPeriodicVestingAccount(accMap map[string]interface{}, accountInfo *AccountInfo) error { // Specific periodic stuff - accountInfo.startTime = cast.ToInt64(accMap["start_time"].(string)) + accountInfo.StartTime = cast.ToInt64(accMap["start_time"].(string)) // parse periods // Do we care? @@ -491,7 +491,7 @@ func parseGenesisPeriodicVestingAccount(accMap map[string]interface{}, accountIn func parseGenesisModuleAccount(accMap map[string]interface{}, accountInfo *AccountInfo) error { // Specific module account values - accountInfo.name = accMap["name"].(string) + accountInfo.Name = accMap["name"].(string) // parse inner base account baseAccData := accMap["base_account"].(map[string]interface{}) @@ -504,7 +504,7 @@ func parseGenesisModuleAccount(accMap map[string]interface{}, accountInfo *Accou } func parseGenesisAccount(accMap map[string]interface{}) (*AccountInfo, error) { - accountInfo := AccountInfo{balance: sdk.NewCoins(), migrated: false, rawAccData: accMap} + accountInfo := AccountInfo{Balance: sdk.NewCoins(), Migrated: false, RawAccData: accMap} accType := accMap["@type"] // Extract base account and special values @@ -513,37 +513,37 @@ func parseGenesisAccount(accMap map[string]interface{}) (*AccountInfo, error) { if err != nil { return nil, err } - accountInfo.accountType = ModuleAccountType + accountInfo.AccountType = ModuleAccountType } else if accType == DelayedVestingAccount { err := parseGenesisDelayedVestingAccount(accMap, &accountInfo) if err != nil { return nil, err } - accountInfo.accountType = DelayedVestingAccountType + accountInfo.AccountType = DelayedVestingAccountType } else if accType == ContinuousVestingAccount { err := parseGenesisContinuousVestingAccount(accMap, &accountInfo) if err != nil { return nil, err } - accountInfo.accountType = ContinuousVestingAccountType + accountInfo.AccountType = ContinuousVestingAccountType } else if accType == PermanentLockedAccount { err := parseGenesisPermanentLockedAccount(accMap, &accountInfo) if err != nil { return nil, err } - accountInfo.accountType = PermanentLockedAccountType + accountInfo.AccountType = PermanentLockedAccountType } else if accType == PeriodicVestingAccount { err := parseGenesisPeriodicVestingAccount(accMap, &accountInfo) if err != nil { return nil, err } - accountInfo.accountType = PeriodicVestingAccountType + accountInfo.AccountType = PeriodicVestingAccountType } else if accType == BaseAccount { err := parseGenesisBaseAccount(accMap, &accountInfo) if err != nil { return nil, err } - accountInfo.accountType = BaseAccountType + accountInfo.AccountType = BaseAccountType } else { return nil, fmt.Errorf("unknown account type %s", accType) @@ -567,13 +567,13 @@ func parseGenesisAccounts(jsonData map[string]interface{}, contractAccountMap *O } // Check if not contract or IBC type - if _, exists := contractAccountMap.Get(accountInfo.address); exists { - accountInfo.accountType = ContractAccountType - } else if _, exists := IBCAccountsMap.Get(accountInfo.address); exists { - accountInfo.accountType = IBCAccountType + if _, exists := contractAccountMap.Get(accountInfo.Address); exists { + accountInfo.AccountType = ContractAccountType + } else if _, exists := IBCAccountsMap.Get(accountInfo.Address); exists { + accountInfo.AccountType = IBCAccountType } - accountMap.SetNew(accountInfo.address, accountInfo) + accountMap.SetNew(accountInfo.Address, accountInfo) } // Add balances to accounts map @@ -654,7 +654,7 @@ func (v ValidatorInfo) TokensFromShares(shares sdk.Dec) sdk.Dec { } func parseGenesisValidators(jsonData map[string]interface{}) (*OrderedMap[string, *ValidatorInfo], error) { - // Validator pubkey hex -> ValidatorInfo + // Validator Pubkey hex -> ValidatorInfo validatorInfoMap := NewOrderedMap[string, *ValidatorInfo]() staking := jsonData[stakingtypes.ModuleName].(map[string]interface{}) @@ -766,7 +766,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa currentValidatorInfo := genesisData.Validators.MustGet(validatorOperatorAddress) delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.shares).TruncateInt() - // Move balance to delegator address + // Move balance to delegator Address delegatorBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, delegatorTokens)) if delegatorTokens.IsZero() { @@ -806,7 +806,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa for _, entry := range unbondingDelegation.entries { unbondingDelegationBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, entry.balance)) - // Move unbonding balance from not-bonded pool to delegator address + // Move unbonding balance from not-bonded pool to delegator Address err := moveGenesisBalance(genesisData, genesisData.NotBondedPoolAddress, resolvedDelegatorAddress, unbondingDelegationBalance, "unbonding_delegation", manifest, cudosCfg) if err != nil { return err @@ -822,16 +822,16 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa bondedPool := genesisData.Accounts.MustGet(genesisData.BondedPoolAddress) // TODO: Write to manifest? - err := checkTolerance(bondedPool.balance, maxToleratedRemainingStakingBalance) + err := checkTolerance(bondedPool.Balance, maxToleratedRemainingStakingBalance) if err != nil { - return fmt.Errorf("remaining bonded pool balance %s is too high", bondedPool.balance.String()) + return fmt.Errorf("remaining bonded pool balance %s is too high", bondedPool.Balance.String()) } if logger != nil { - logger.Info("cudos merge: remaining bonded pool balance", "amount", bondedPool.balance.String()) + logger.Info("cudos merge: remaining bonded pool balance", "amount", bondedPool.Balance.String()) } - err = moveGenesisBalance(genesisData, genesisData.BondedPoolAddress, cudosCfg.Config.RemainingStakingBalanceAddr, bondedPool.balance, "remaining_bonded_pool_balance", manifest, cudosCfg) + err = moveGenesisBalance(genesisData, genesisData.BondedPoolAddress, cudosCfg.Config.RemainingStakingBalanceAddr, bondedPool.Balance, "remaining_bonded_pool_balance", manifest, cudosCfg) if err != nil { return err } @@ -840,16 +840,16 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa notBondedPool := genesisData.Accounts.MustGet(genesisData.NotBondedPoolAddress) // TODO: Write to manifest? - err = checkTolerance(notBondedPool.balance, maxToleratedRemainingStakingBalance) + err = checkTolerance(notBondedPool.Balance, maxToleratedRemainingStakingBalance) if err != nil { - return fmt.Errorf("remaining not-bonded pool balance %s is too high", notBondedPool.balance.String()) + return fmt.Errorf("remaining not-bonded pool balance %s is too high", notBondedPool.Balance.String()) } if logger != nil { - logger.Info("cudos merge: remaining not-bonded pool balance", "amount", notBondedPool.balance.String()) + logger.Info("cudos merge: remaining not-bonded pool balance", "amount", notBondedPool.Balance.String()) } - err = moveGenesisBalance(genesisData, genesisData.NotBondedPoolAddress, cudosCfg.Config.RemainingStakingBalanceAddr, notBondedPool.balance, "remaining_not_bonded_pool_balance", manifest, cudosCfg) + err = moveGenesisBalance(genesisData, genesisData.NotBondedPoolAddress, cudosCfg.Config.RemainingStakingBalanceAddr, notBondedPool.Balance, "remaining_not_bonded_pool_balance", manifest, cudosCfg) if err != nil { return err } @@ -939,16 +939,16 @@ func handleCommunityPoolBalance(ctx sdk.Context, app *App, genesisData *GenesisD } if cudosCfg.Config.CommunityPoolBalanceDestAddr == "" { - // If community pool balance destination address is not we move community pool balance to destination chain community pool + // If community pool balance destination Address is not we move community pool balance to destination chain community pool - // Mint balance to distribution leftover address - err = migrateToAccount(ctx, app, minttypes.ModuleName, RemainingDistributionBalanceAccount.rawAddress, communityPoolBalance, convertedCommunityPoolBalance, "community_pool_balance", manifest) + // Mint balance to distribution leftover Address + err = migrateToAccount(ctx, app, minttypes.ModuleName, RemainingDistributionBalanceAccount.RawAddress, communityPoolBalance, convertedCommunityPoolBalance, "community_pool_balance", manifest) if err != nil { return err } // Move balance to destination chain community pool - err = app.DistrKeeper.FundCommunityPool(ctx, convertedCommunityPoolBalance, RemainingDistributionBalanceAccount.rawAddress) + err = app.DistrKeeper.FundCommunityPool(ctx, convertedCommunityPoolBalance, RemainingDistributionBalanceAccount.RawAddress) if err != nil { return err } @@ -961,7 +961,7 @@ func handleCommunityPoolBalance(ctx sdk.Context, app *App, genesisData *GenesisD } else { // If community pool destination balance is set we move community pool tokens there. - err = moveGenesisBalance(genesisData, RemainingDistributionBalanceAccount.address, cudosCfg.Config.CommunityPoolBalanceDestAddr, communityPoolBalance, "community_pool_balance", manifest, cudosCfg) + err = moveGenesisBalance(genesisData, RemainingDistributionBalanceAccount.Address, cudosCfg.Config.CommunityPoolBalanceDestAddr, communityPoolBalance, "community_pool_balance", manifest, cudosCfg) if err != nil { return fmt.Errorf("failed to move community pool balance %w", err) } @@ -1084,7 +1084,7 @@ func withdrawGenesisContractBalances(genesisData *GenesisData, manifest *Upgrade contractBalance, contractBalancePresent := genesisData.Accounts.Get(contractAddress) if contractBalancePresent { - err := moveGenesisBalance(genesisData, contractAddress, resolvedAddress, contractBalance.balance, "contract_balance", manifest, cudosCfg) + err := moveGenesisBalance(genesisData, contractAddress, resolvedAddress, contractBalance.Balance, "contract_balance", manifest, cudosCfg) if err != nil { return err } @@ -1126,15 +1126,15 @@ func ensureAccount(addrStr string, genesisAccountsMap *OrderedMap[string, *Accou return nil } - _, accRawAddress, err := bech32.DecodeAndConvert(addrStr) + _, accRawAddresss, err := bech32.DecodeAndConvert(addrStr) if err != nil { return err } accountInfoEntry := &AccountInfo{ - rawAddress: accRawAddress, - address: addrStr, - accountType: BaseAccountType, + RawAddress: accRawAddresss, + Address: addrStr, + AccountType: BaseAccountType, } genesisAccountsMap.Set(addrStr, accountInfoEntry) @@ -1156,7 +1156,7 @@ func fillGenesisBalancesToAccountsMap(jsonData map[string]interface{}, genesisAc addr := balance.(map[string]interface{})["address"] if addr == nil { - return fmt.Errorf("failed to get address") + return fmt.Errorf("failed to get Address") } addrStr := addr.(string) @@ -1181,7 +1181,7 @@ func fillGenesisBalancesToAccountsMap(jsonData map[string]interface{}, genesisAc return err } accountInfoEntry := genesisAccountsMap.MustGet(addrStr) - accountInfoEntry.balance = sdkBalance + accountInfoEntry.Balance = sdkBalance genesisAccountsMap.Set(addrStr, accountInfoEntry) } @@ -1191,7 +1191,7 @@ func fillGenesisBalancesToAccountsMap(jsonData map[string]interface{}, genesisAc func genesisUpgradeWithdrawIBCChannelsBalances(genesisData *GenesisData, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error { if cudosCfg.Config.IbcTargetAddr == "" { - return fmt.Errorf("no IBC withdrawal address set") + return fmt.Errorf("no IBC withdrawal Address set") } ibcWithdrawalAddress := cudosCfg.Config.IbcTargetAddr @@ -1208,7 +1208,7 @@ func genesisUpgradeWithdrawIBCChannelsBalances(genesisData *GenesisData, cudosCf var channelBalance sdk.Coins if IBCAccountExists { - channelBalance = IBCaccount.balance + channelBalance = IBCaccount.Balance err := moveGenesisBalance(genesisData, IBCaccountAddress, ibcWithdrawalAddress, channelBalance, "ibc_balance", manifest, cudosCfg) if err != nil { return err @@ -1328,10 +1328,10 @@ func resolveIfContractAddressWithFallback(address string, contracts *OrderedMap[ } if resolvedAddress == nil || strings.TrimSpace(*resolvedAddress) == "" { - // Use fallback address + // Use fallback Address return cudosCfg.Config.ContractDestinationFallbackAddr, nil } else { - // Use resolved address + // Use resolved Address return *resolvedAddress, nil } } @@ -1345,12 +1345,12 @@ func resolveIfContractAddress(address string, contracts *OrderedMap[string, *Con if !exists { return &address, nil } - // If the contract has an admin that is not itself, continue with the admin address. + // If the contract has an admin that is not itself, continue with the admin Address. if len(creatorsMap) == 0 && len(adminsMap) < RecursionDepthLimit && contractInfo.Admin != "" && contractInfo.Admin != address && !adminsMap[contractInfo.Admin] { adminsMap[contractInfo.Admin] = true address = contractInfo.Admin } else if len(creatorsMap) < RecursionDepthLimit && contractInfo.Creator != "" && !creatorsMap[contractInfo.Creator] { - // Otherwise, if the creator is present, continue with the creator address. + // Otherwise, if the creator is present, continue with the creator Address. creatorsMap[contractInfo.Creator] = true address = contractInfo.Creator } else { @@ -1380,7 +1380,7 @@ func decodePubKeyFromMap(pubKeyMap map[string]interface{}) (cryptotypes.PubKey, // Ensure the byte slice is the correct length for a secp256k1 public key if len(keyBytes) != secp256k1.PubKeySize { - return nil, fmt.Errorf("invalid pubkey length: got %d, expected %d", len(keyBytes), secp256k1.PubKeySize) + return nil, fmt.Errorf("invalid Pubkey length: got %d, expected %d", len(keyBytes), secp256k1.PubKeySize) } pubKey := secp256k1.PubKey{ @@ -1401,7 +1401,7 @@ func decodePubKeyFromMap(pubKeyMap map[string]interface{}) (cryptotypes.PubKey, // Ensure the byte slice is the correct length for an ed25519 public key if len(keyBytes) != ed25519.PubKeySize { - return nil, fmt.Errorf("invalid pubkey length: got %d, expected %d", len(keyBytes), ed25519.PubKeySize) + return nil, fmt.Errorf("invalid Pubkey length: got %d, expected %d", len(keyBytes), ed25519.PubKeySize) } pubKey := ed25519.PubKey{ @@ -1446,7 +1446,7 @@ func decodePubKeyFromMap(pubKeyMap map[string]interface{}) (cryptotypes.PubKey, func getNewBaseAccount(ctx sdk.Context, app *App, accountInfo *AccountInfo) (*authtypes.BaseAccount, error) { // Create new account newAccNumber := app.AccountKeeper.GetNextAccountNumber(ctx) - newBaseAccount := authtypes.NewBaseAccount(accountInfo.rawAddress, accountInfo.pubkey, newAccNumber, 0) + newBaseAccount := authtypes.NewBaseAccount(accountInfo.RawAddress, accountInfo.Pubkey, newAccNumber, 0) return newBaseAccount, nil } @@ -1497,11 +1497,11 @@ func markAccountAsMigrated(genesisData *GenesisData, accountAddress string) erro return fmt.Errorf("genesis account %s not found", accountAddress) } - if AccountInfoRecord.migrated { + if AccountInfoRecord.Migrated { return fmt.Errorf("genesis account %s already migrated", accountAddress) } - AccountInfoRecord.migrated = true + AccountInfoRecord.Migrated = true genesisData.Accounts.Set(accountAddress, AccountInfoRecord) @@ -1629,18 +1629,18 @@ func moveGenesisBalance(genesisData *GenesisData, fromAddress, toAddress string, return err } - if toAcc := genesisData.Accounts.MustGet(toAddress); toAcc.migrated { + if toAcc := genesisData.Accounts.MustGet(toAddress); toAcc.Migrated { return fmt.Errorf("genesis account %s already migrated", toAddress) } - if fromAcc := genesisData.Accounts.MustGet(fromAddress); fromAcc.migrated { + if fromAcc := genesisData.Accounts.MustGet(fromAddress); fromAcc.Migrated { return fmt.Errorf("genesis account %s already migrated", fromAddress) } genesisToBalance := genesisData.Accounts.MustGet(toAddress) genesisFromBalance := genesisData.Accounts.MustGet(fromAddress) - genesisToBalance.balance = genesisToBalance.balance.Add(amount...) - genesisFromBalance.balance = genesisFromBalance.balance.Sub(amount) + genesisToBalance.Balance = genesisToBalance.Balance.Add(amount...) + genesisFromBalance.Balance = genesisFromBalance.Balance.Sub(amount) genesisData.Accounts.Set(toAddress, genesisToBalance) genesisData.Accounts.Set(fromAddress, genesisFromBalance) @@ -1657,13 +1657,13 @@ func createGenesisBalance(genesisData *GenesisData, toAddress string, amount sdk return err } - if toAcc := genesisData.Accounts.MustGet(toAddress); toAcc.migrated { + if toAcc := genesisData.Accounts.MustGet(toAddress); toAcc.Migrated { return fmt.Errorf("genesis account %s already migrated", toAddress) } genesisToBalance := genesisData.Accounts.MustGet(toAddress) - genesisToBalance.balance = genesisToBalance.balance.Add(amount...) + genesisToBalance.Balance = genesisToBalance.Balance.Add(amount...) genesisData.Accounts.Set(toAddress, genesisToBalance) @@ -1675,15 +1675,15 @@ func createGenesisBalance(genesisData *GenesisData, toAddress string, amount sdk func removeGenesisBalance(genesisData *GenesisData, address string, amount sdk.Coins, memo string, manifest *UpgradeManifest) error { // Check if fromAddress exists if _, ok := genesisData.Accounts.Get(address); !ok { - return fmt.Errorf("address %s does not exist in genesis balances", address) + return fmt.Errorf("Address %s does not exist in genesis balances", address) } - if acc := genesisData.Accounts.MustGet(address); acc.migrated { + if acc := genesisData.Accounts.MustGet(address); acc.Migrated { return fmt.Errorf("genesis account %s already migrated", address) } genesisAccount := genesisData.Accounts.MustGet(address) - genesisAccount.balance = genesisAccount.balance.Sub(amount) + genesisAccount.Balance = genesisAccount.Balance.Sub(amount) genesisData.Accounts.Set(address, genesisAccount) @@ -1697,13 +1697,13 @@ func GetAddressByName(genesisAccounts *OrderedMap[string, *AccountInfo], name st for _, accAddress := range genesisAccounts.Keys() { acc := genesisAccounts.MustGet(accAddress) - if acc.name == name { + if acc.Name == name { return accAddress, nil } } - return "", fmt.Errorf("address not found in genesis accounts: %s", name) + return "", fmt.Errorf("Address not found in genesis accounts: %s", name) } func checkDecTolerance(coins sdk.DecCoins, maxToleratedDiff sdk.Int) error { @@ -1717,7 +1717,7 @@ func checkDecTolerance(coins sdk.DecCoins, maxToleratedDiff sdk.Int) error { func withdrawGenesisGravity(genesisData *GenesisData, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error { - gravityBalance := genesisData.Accounts.MustGet(genesisData.GravityModuleAccountAddress).balance + gravityBalance := genesisData.Accounts.MustGet(genesisData.GravityModuleAccountAddress).Balance err := moveGenesisBalance(genesisData, genesisData.GravityModuleAccountAddress, cudosCfg.Config.RemainingGravityBalanceAddr, gravityBalance, "gravity_balance", manifest, cudosCfg) if err != nil { return err @@ -1731,29 +1731,29 @@ func accountIToAccountInfo(existingAccount authtypes.AccountI) (*AccountInfo, er // Get existing account type if existingAccount != nil { - accountInfo.pubkey = existingAccount.GetPubKey() - accountInfo.rawAddress = existingAccount.GetAddress() - accountInfo.address = accountInfo.rawAddress.String() + accountInfo.Pubkey = existingAccount.GetPubKey() + accountInfo.RawAddress = existingAccount.GetAddress() + accountInfo.Address = accountInfo.RawAddress.String() if periodicVestingAccount, ok := existingAccount.(*authvesting.PeriodicVestingAccount); ok { - accountInfo.accountType = PeriodicVestingAccountType - accountInfo.endTime = periodicVestingAccount.EndTime - accountInfo.originalVesting = periodicVestingAccount.OriginalVesting + accountInfo.AccountType = PeriodicVestingAccountType + accountInfo.EndTime = periodicVestingAccount.EndTime + accountInfo.OriginalVesting = periodicVestingAccount.OriginalVesting } else if delayedVestingAccount, ok := existingAccount.(*authvesting.DelayedVestingAccount); ok { - accountInfo.accountType = DelayedVestingAccountType - accountInfo.endTime = delayedVestingAccount.EndTime - accountInfo.originalVesting = delayedVestingAccount.OriginalVesting + accountInfo.AccountType = DelayedVestingAccountType + accountInfo.EndTime = delayedVestingAccount.EndTime + accountInfo.OriginalVesting = delayedVestingAccount.OriginalVesting } else if continuousVestingAccount, ok := existingAccount.(*authvesting.ContinuousVestingAccount); ok { - accountInfo.accountType = ContinuousVestingAccountType - accountInfo.endTime = continuousVestingAccount.EndTime - accountInfo.startTime = continuousVestingAccount.StartTime - accountInfo.originalVesting = continuousVestingAccount.OriginalVesting + accountInfo.AccountType = ContinuousVestingAccountType + accountInfo.EndTime = continuousVestingAccount.EndTime + accountInfo.StartTime = continuousVestingAccount.StartTime + accountInfo.OriginalVesting = continuousVestingAccount.OriginalVesting } else if permanentLockedAccount, ok := existingAccount.(*authvesting.PermanentLockedAccount); ok { - accountInfo.accountType = PermanentLockedAccount - accountInfo.originalVesting = permanentLockedAccount.OriginalVesting + accountInfo.AccountType = PermanentLockedAccount + accountInfo.OriginalVesting = permanentLockedAccount.OriginalVesting } else if _, ok := existingAccount.(*authtypes.BaseAccount); ok { // Handle base account - accountInfo.accountType = BaseAccountType + accountInfo.AccountType = BaseAccountType } else { return nil, fmt.Errorf("unexpected account type") } @@ -1766,23 +1766,23 @@ func resolveNewBaseAccount(ctx sdk.Context, app *App, genesisAccount *AccountInf var newBaseAccount *authtypes.BaseAccount var err error - // Check for pubkey collision + // Check for Pubkey collision if existingAccount != nil { // Handle collision - // Set pubkey from newAcc if is not in existingAccount - if existingAccount.GetPubKey() == nil && genesisAccount.pubkey != nil { - err := existingAccount.SetPubKey(genesisAccount.pubkey) + // Set Pubkey from newAcc if is not in existingAccount + if existingAccount.GetPubKey() == nil && genesisAccount.Pubkey != nil { + err := existingAccount.SetPubKey(genesisAccount.Pubkey) if err != nil { return nil, err } } - if genesisAccount.pubkey != nil && existingAccount.GetPubKey() != nil && !existingAccount.GetPubKey().Equals(genesisAccount.pubkey) { - return nil, fmt.Errorf("account already exists with different pubkey: %s", genesisAccount.address) + if genesisAccount.Pubkey != nil && existingAccount.GetPubKey() != nil && !existingAccount.GetPubKey().Equals(genesisAccount.Pubkey) { + return nil, fmt.Errorf("account already exists with different Pubkey: %s", genesisAccount.Address) } - newBaseAccount = authtypes.NewBaseAccount(genesisAccount.rawAddress, existingAccount.GetPubKey(), existingAccount.GetAccountNumber(), existingAccount.GetSequence()) + newBaseAccount = authtypes.NewBaseAccount(genesisAccount.RawAddress, existingAccount.GetPubKey(), existingAccount.GetAccountNumber(), existingAccount.GetSequence()) } else { @@ -1808,7 +1808,7 @@ func doRegularAccountMigration(ctx sdk.Context, app *App, genesisAccount *Accoun if newBalance != nil { // Account is not vesting - if cudosCfg.NotVestedAccounts.Has(genesisAccount.address) { + if cudosCfg.NotVestedAccounts.Has(genesisAccount.Address) { err := createNewNormalAccountFromBaseAccount(ctx, app, newBaseAccount) if err != nil { return err @@ -1821,7 +1821,7 @@ func doRegularAccountMigration(ctx sdk.Context, app *App, genesisAccount *Accoun } } - err = migrateToAccount(ctx, app, genesisAccount.address, genesisAccount.rawAddress, genesisAccount.balance, newBalance, "regular_account", manifest) + err = migrateToAccount(ctx, app, genesisAccount.Address, genesisAccount.RawAddress, genesisAccount.Balance, newBalance, "regular_account", manifest) if err != nil { return err } @@ -1839,14 +1839,14 @@ func doRegularAccountMigration(ctx sdk.Context, app *App, genesisAccount *Accoun func doCollisionMigration(ctx sdk.Context, app *App, genesisData *GenesisData, genesisAccount *AccountInfo, existingAccount authtypes.AccountI, newBalance sdk.Coins, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error { // Keep existing account intact and move cudos balance to account specified in config - genesisData.CollisionMap.SetNew(genesisAccount.address, cudosCfg.Config.VestingCollisionDestAddr) + genesisData.CollisionMap.SetNew(genesisAccount.Address, cudosCfg.Config.VestingCollisionDestAddr) _, destRawAddr, err := bech32.DecodeAndConvert(cudosCfg.Config.VestingCollisionDestAddr) if err != nil { return err } - err = migrateToAccount(ctx, app, genesisAccount.address, destRawAddr, genesisAccount.balance, newBalance, "vesting_collision_account", manifest) + err = migrateToAccount(ctx, app, genesisAccount.Address, destRawAddr, genesisAccount.Balance, newBalance, "vesting_collision_account", manifest) if err != nil { return err } @@ -1876,7 +1876,7 @@ func MigrateGenesisAccounts(genesisData *GenesisData, ctx sdk.Context, app *App, _, commissionRawAcc, err := bech32.DecodeAndConvert(cudosCfg.Config.CommissionFetchAddr) if err != nil { - return fmt.Errorf("failed to get commission account raw address: %w", err) + return fmt.Errorf("failed to get commission account raw Address: %w", err) } err = migrateToAccount(ctx, app, "mint_module", commissionRawAcc, sdk.NewCoins(), totalCommission, "total_commission", manifest) @@ -1903,62 +1903,62 @@ func MigrateGenesisAccounts(genesisData *GenesisData, ctx sdk.Context, app *App, for _, genesisAccountAddress := range genesisData.Accounts.Keys() { genesisAccount := genesisData.Accounts.MustGet(genesisAccountAddress) - if genesisAccount.accountType == ContractAccountType { + if genesisAccount.AccountType == ContractAccountType { // All contracts balance should be handled already - if genesisAccount.balance.Empty() { + if genesisAccount.Balance.Empty() { err = markAccountAsMigrated(genesisData, genesisAccountAddress) if err != nil { return err } } else { - return fmt.Errorf("unresolved contract balance: %s %s", genesisAccountAddress, genesisAccount.balance.String()) + return fmt.Errorf("unresolved contract balance: %s %s", genesisAccountAddress, genesisAccount.Balance.String()) } continue } - if genesisAccount.accountType == ModuleAccountType { - if genesisAccount.balance.Empty() { + if genesisAccount.AccountType == ModuleAccountType { + if genesisAccount.Balance.Empty() { err = markAccountAsMigrated(genesisData, genesisAccountAddress) if err != nil { return err } } else { - return fmt.Errorf("unresolved module balance: %s %s %s", genesisAccountAddress, genesisAccount.balance.String(), genesisAccount.name) + return fmt.Errorf("unresolved module balance: %s %s %s", genesisAccountAddress, genesisAccount.Balance.String(), genesisAccount.Name) } continue } - if genesisAccount.accountType == IBCAccountType { + if genesisAccount.AccountType == IBCAccountType { // All IBC balances should be handled already - if genesisAccount.balance.Empty() { + if genesisAccount.Balance.Empty() { err = markAccountAsMigrated(genesisData, genesisAccountAddress) if err != nil { return err } } else { - return fmt.Errorf("unresolved contract balance: %s %s", genesisAccountAddress, genesisAccount.balance.String()) + return fmt.Errorf("unresolved contract balance: %s %s", genesisAccountAddress, genesisAccount.Balance.String()) } continue } - existingAccount := app.AccountKeeper.GetAccount(ctx, genesisAccount.rawAddress) + existingAccount := app.AccountKeeper.GetAccount(ctx, genesisAccount.RawAddress) existingAccountInfo, err := accountIToAccountInfo(existingAccount) if err != nil { return err } // Get balance to mint - newBalance, err := convertBalance(app.StakingKeeper.BondDenom(ctx), genesisAccount.balance, cudosCfg) + newBalance, err := convertBalance(app.StakingKeeper.BondDenom(ctx), genesisAccount.Balance, cudosCfg) if err != nil { return err } // Handle all collision cases regularMigration := true - if existingAccount != nil && existingAccountInfo.accountType != BaseAccountType { + if existingAccount != nil && existingAccountInfo.AccountType != BaseAccountType { regularMigration = false } - if genesisAccount.accountType != BaseAccountType { + if genesisAccount.AccountType != BaseAccountType { regularMigration = false } @@ -2011,12 +2011,12 @@ func DoGenesisAccountMovements(genesisData *GenesisData, cudosCfg *CudosMergeCon return nil } - if fromAcc.balance.IsZero() { + if fromAcc.Balance.IsZero() { registerManifestBalanceMovement(accountMovement.SourceAddress, accountMovement.DestinationAddress, nil, "nothing_to_move_err", manifest) return nil } - fromAccTokensAmount := fromAcc.balance.AmountOfNoDenomValidation(genesisData.BondDenom) + fromAccTokensAmount := fromAcc.Balance.AmountOfNoDenomValidation(genesisData.BondDenom) // Move entire balance if balance to move is 0 or greater than available balance if accountMovement.Amount == nil || fromAccTokensAmount.LT(*accountMovement.Amount) { diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index c078f1980..55d17519a 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -358,11 +358,11 @@ func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisD return err } - // Withdraw Community pool balance to address if defined + // Withdraw Community pool balance to Address if defined communityBalance, _ := genesisData.DistributionInfo.FeePool.CommunityPool.TruncateDecimal() distributionModuleAccount := genesisData.Accounts.MustGet(genesisData.DistributionInfo.DistributionModuleAccountAddress) - remainingBalance := distributionModuleAccount.balance.Sub(communityBalance) + remainingBalance := distributionModuleAccount.Balance.Sub(communityBalance) // Withdraw remaining balance if logger != nil { @@ -375,7 +375,7 @@ func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisD return fmt.Errorf("remaining distribution balance %s is too high", remainingBalance.String()) } - err = moveGenesisBalance(genesisData, genesisData.DistributionInfo.DistributionModuleAccountAddress, cudosCfg.Config.RemainingDistributionBalanceAddr, distributionModuleAccount.balance, "remaining_distribution_module_balance", manifest, cudosCfg) + err = moveGenesisBalance(genesisData, genesisData.DistributionInfo.DistributionModuleAccountAddress, cudosCfg.Config.RemainingDistributionBalanceAddr, distributionModuleAccount.Balance, "remaining_distribution_module_balance", manifest, cudosCfg) if err != nil { return err } @@ -585,7 +585,7 @@ func calculateDelegationRewards(blockHeight uint64, distributionInfo *Distributi return rewards, nil } -// get the delegator withdraw address, defaulting to the delegator address +// get the delegator withdraw Address, defaulting to the delegator Address func (d DistributionInfo) GetDelegatorWithdrawAddr(delAddr string) string { b, exists := d.DelegatorWithdrawInfos.Get(delAddr) if !exists { diff --git a/app/upgrade_v_11_4_manifest.go b/app/upgrade_v_11_4_manifest.go index 77f436a90..d875ee73a 100644 --- a/app/upgrade_v_11_4_manifest.go +++ b/app/upgrade_v_11_4_manifest.go @@ -240,8 +240,8 @@ func RegisterVestingCollision(manifest *UpgradeManifest, originalAccount *Accoun } collision := VestingCollision{ - OriginalAccountFunds: originalAccount.balance, - OriginalAccount: originalAccount.rawAccData, + OriginalAccountFunds: originalAccount.Balance, + OriginalAccount: originalAccount.RawAddress, } if targetAccount != nil { res, err := codec.MarshalJSONIndent(authtypes.ModuleCdc.LegacyAmino, targetAccount) diff --git a/app/upgrade_v_11_4_network_config.go b/app/upgrade_v_11_4_network_config.go index d62b708e7..c3e9d580d 100644 --- a/app/upgrade_v_11_4_network_config.go +++ b/app/upgrade_v_11_4_network_config.go @@ -319,16 +319,16 @@ func LoadAndVerifyNetworkConfigFromFile(configFilePath string, expectedSha256Hex } type CudosMergeConfigJSON struct { - IbcTargetAddr string `json:"ibc_target_addr"` // Cudos address + IbcTargetAddr string `json:"ibc_target_addr"` // Cudos Address RemainingStakingBalanceAddr string `json:"remaining_staking_balance_addr"` // Cudos account for remaining bonded and not-bonded pool balances - RemainingGravityBalanceAddr string `json:"remaining_gravity_balance_addr"` // Cudos address - RemainingDistributionBalanceAddr string `json:"remaining_distribution_balance_addr"` // Cudos address - ContractDestinationFallbackAddr string `json:"contract_destination_fallback_addr"` // Cudos address - CommunityPoolBalanceDestAddr string `json:"community_pool_balance_dest_addr,omitempty"` // Cudos address, funds are moved to destination chain community pool if not set - - CommissionFetchAddr string `json:"commission_fetch_addr"` // Fetch address for commission - ExtraSupplyFetchAddr string `json:"extra_supply_fetch_addr"` // Fetch address for extra supply - VestingCollisionDestAddr string `json:"vesting_collision_dest_addr"` // This gets converted to raw address, so it can be fetch or cudos address + RemainingGravityBalanceAddr string `json:"remaining_gravity_balance_addr"` // Cudos Address + RemainingDistributionBalanceAddr string `json:"remaining_distribution_balance_addr"` // Cudos Address + ContractDestinationFallbackAddr string `json:"contract_destination_fallback_addr"` // Cudos Address + CommunityPoolBalanceDestAddr string `json:"community_pool_balance_dest_addr,omitempty"` // Cudos Address, funds are moved to destination chain community pool if not set + + CommissionFetchAddr string `json:"commission_fetch_addr"` // Fetch Address for commission + ExtraSupplyFetchAddr string `json:"extra_supply_fetch_addr"` // Fetch Address for extra supply + VestingCollisionDestAddr string `json:"vesting_collision_dest_addr"` // This gets converted to raw Address, so it can be fetch or cudos Address VestingPeriod int64 `json:"vesting_period"` // Vesting period diff --git a/app/utils.go b/app/utils.go index 01781db3b..158219a8e 100644 --- a/app/utils.go +++ b/app/utils.go @@ -76,7 +76,7 @@ func VerifyAddressPrefix(addr string, expectedPrefix string) error { } if prefix != expectedPrefix { - return fmt.Errorf("invalid address prefix: expected %s, got %s", expectedPrefix, prefix) + return fmt.Errorf("invalid Address prefix: expected %s, got %s", expectedPrefix, prefix) } return nil diff --git a/cmd/fetchd/cmd/cudos_merge.go b/cmd/fetchd/cmd/cudos_merge.go index 8ae5e5237..6c681d69f 100644 --- a/cmd/fetchd/cmd/cudos_merge.go +++ b/cmd/fetchd/cmd/cudos_merge.go @@ -89,6 +89,32 @@ It checks whether the network merge config file conforms to expected schema - pr networkMergeCmd.AddCommand(cmd) } +func AddCommandExtractAddressInfo(networkMergeCmd *cobra.Command) { + cmd := &cobra.Command{ + Use: "extract-address-info [network_merge_config_json_file_path] [source_chain_genesis_json_file_path] [address]", + Short: "Extracts balance information for a specific address", + Long: `This command retrieves all balance information for a given address, including the amount delegated to validators, rewards, and other relevant data. +It utilizes the provided network merge config and genesis JSON files to perform the extraction and display the results.`, + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := client.GetClientContextFromCmd(cmd) + + configFilePath := args[0] + GenesisFilePath := args[1] + address := args[2] + + // Call a function to extract address info + err := ExtractAddressInfo(configFilePath, GenesisFilePath, address, ctx) + if err != nil { + return err + } + return nil + }, + } + + networkMergeCmd.AddCommand(cmd) +} + func utilNetworkMergeCommand() *cobra.Command { cmd := &cobra.Command{ Use: "network-merge", @@ -99,6 +125,7 @@ func utilNetworkMergeCommand() *cobra.Command { } AddCommandVerify(cmd) + AddCommandExtractAddressInfo(cmd) return cmd } @@ -237,3 +264,48 @@ func VerifyConfigFile(configFilePath string, GenesisFilePath string, ctx client. return nil } + +func ExtractAddressInfo(configFilePath string, GenesisFilePath string, address string, ctx client.Context) error { + manifest := app.NewUpgradeManifest() + + networkInfo, _, err := app.LoadNetworkConfigFromFile(configFilePath) + if err != nil { + return err + } + + cudosConfig := app.NewCudosMergeConfig(networkInfo.CudosMerge) + genesisData, err := LoadGenesisDataFromFile(GenesisFilePath, cudosConfig, manifest) + if err != nil { + return err + } + + err = printAccInfo(genesisData, address, ctx) + if err != nil { + return err + } + + /* + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + err = app.ProcessSourceNetworkGenesis(logger, cudosConfig, genesisData, manifest) + if err != nil { + return err + } + */ + + return nil +} + +func printAccInfo(genesisData *app.GenesisData, address string, ctx client.Context) error { + accountInfo, exists := genesisData.Accounts.Get(address) + if !exists { + err := ctx.PrintString(fmt.Sprintf("Account %s doesn't exist", address)) + if err != nil { + return err + } + return nil + } + + print(accountInfo.Balance.String()) + + return nil +} From 8ff02d704d17135b0114041743fadf452ab357be Mon Sep 17 00:00:00 2001 From: Jiri Date: Tue, 15 Oct 2024 15:24:41 +0200 Subject: [PATCH 02/11] Info command --- app/upgrade_cudos.go | 138 ++++++++++++++++++++---------- app/upgrade_cudos_distribution.go | 50 +++++------ cmd/fetchd/cmd/cudos_merge.go | 123 +++++++++++++++++++++++++- 3 files changed, 241 insertions(+), 70 deletions(-) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index c53f60a4a..7bea9a1b3 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -111,10 +111,12 @@ type GenesisData struct { Prefix string BondDenom string - Accounts *OrderedMap[string, *AccountInfo] - Contracts *OrderedMap[string, *ContractInfo] - IbcAccounts *OrderedMap[string, *IBCInfo] - Delegations *OrderedMap[string, *OrderedMap[string, sdk.Int]] + Accounts *OrderedMap[string, *AccountInfo] + Contracts *OrderedMap[string, *ContractInfo] + IbcAccounts *OrderedMap[string, *IBCInfo] + Delegations *OrderedMap[string, *OrderedMap[string, sdk.Int]] + UnbondedDelegations *OrderedMap[string, *OrderedMap[string, sdk.Int]] + UnbondingDelegations *OrderedMap[string, *OrderedMap[string, sdk.Int]] Validators *OrderedMap[string, *ValidatorInfo] BondedPoolAddress string @@ -333,11 +335,16 @@ func ParseGenesisData(jsonData map[string]interface{}, genDoc *tmtypes.GenesisDo return nil, fmt.Errorf("failed to get validators map: %w", err) } - genesisData.Delegations, err = parseGenesisDelegations(genesisData.Validators, genesisData.Contracts, cudosCfg) + genesisData.Delegations, genesisData.UnbondedDelegations, err = parseGenesisDelegations(genesisData.Validators, genesisData.Contracts, cudosCfg) if err != nil { return nil, fmt.Errorf("failed to get delegations map: %w", err) } + genesisData.UnbondingDelegations, err = parseGenesisUnbondingDelegations(genesisData.Validators, genesisData.Contracts, cudosCfg) + if err != nil { + return nil, fmt.Errorf("failed to get unbonding delegations map: %w", err) + } + distributionInfo, err := parseGenesisDistribution(jsonData, genesisData.Accounts) if err != nil { return nil, fmt.Errorf("failed to get distribution module map: %w", err) @@ -585,22 +592,24 @@ func parseGenesisAccounts(jsonData map[string]interface{}, contractAccountMap *O return accountMap, nil } -func parseGenesisDelegations(validators *OrderedMap[string, *ValidatorInfo], contracts *OrderedMap[string, *ContractInfo], cudosCfg *CudosMergeConfig) (*OrderedMap[string, *OrderedMap[string, sdk.Int]], error) { +func parseGenesisDelegations(validators *OrderedMap[string, *ValidatorInfo], contracts *OrderedMap[string, *ContractInfo], cudosCfg *CudosMergeConfig) (*OrderedMap[string, *OrderedMap[string, sdk.Int]], *OrderedMap[string, *OrderedMap[string, sdk.Int]], error) { // Handle delegations delegatedBalanceMap := NewOrderedMap[string, *OrderedMap[string, sdk.Int]]() + unbondingDelegatedBalanceMap := NewOrderedMap[string, *OrderedMap[string, sdk.Int]]() + for i := range validators.Iterate() { validatorOperatorAddress, validator := i.Key, i.Value - for j := range validator.delegations.Iterate() { + for j := range validator.Delegations.Iterate() { delegatorAddress, delegation := j.Key, j.Value resolvedDelegatorAddress, err := resolveIfContractAddressWithFallback(delegatorAddress, contracts, cudosCfg) if err != nil { - return nil, err + return nil, nil, err } currentValidatorInfo := validators.MustGet(validatorOperatorAddress) - delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.shares).TruncateInt() + delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.Shares).TruncateInt() if delegatorTokens.IsZero() { // This happens when number of shares is less than 1 @@ -608,49 +617,92 @@ func parseGenesisDelegations(validators *OrderedMap[string, *ValidatorInfo], con } // Subtract balance from bonded or not-bonded pool - if currentValidatorInfo.status == BondedStatus { + if currentValidatorInfo.Status == BondedStatus { // Store delegation to delegated map resolvedDelegatorMap, _ := delegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) resolvedDelegator, _ := resolvedDelegatorMap.GetOrSetDefault(validatorOperatorAddress, sdk.NewInt(0)) resolvedDelegatorMap.Set(validatorOperatorAddress, resolvedDelegator.Add(delegatorTokens)) delegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) + } else { + // Store delegation to delegated map + resolvedDelegatorMap, _ := unbondingDelegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) + resolvedDelegator, _ := resolvedDelegatorMap.GetOrSetDefault(validatorOperatorAddress, sdk.NewInt(0)) + resolvedDelegatorMap.Set(validatorOperatorAddress, resolvedDelegator.Add(delegatorTokens)) + unbondingDelegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) + } + } + } + + return delegatedBalanceMap, unbondingDelegatedBalanceMap, nil +} + +func parseGenesisUnbondingDelegations(validators *OrderedMap[string, *ValidatorInfo], contracts *OrderedMap[string, *ContractInfo], cudosCfg *CudosMergeConfig) (*OrderedMap[string, *OrderedMap[string, sdk.Int]], error) { + // Handle delegations + unbondedDelegatedBalanceMap := NewOrderedMap[string, *OrderedMap[string, sdk.Int]]() + + for i := range validators.Iterate() { + validatorOperatorAddress, validator := i.Key, i.Value + + for j := range validator.UnbondingDelegations.Iterate() { + delegatorAddress, delegation := j.Key, j.Value + + resolvedDelegatorAddress, err := resolveIfContractAddressWithFallback(delegatorAddress, contracts, cudosCfg) + if err != nil { + return nil, err } + + delegatorTokens := sdk.NewInt(0) + + for _, entry := range delegation.Entries { + delegatorTokens = delegatorTokens.Add(entry.Balance) + } + + if delegatorTokens.IsZero() { + // This happens when number of shares is less than 1 + continue + } + + // Store delegation to delegated map + resolvedDelegatorMap, _ := unbondedDelegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) + resolvedDelegator, _ := resolvedDelegatorMap.GetOrSetDefault(validatorOperatorAddress, sdk.NewInt(0)) + resolvedDelegatorMap.Set(validatorOperatorAddress, resolvedDelegator.Add(delegatorTokens)) + unbondedDelegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) } } - return delegatedBalanceMap, nil + return unbondedDelegatedBalanceMap, nil } type DelegationInfo struct { - delegatorAddress string - shares sdk.Dec + DelegatorAddress string + Shares sdk.Dec } type UnbondingDelegationInfo struct { - delegatorAddress string - entries []*UnbondingDelegationEntry + DelegatorAddress string + Entries []*UnbondingDelegationEntry } type UnbondingDelegationEntry struct { - balance sdk.Int - initialBalance sdk.Int - creationHeight uint64 - completionTime string + Balance sdk.Int + InitialBalance sdk.Int + CreationHeight uint64 + CompletionTime string } type ValidatorInfo struct { - stake sdk.Int - shares sdk.Dec - status string - operatorAddress string - consensusPubkey cryptotypes.PubKey - delegations *OrderedMap[string, *DelegationInfo] - unbondingDelegations *OrderedMap[string, *UnbondingDelegationInfo] + Stake sdk.Int + Shares sdk.Dec + Status string + OperatorAddress string + ConsensusPubkey cryptotypes.PubKey + Delegations *OrderedMap[string, *DelegationInfo] + UnbondingDelegations *OrderedMap[string, *UnbondingDelegationInfo] } func (v ValidatorInfo) TokensFromShares(shares sdk.Dec) sdk.Dec { - return (shares.MulInt(v.stake)).Quo(v.shares) + return (shares.MulInt(v.Stake)).Quo(v.Shares) } func parseGenesisValidators(jsonData map[string]interface{}) (*OrderedMap[string, *ValidatorInfo], error) { @@ -687,13 +739,13 @@ func parseGenesisValidators(jsonData map[string]interface{}) (*OrderedMap[string } validatorInfoMap.SetNew(operatorAddress, &ValidatorInfo{ - stake: tokensInt, - shares: validatorSharesDec, - status: status, - operatorAddress: operatorAddress, - consensusPubkey: decodedConsensusPubkey, - delegations: NewOrderedMap[string, *DelegationInfo](), - unbondingDelegations: NewOrderedMap[string, *UnbondingDelegationInfo](), + Stake: tokensInt, + Shares: validatorSharesDec, + Status: status, + OperatorAddress: operatorAddress, + ConsensusPubkey: decodedConsensusPubkey, + Delegations: NewOrderedMap[string, *DelegationInfo](), + UnbondingDelegations: NewOrderedMap[string, *UnbondingDelegationInfo](), }) } @@ -711,7 +763,7 @@ func parseGenesisValidators(jsonData map[string]interface{}) (*OrderedMap[string } validator := validatorInfoMap.MustGet(validatorAddress) - validator.delegations.SetNew(delegatorAddress, &DelegationInfo{delegatorAddress: delegatorAddress, shares: delegatorSharesDec}) + validator.Delegations.SetNew(delegatorAddress, &DelegationInfo{DelegatorAddress: delegatorAddress, Shares: delegatorSharesDec}) } unbondingDelegations := staking["unbonding_delegations"].([]interface{}) @@ -740,11 +792,11 @@ func parseGenesisValidators(jsonData map[string]interface{}) (*OrderedMap[string completionTime := entryMap["completion_time"].(string) - unbondingDelegationEntries = append(unbondingDelegationEntries, &UnbondingDelegationEntry{balance: balance, initialBalance: initialBalance, creationHeight: creationHeight, completionTime: completionTime}) + unbondingDelegationEntries = append(unbondingDelegationEntries, &UnbondingDelegationEntry{Balance: balance, InitialBalance: initialBalance, CreationHeight: creationHeight, CompletionTime: completionTime}) } validator := validatorInfoMap.MustGet(validatorAddress) - validator.unbondingDelegations.SetNew(delegatorAddress, &UnbondingDelegationInfo{delegatorAddress: delegatorAddress, entries: unbondingDelegationEntries}) + validator.UnbondingDelegations.SetNew(delegatorAddress, &UnbondingDelegationInfo{DelegatorAddress: delegatorAddress, Entries: unbondingDelegationEntries}) } return validatorInfoMap, nil @@ -755,7 +807,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa for i := range genesisData.Validators.Iterate() { validatorOperatorAddress, validator := i.Key, i.Value - for j := range validator.delegations.Iterate() { + for j := range validator.Delegations.Iterate() { delegatorAddress, delegation := j.Key, j.Value resolvedDelegatorAddress, err := resolveIfContractAddressWithFallback(delegatorAddress, genesisData.Contracts, cudosCfg) @@ -764,7 +816,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa } currentValidatorInfo := genesisData.Validators.MustGet(validatorOperatorAddress) - delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.shares).TruncateInt() + delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.Shares).TruncateInt() // Move balance to delegator Address delegatorBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, delegatorTokens)) @@ -775,7 +827,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa } // Subtract balance from bonded or not-bonded pool - if currentValidatorInfo.status == BondedStatus { + if currentValidatorInfo.Status == BondedStatus { // Move balance from bonded pool to delegator err := moveGenesisBalance(genesisData, genesisData.BondedPoolAddress, resolvedDelegatorAddress, delegatorBalance, "bonded_delegation", manifest, cudosCfg) if err != nil { @@ -795,7 +847,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa } // Handle unbonding delegations - for j := range validator.unbondingDelegations.Iterate() { + for j := range validator.UnbondingDelegations.Iterate() { delegatorAddress, unbondingDelegation := j.Key, j.Value resolvedDelegatorAddress, err := resolveIfContractAddressWithFallback(delegatorAddress, genesisData.Contracts, cudosCfg) @@ -803,8 +855,8 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa return err } - for _, entry := range unbondingDelegation.entries { - unbondingDelegationBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, entry.balance)) + for _, entry := range unbondingDelegation.Entries { + unbondingDelegationBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, entry.Balance)) // Move unbonding balance from not-bonded pool to delegator Address err := moveGenesisBalance(genesisData, genesisData.NotBondedPoolAddress, resolvedDelegatorAddress, unbondingDelegationBalance, "unbonding_delegation", manifest, cudosCfg) diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index 55d17519a..cac168326 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -332,10 +332,10 @@ func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisD delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOpertorAddr) - endingPeriod := updateValidatorData(genesisData.DistributionInfo, validator) + endingPeriod := UpdateValidatorData(genesisData.DistributionInfo, validator) for _, delegatorAddr := range delegatorStartInfo.Keys() { - delegation := validator.delegations.MustGet(delegatorAddr) + delegation := validator.Delegations.MustGet(delegatorAddr) _, err := withdrawDelegationRewards(logger, genesisData, validator, delegation, endingPeriod, blockHeight, cudosCfg, manifest) if err != nil { @@ -441,7 +441,7 @@ func calculateDelegationRewardsBetween(distributionInfo *DistributionInfo, val * // return staking * (ending - starting) - operatorRewards := distributionInfo.ValidatorHistoricalRewards.MustGet(val.operatorAddress) + operatorRewards := distributionInfo.ValidatorHistoricalRewards.MustGet(val.OperatorAddress) starting := operatorRewards.MustGet(startingPeriod) ending := operatorRewards.MustGet(endingPeriod) @@ -490,10 +490,10 @@ func IterateValidatorSlashEventsBetween(distributionInfo *DistributionInfo, val } // calculate the total rewards accrued by a delegation -func calculateDelegationRewards(blockHeight uint64, distributionInfo *DistributionInfo, val *ValidatorInfo, del *DelegationInfo, endingPeriod uint64) (rewards sdk.DecCoins, err error) { +func CalculateDelegationRewards(blockHeight uint64, distributionInfo *DistributionInfo, val *ValidatorInfo, del *DelegationInfo, endingPeriod uint64) (rewards sdk.DecCoins, err error) { // fetch starting info for delegation - delStartingInfo := distributionInfo.DelegatorStartingInfos.MustGet(val.operatorAddress) - startingInfo := delStartingInfo.MustGet(del.delegatorAddress) + delStartingInfo := distributionInfo.DelegatorStartingInfos.MustGet(val.OperatorAddress) + startingInfo := delStartingInfo.MustGet(del.DelegatorAddress) if startingInfo.height == blockHeight { // started this height, no rewards yet @@ -515,7 +515,7 @@ func calculateDelegationRewards(blockHeight uint64, distributionInfo *Distributi // for them for the stake sanity check below. endingHeight := blockHeight if endingHeight > startingHeight { - err := IterateValidatorSlashEventsBetween(distributionInfo, val.operatorAddress, startingHeight, endingHeight, + err := IterateValidatorSlashEventsBetween(distributionInfo, val.OperatorAddress, startingHeight, endingHeight, func(height uint64, event *ValidatorSlashEvent) (stop bool, err error) { endingPeriod := event.validatorPeriod if endingPeriod > startingPeriod { @@ -541,7 +541,7 @@ func calculateDelegationRewards(blockHeight uint64, distributionInfo *Distributi // equal to current stake here. We cannot use Equals because stake is truncated // when multiplied by slash fractions (see above). We could only use equals if // we had arbitrary-precision rationals. - currentStake := val.TokensFromShares(del.shares) + currentStake := val.TokensFromShares(del.Shares) if stake.GT(currentStake) { // AccountI for rounding inconsistencies between: @@ -571,7 +571,7 @@ func calculateDelegationRewards(blockHeight uint64, distributionInfo *Distributi return sdk.DecCoins{}, fmt.Errorf("calculated final stake for delegator %s greater than current stake"+ "\n\tfinal stake:\t%s"+ "\n\tcurrent stake:\t%s", - del.delegatorAddress, stake, currentStake) + del.DelegatorAddress, stake, currentStake) } } @@ -597,19 +597,19 @@ func (d DistributionInfo) GetDelegatorWithdrawAddr(delAddr string) string { func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val *ValidatorInfo, del *DelegationInfo, endingPeriod uint64, blockHeight uint64, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) (sdk.Coins, error) { // check existence of delegator starting info - genesisData.DistributionInfo.DelegatorStartingInfos.Has(val.operatorAddress) - StartingInfoMap, exists := genesisData.DistributionInfo.DelegatorStartingInfos.Get(val.operatorAddress) - if !exists || !StartingInfoMap.Has(del.delegatorAddress) { + genesisData.DistributionInfo.DelegatorStartingInfos.Has(val.OperatorAddress) + StartingInfoMap, exists := genesisData.DistributionInfo.DelegatorStartingInfos.Get(val.OperatorAddress) + if !exists || !StartingInfoMap.Has(del.DelegatorAddress) { return nil, fmt.Errorf("delegator starting info not found") } // end current period and calculate rewards //endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewardsRaw, err := calculateDelegationRewards(blockHeight, genesisData.DistributionInfo, val, del, endingPeriod) + rewardsRaw, err := CalculateDelegationRewards(blockHeight, genesisData.DistributionInfo, val, del, endingPeriod) if err != nil { return nil, err } - outstanding := genesisData.DistributionInfo.OutstandingRewards.MustGet(val.operatorAddress) + outstanding := genesisData.DistributionInfo.OutstandingRewards.MustGet(val.OperatorAddress) // defensive edge case may happen on the very final digits // of the decCoins due to operation order of the distribution mechanism. @@ -618,8 +618,8 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val if logger != nil { logger.Error( "rounding error withdrawing rewards from validator", - "delegator", del.delegatorAddress, - "validator", val.operatorAddress, + "delegator", del.DelegatorAddress, + "validator", val.OperatorAddress, "got", rewards.String(), "expected", rewardsRaw.String(), ) @@ -631,7 +631,7 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val // add coins to user account if !finalRewards.IsZero() { - withdrawAddr := genesisData.DistributionInfo.GetDelegatorWithdrawAddr(del.delegatorAddress) + withdrawAddr := genesisData.DistributionInfo.GetDelegatorWithdrawAddr(del.DelegatorAddress) // SendCoinsFromModuleToAccount err := moveGenesisBalance(genesisData, genesisData.DistributionInfo.DistributionModuleAccountAddress, withdrawAddr, finalRewards, "delegation_reward", manifest, cudosCfg) @@ -643,7 +643,7 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val // update the outstanding rewards and the community pool only if the // transaction was successful - genesisData.DistributionInfo.OutstandingRewards.Set(val.operatorAddress, outstanding.Sub(rewards)) + genesisData.DistributionInfo.OutstandingRewards.Set(val.OperatorAddress, outstanding.Sub(rewards)) genesisData.DistributionInfo.FeePool.CommunityPool = genesisData.DistributionInfo.FeePool.CommunityPool.Add(remainder...) // decrement reference count of starting period @@ -682,31 +682,31 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val } // Code based on IncrementValidatorPeriod -func updateValidatorData(distributionInfo *DistributionInfo, val *ValidatorInfo) uint64 { +func UpdateValidatorData(distributionInfo *DistributionInfo, val *ValidatorInfo) uint64 { // fetch current rewards - rewards := distributionInfo.ValidatorCurrentRewards.MustGet(val.operatorAddress) + rewards := distributionInfo.ValidatorCurrentRewards.MustGet(val.OperatorAddress) // calculate current ratio var current sdk.DecCoins - if val.stake.IsZero() { + if val.Stake.IsZero() { // can't calculate ratio for zero-token validators // ergo we instead add to the community pool - outstanding := distributionInfo.OutstandingRewards.MustGet(val.operatorAddress) + outstanding := distributionInfo.OutstandingRewards.MustGet(val.OperatorAddress) distributionInfo.FeePool.CommunityPool = distributionInfo.FeePool.CommunityPool.Add(rewards.reward...) outstanding = outstanding.Sub(rewards.reward) - distributionInfo.OutstandingRewards.Set(val.operatorAddress, outstanding) + distributionInfo.OutstandingRewards.Set(val.OperatorAddress, outstanding) current = sdk.DecCoins{} } else { // note: necessary to truncate so we don't allow withdrawing more rewards than owed - current = rewards.reward.QuoDecTruncate(val.stake.ToDec()) + current = rewards.reward.QuoDecTruncate(val.Stake.ToDec()) } // fetch historical rewards for last period //historical := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), rewards.Period-1).CumulativeRewardRatio - historicalValInfo := distributionInfo.ValidatorHistoricalRewards.MustGet(val.operatorAddress) + historicalValInfo := distributionInfo.ValidatorHistoricalRewards.MustGet(val.OperatorAddress) historical := historicalValInfo.MustGet(rewards.period - 1) // decrement reference count diff --git a/cmd/fetchd/cmd/cudos_merge.go b/cmd/fetchd/cmd/cudos_merge.go index 6c681d69f..9592481b1 100644 --- a/cmd/fetchd/cmd/cudos_merge.go +++ b/cmd/fetchd/cmd/cudos_merge.go @@ -5,10 +5,12 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/fetchai/fetchd/app" "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/log" + "math" "os" ) @@ -296,16 +298,133 @@ func ExtractAddressInfo(configFilePath string, GenesisFilePath string, address s } func printAccInfo(genesisData *app.GenesisData, address string, ctx client.Context) error { + totalAvailableBalance := sdk.NewCoins() + accountInfo, exists := genesisData.Accounts.Get(address) if !exists { - err := ctx.PrintString(fmt.Sprintf("Account %s doesn't exist", address)) + err := ctx.PrintString(fmt.Sprintf("Account %s doesn't exist\n", address)) if err != nil { return err } return nil } - print(accountInfo.Balance.String()) + err := ctx.PrintString(fmt.Sprintf("Account type: %s\n", accountInfo.AccountType)) + if err != nil { + return err + } + + if accountInfo.Name != "" { + err = ctx.PrintString(fmt.Sprintf("Account name: %s\n", accountInfo.Name)) + if err != nil { + return err + } + } + + if !accountInfo.OriginalVesting.IsZero() { + err = ctx.PrintString(fmt.Sprintf("Vested balance: %s\n", accountInfo.OriginalVesting)) + if err != nil { + return err + } + } + + // Get bank balance + totalAvailableBalance = totalAvailableBalance.Add(accountInfo.Balance...) + err = ctx.PrintString(fmt.Sprintf("Bank balance: %s\n", accountInfo.Balance)) + if err != nil { + return err + } + + // Bonded tokens + err = ctx.PrintString("Balance in delegations:\n") + if err != nil { + return err + } + if delegations, exists := genesisData.Delegations.Get(address); exists { + for i := range delegations.Iterate() { + validatorAddress, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalAvailableBalance = totalAvailableBalance.Add(delegatedBalance) + err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorAddress, delegatedBalance)) + if err != nil { + return err + } + } + } + + // Unbonding tokens + err = ctx.PrintString("Balance in unbonding delegations:\n") + if err != nil { + return err + } + if delegations, exists := genesisData.UnbondingDelegations.Get(address); exists { + for i := range delegations.Iterate() { + validatorAddress, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalAvailableBalance = totalAvailableBalance.Add(delegatedBalance) + err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorAddress, delegatedBalance)) + if err != nil { + return err + } + } + } + + // Unbonded tokens + err = ctx.PrintString("Balance in unbonded delegations:\n") + if err != nil { + return err + } + if delegations, exists := genesisData.UnbondedDelegations.Get(address); exists { + for i := range delegations.Iterate() { + validatorAddress, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalAvailableBalance = totalAvailableBalance.Add(delegatedBalance) + err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorAddress, delegatedBalance)) + if err != nil { + return err + } + } + } + + // Get distribution module rewards + err = ctx.PrintString("Rewards:\n") + if err != nil { + return err + } + blockHeight := uint64(math.MaxUint64) + for _, validatorOpertorAddr := range genesisData.DistributionInfo.DelegatorStartingInfos.Keys() { + validator := genesisData.Validators.MustGet(validatorOpertorAddr) + + delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOpertorAddr) + + endingPeriod := app.UpdateValidatorData(genesisData.DistributionInfo, validator) + + if !delegatorStartInfo.Has(address) { + continue + } + delegation := validator.Delegations.MustGet(address) + + rewardsRaw, err := app.CalculateDelegationRewards(blockHeight, genesisData.DistributionInfo, validator, delegation, endingPeriod) + if err != nil { + return err + } + reward, _ := rewardsRaw.TruncateDecimal() + + if !reward.IsZero() { + + totalAvailableBalance = totalAvailableBalance.Add(reward...) + + err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorOpertorAddr, reward)) + if err != nil { + return err + } + } + } + + err = ctx.PrintString(fmt.Sprintf("Total available balance: %s\n", totalAvailableBalance)) + if err != nil { + return err + } return nil } From 410fcae4077058d705ffe15e04fccb712adcd82a Mon Sep 17 00:00:00 2001 From: Jiri Date: Wed, 16 Oct 2024 11:20:53 +0200 Subject: [PATCH 03/11] Refactor --- app/upgrade_cudos.go | 10 +++---- app/upgrade_cudos_distribution.go | 49 +++++++++++++++++++++++++++---- cmd/fetchd/cmd/cudos_merge.go | 36 +++++++---------------- 3 files changed, 60 insertions(+), 35 deletions(-) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index 7bea9a1b3..c4dfed175 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -345,7 +345,7 @@ func ParseGenesisData(jsonData map[string]interface{}, genDoc *tmtypes.GenesisDo return nil, fmt.Errorf("failed to get unbonding delegations map: %w", err) } - distributionInfo, err := parseGenesisDistribution(jsonData, genesisData.Accounts) + distributionInfo, err := parseGenesisDistribution(jsonData, genesisData.Accounts, genesisData.Validators) if err != nil { return nil, fmt.Errorf("failed to get distribution module map: %w", err) } @@ -639,7 +639,7 @@ func parseGenesisDelegations(validators *OrderedMap[string, *ValidatorInfo], con func parseGenesisUnbondingDelegations(validators *OrderedMap[string, *ValidatorInfo], contracts *OrderedMap[string, *ContractInfo], cudosCfg *CudosMergeConfig) (*OrderedMap[string, *OrderedMap[string, sdk.Int]], error) { // Handle delegations - unbondedDelegatedBalanceMap := NewOrderedMap[string, *OrderedMap[string, sdk.Int]]() + unbondingDelegatedBalanceMap := NewOrderedMap[string, *OrderedMap[string, sdk.Int]]() for i := range validators.Iterate() { validatorOperatorAddress, validator := i.Key, i.Value @@ -664,14 +664,14 @@ func parseGenesisUnbondingDelegations(validators *OrderedMap[string, *ValidatorI } // Store delegation to delegated map - resolvedDelegatorMap, _ := unbondedDelegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) + resolvedDelegatorMap, _ := unbondingDelegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) resolvedDelegator, _ := resolvedDelegatorMap.GetOrSetDefault(validatorOperatorAddress, sdk.NewInt(0)) resolvedDelegatorMap.Set(validatorOperatorAddress, resolvedDelegator.Add(delegatorTokens)) - unbondedDelegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) + unbondingDelegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) } } - return unbondedDelegatedBalanceMap, nil + return unbondingDelegatedBalanceMap, nil } type DelegationInfo struct { diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index cac168326..95be0942f 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -48,8 +48,11 @@ type DistributionInfo struct { DelegatorStartingInfos *OrderedMap[string, *OrderedMap[string, *DelegatorStartingInfo]] // validator_addr -> delegator_addr -> starting_info DelegatorWithdrawInfos *OrderedMap[string, string] // delegator_address -> withdraw_address - ValidatorSlashEvents *OrderedMap[string, *OrderedMap[uint64, *ValidatorSlashEvent]] // validatior_address -> height -> validator_slash_event + ValidatorSlashEvents *OrderedMap[string, *OrderedMap[uint64, *ValidatorSlashEvent]] // validator_address -> height -> validator_slash_event DistributionModuleAccountAddress string + + // Aggregated values + Rewards *OrderedMap[string, *OrderedMap[string, sdk.DecCoins]] // delegator_addr -> validator_addr -> reward } func parseDelegatorStartingInfos(distribution map[string]interface{}) (*OrderedMap[string, *OrderedMap[string, *DelegatorStartingInfo]], error) { @@ -242,7 +245,38 @@ func parseDelegatorWithdrawInfos(distribution map[string]interface{}) (*OrderedM return delegatorWithdrawInfos, nil } -func parseGenesisDistribution(jsonData map[string]interface{}, genesisAccounts *OrderedMap[string, *AccountInfo]) (*DistributionInfo, error) { +func aggregateRewards(distributionInfo *DistributionInfo, validators *OrderedMap[string, *ValidatorInfo]) error { + blockHeight := uint64(math.MaxUint64) + + if distributionInfo.Rewards == nil { + distributionInfo.Rewards = NewOrderedMap[string, *OrderedMap[string, sdk.DecCoins]]() + } + + // Withdraw all delegation rewards + for i := range distributionInfo.DelegatorStartingInfos.Iterate() { + validatorOperatorAddr, delegatorStartInfo := i.Key, i.Value + validator := validators.MustGet(validatorOperatorAddr) + + endingPeriod := UpdateValidatorData(distributionInfo, validator) + + for _, delegatorAddr := range delegatorStartInfo.Keys() { + delegation := validator.Delegations.MustGet(delegatorAddr) + + rewardsRaw, err := CalculateDelegationRewards(blockHeight, distributionInfo, validator, delegation, endingPeriod) + if err != nil { + return err + } + + delegatorRewards, _ := distributionInfo.Rewards.GetOrSetDefault(delegatorAddr, NewOrderedMap[string, sdk.DecCoins]()) + delegatorRewards.SetNew(validatorOperatorAddr, rewardsRaw) + } + + } + + return nil +} + +func parseGenesisDistribution(jsonData map[string]interface{}, genesisAccounts *OrderedMap[string, *AccountInfo], validators *OrderedMap[string, *ValidatorInfo]) (*DistributionInfo, error) { distribution := jsonData[distributiontypes.ModuleName].(map[string]interface{}) distributionInfo := DistributionInfo{} var err error @@ -292,6 +326,11 @@ func parseGenesisDistribution(jsonData map[string]interface{}, genesisAccounts * return nil, err } + err = aggregateRewards(&distributionInfo, validators) + if err != nil { + return nil, err + } + return &distributionInfo, nil } @@ -327,10 +366,10 @@ func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisD blockHeight := uint64(math.MaxUint64) // Withdraw all delegation rewards - for _, validatorOpertorAddr := range genesisData.DistributionInfo.DelegatorStartingInfos.Keys() { - validator := genesisData.Validators.MustGet(validatorOpertorAddr) + for _, validatorOperatorAddr := range genesisData.DistributionInfo.DelegatorStartingInfos.Keys() { + validator := genesisData.Validators.MustGet(validatorOperatorAddr) - delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOpertorAddr) + delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOperatorAddr) endingPeriod := UpdateValidatorData(genesisData.DistributionInfo, validator) diff --git a/cmd/fetchd/cmd/cudos_merge.go b/cmd/fetchd/cmd/cudos_merge.go index 9592481b1..5c427565a 100644 --- a/cmd/fetchd/cmd/cudos_merge.go +++ b/cmd/fetchd/cmd/cudos_merge.go @@ -10,7 +10,6 @@ import ( "github.com/fetchai/fetchd/app" "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/log" - "math" "os" ) @@ -391,33 +390,20 @@ func printAccInfo(genesisData *app.GenesisData, address string, ctx client.Conte if err != nil { return err } - blockHeight := uint64(math.MaxUint64) - for _, validatorOpertorAddr := range genesisData.DistributionInfo.DelegatorStartingInfos.Keys() { - validator := genesisData.Validators.MustGet(validatorOpertorAddr) - delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOpertorAddr) + if DelegatorRewards, exists := genesisData.DistributionInfo.Rewards.Get(address); exists { + for j := range DelegatorRewards.Iterate() { + validatorOperatorAddr, rewardDecAmount := j.Key, j.Value + rewardAmount, _ := rewardDecAmount.TruncateDecimal() + if !rewardAmount.IsZero() { + totalAvailableBalance = totalAvailableBalance.Add(rewardAmount...) - endingPeriod := app.UpdateValidatorData(genesisData.DistributionInfo, validator) - - if !delegatorStartInfo.Has(address) { - continue - } - delegation := validator.Delegations.MustGet(address) - - rewardsRaw, err := app.CalculateDelegationRewards(blockHeight, genesisData.DistributionInfo, validator, delegation, endingPeriod) - if err != nil { - return err - } - reward, _ := rewardsRaw.TruncateDecimal() - - if !reward.IsZero() { - - totalAvailableBalance = totalAvailableBalance.Add(reward...) - - err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorOpertorAddr, reward)) - if err != nil { - return err + err = ctx.PrintString(fmt.Sprintf("%s, %s\n", validatorOperatorAddr, rewardAmount)) + if err != nil { + return err + } } + } } From e8b65d2fd4cc867c9ffac56a9985a70145e4bf2d Mon Sep 17 00:00:00 2001 From: Jiri Date: Wed, 16 Oct 2024 11:35:23 +0200 Subject: [PATCH 04/11] Rewards withdrawal refactor --- app/upgrade_cudos_distribution.go | 37 ++++++++++--------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index 95be0942f..22515e6d1 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -361,22 +361,13 @@ func verifyOutstandingBalances(genesisData *GenesisData) error { } func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisData, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error { - // block height is used only to early stop rewards calculation - //blockHeight := getMaxBlockHeight(genesisData) + 1 - blockHeight := uint64(math.MaxUint64) - // Withdraw all delegation rewards for _, validatorOperatorAddr := range genesisData.DistributionInfo.DelegatorStartingInfos.Keys() { - validator := genesisData.Validators.MustGet(validatorOperatorAddr) - delegatorStartInfo := genesisData.DistributionInfo.DelegatorStartingInfos.MustGet(validatorOperatorAddr) - endingPeriod := UpdateValidatorData(genesisData.DistributionInfo, validator) - for _, delegatorAddr := range delegatorStartInfo.Keys() { - delegation := validator.Delegations.MustGet(delegatorAddr) - _, err := withdrawDelegationRewards(logger, genesisData, validator, delegation, endingPeriod, blockHeight, cudosCfg, manifest) + _, err := withdrawDelegationRewards(logger, genesisData, validatorOperatorAddr, delegatorAddr, cudosCfg, manifest) if err != nil { return err } @@ -633,22 +624,18 @@ func (d DistributionInfo) GetDelegatorWithdrawAddr(delAddr string) string { return b } -func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val *ValidatorInfo, del *DelegationInfo, endingPeriod uint64, blockHeight uint64, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) (sdk.Coins, error) { +func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, validatorOperatorAddress string, delegatorAddress string, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) (sdk.Coins, error) { // check existence of delegator starting info - genesisData.DistributionInfo.DelegatorStartingInfos.Has(val.OperatorAddress) - StartingInfoMap, exists := genesisData.DistributionInfo.DelegatorStartingInfos.Get(val.OperatorAddress) - if !exists || !StartingInfoMap.Has(del.DelegatorAddress) { + genesisData.DistributionInfo.DelegatorStartingInfos.Has(validatorOperatorAddress) + StartingInfoMap, exists := genesisData.DistributionInfo.DelegatorStartingInfos.Get(validatorOperatorAddress) + if !exists || !StartingInfoMap.Has(delegatorAddress) { return nil, fmt.Errorf("delegator starting info not found") } - // end current period and calculate rewards - //endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewardsRaw, err := CalculateDelegationRewards(blockHeight, genesisData.DistributionInfo, val, del, endingPeriod) - if err != nil { - return nil, err - } - outstanding := genesisData.DistributionInfo.OutstandingRewards.MustGet(val.OperatorAddress) + delegatorRewards := genesisData.DistributionInfo.Rewards.MustGet(delegatorAddress) + rewardsRaw := delegatorRewards.MustGet(validatorOperatorAddress) + outstanding := genesisData.DistributionInfo.OutstandingRewards.MustGet(validatorOperatorAddress) // defensive edge case may happen on the very final digits // of the decCoins due to operation order of the distribution mechanism. @@ -657,8 +644,8 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val if logger != nil { logger.Error( "rounding error withdrawing rewards from validator", - "delegator", del.DelegatorAddress, - "validator", val.OperatorAddress, + "delegator", delegatorAddress, + "validator", validatorOperatorAddress, "got", rewards.String(), "expected", rewardsRaw.String(), ) @@ -670,7 +657,7 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val // add coins to user account if !finalRewards.IsZero() { - withdrawAddr := genesisData.DistributionInfo.GetDelegatorWithdrawAddr(del.DelegatorAddress) + withdrawAddr := genesisData.DistributionInfo.GetDelegatorWithdrawAddr(delegatorAddress) // SendCoinsFromModuleToAccount err := moveGenesisBalance(genesisData, genesisData.DistributionInfo.DistributionModuleAccountAddress, withdrawAddr, finalRewards, "delegation_reward", manifest, cudosCfg) @@ -682,7 +669,7 @@ func withdrawDelegationRewards(logger log.Logger, genesisData *GenesisData, val // update the outstanding rewards and the community pool only if the // transaction was successful - genesisData.DistributionInfo.OutstandingRewards.Set(val.OperatorAddress, outstanding.Sub(rewards)) + genesisData.DistributionInfo.OutstandingRewards.Set(validatorOperatorAddress, outstanding.Sub(rewards)) genesisData.DistributionInfo.FeePool.CommunityPool = genesisData.DistributionInfo.FeePool.CommunityPool.Add(remainder...) // decrement reference count of starting period From 945683b39c177920b75cd2ec2aa9af456a4210ef Mon Sep 17 00:00:00 2001 From: Jiri Date: Wed, 16 Oct 2024 11:53:23 +0200 Subject: [PATCH 05/11] Removed unwanted changes --- app/export.go | 2 +- app/upgrade_0_11_4_reconciliation.go | 4 ++-- app/upgrade_cudos.go | 20 +++++++++++--------- app/upgrade_cudos_distribution.go | 2 +- app/upgrade_v_11_4_network_config.go | 14 +++++++------- app/utils.go | 2 +- 6 files changed, 23 insertions(+), 21 deletions(-) diff --git a/app/export.go b/app/export.go index 4af90b043..a744e5496 100644 --- a/app/export.go +++ b/app/export.go @@ -54,7 +54,7 @@ func (app *App) ExportAppStateAndValidators( func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false - // check if there is a allowed Address list + // check if there is a allowed address list if len(jailAllowedAddrs) > 0 { applyAllowedAddrs = true } diff --git a/app/upgrade_0_11_4_reconciliation.go b/app/upgrade_0_11_4_reconciliation.go index 464b6967c..ad5657ebf 100644 --- a/app/upgrade_0_11_4_reconciliation.go +++ b/app/upgrade_0_11_4_reconciliation.go @@ -205,7 +205,7 @@ func (app *App) WithdrawReconciliationBalances(ctx types.Context, networkInfo *N } if !app.AccountKeeper.HasAccount(ctx, landingAddr) { - return fmt.Errorf("landing Address does not exist") + return fmt.Errorf("landing address does not exist") } transfers := UpgradeReconciliationTransfers{} @@ -480,7 +480,7 @@ func (app *App) DeleteContractStates(ctx types.Context, networkInfo *NetworkConf return nil } -// getContractData returns the contract Address, info, and states for a given contract Address +// getContractData returns the contract address, info, and states for a given contract address func (app *App) getContractData(ctx types.Context, contractAddr string) (*types.AccAddress, *types.KVStore, *prefix.Store, error) { addr, err := types.AccAddressFromBech32(contractAddr) if err != nil { diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index c4dfed175..f3d333ddd 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -44,9 +44,10 @@ const ( PermanentLockedAccount = "/cosmos.vesting.v1beta1.PermanentLockedAccount" PeriodicVestingAccount = "/cosmos.vesting.v1beta1.PeriodicVestingAccount" - UnbondedStatus = "BOND_STATUS_UNBONDED" - UnbondingStatus = "BOND_STATUS_UNBONDING" - BondedStatus = "BOND_STATUS_BONDED" + UnspecifiedBondStatus = "BOND_STATUS_UNSPECIFIED" + UnbondedStatus = "BOND_STATUS_UNBONDED" + UnbondingStatus = "BOND_STATUS_UNBONDING" + BondedStatus = "BOND_STATUS_BONDED" // Modules with balance BondedPoolAccName = "bonded_tokens_pool" @@ -247,7 +248,7 @@ func GetAccPrefix(jsonData map[string]interface{}) (string, error) { prefix, _, err := bech32.DecodeAndConvert(accountInfo.Address) if err != nil { - lastErr = fmt.Errorf("failed to decode Address %s: %w", accountInfo.Address, err) + lastErr = fmt.Errorf("failed to decode address %s: %w", accountInfo.Address, err) continue } @@ -432,7 +433,7 @@ func parseGenesisBaseAccount(baseAccData map[string]interface{}, accountInfo *Ac } accountInfo.Pubkey = AccPubKey - // Get raw Address + // Get raw address _, accRawAddr, err := bech32.DecodeAndConvert(accountInfo.Address) accountInfo.RawAddress = accRawAddr @@ -625,6 +626,7 @@ func parseGenesisDelegations(validators *OrderedMap[string, *ValidatorInfo], con resolvedDelegatorMap.Set(validatorOperatorAddress, resolvedDelegator.Add(delegatorTokens)) delegatedBalanceMap.Set(resolvedDelegatorAddress, resolvedDelegatorMap) } else { + // Store delegation to delegated map resolvedDelegatorMap, _ := unbondingDelegatedBalanceMap.GetOrSetDefault(resolvedDelegatorAddress, NewOrderedMap[string, sdk.Int]()) resolvedDelegator, _ := resolvedDelegatorMap.GetOrSetDefault(validatorOperatorAddress, sdk.NewInt(0)) @@ -1397,12 +1399,12 @@ func resolveIfContractAddress(address string, contracts *OrderedMap[string, *Con if !exists { return &address, nil } - // If the contract has an admin that is not itself, continue with the admin Address. + // If the contract has an admin that is not itself, continue with the admin address. if len(creatorsMap) == 0 && len(adminsMap) < RecursionDepthLimit && contractInfo.Admin != "" && contractInfo.Admin != address && !adminsMap[contractInfo.Admin] { adminsMap[contractInfo.Admin] = true address = contractInfo.Admin } else if len(creatorsMap) < RecursionDepthLimit && contractInfo.Creator != "" && !creatorsMap[contractInfo.Creator] { - // Otherwise, if the creator is present, continue with the creator Address. + // Otherwise, if the creator is present, continue with the creator address. creatorsMap[contractInfo.Creator] = true address = contractInfo.Creator } else { @@ -1432,7 +1434,7 @@ func decodePubKeyFromMap(pubKeyMap map[string]interface{}) (cryptotypes.PubKey, // Ensure the byte slice is the correct length for a secp256k1 public key if len(keyBytes) != secp256k1.PubKeySize { - return nil, fmt.Errorf("invalid Pubkey length: got %d, expected %d", len(keyBytes), secp256k1.PubKeySize) + return nil, fmt.Errorf("invalid pubkey length: got %d, expected %d", len(keyBytes), secp256k1.PubKeySize) } pubKey := secp256k1.PubKey{ @@ -1453,7 +1455,7 @@ func decodePubKeyFromMap(pubKeyMap map[string]interface{}) (cryptotypes.PubKey, // Ensure the byte slice is the correct length for an ed25519 public key if len(keyBytes) != ed25519.PubKeySize { - return nil, fmt.Errorf("invalid Pubkey length: got %d, expected %d", len(keyBytes), ed25519.PubKeySize) + return nil, fmt.Errorf("invalid pubkey length: got %d, expected %d", len(keyBytes), ed25519.PubKeySize) } pubKey := ed25519.PubKey{ diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index 22515e6d1..a4f945f56 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -615,7 +615,7 @@ func CalculateDelegationRewards(blockHeight uint64, distributionInfo *Distributi return rewards, nil } -// get the delegator withdraw Address, defaulting to the delegator Address +// get the delegator withdraw address, defaulting to the delegator address func (d DistributionInfo) GetDelegatorWithdrawAddr(delAddr string) string { b, exists := d.DelegatorWithdrawInfos.Get(delAddr) if !exists { diff --git a/app/upgrade_v_11_4_network_config.go b/app/upgrade_v_11_4_network_config.go index c3e9d580d..1db8dfc73 100644 --- a/app/upgrade_v_11_4_network_config.go +++ b/app/upgrade_v_11_4_network_config.go @@ -319,15 +319,15 @@ func LoadAndVerifyNetworkConfigFromFile(configFilePath string, expectedSha256Hex } type CudosMergeConfigJSON struct { - IbcTargetAddr string `json:"ibc_target_addr"` // Cudos Address + IbcTargetAddr string `json:"ibc_target_addr"` // Cudos address RemainingStakingBalanceAddr string `json:"remaining_staking_balance_addr"` // Cudos account for remaining bonded and not-bonded pool balances - RemainingGravityBalanceAddr string `json:"remaining_gravity_balance_addr"` // Cudos Address - RemainingDistributionBalanceAddr string `json:"remaining_distribution_balance_addr"` // Cudos Address - ContractDestinationFallbackAddr string `json:"contract_destination_fallback_addr"` // Cudos Address - CommunityPoolBalanceDestAddr string `json:"community_pool_balance_dest_addr,omitempty"` // Cudos Address, funds are moved to destination chain community pool if not set + RemainingGravityBalanceAddr string `json:"remaining_gravity_balance_addr"` // Cudos address + RemainingDistributionBalanceAddr string `json:"remaining_distribution_balance_addr"` // Cudos address + ContractDestinationFallbackAddr string `json:"contract_destination_fallback_addr"` // Cudos address + CommunityPoolBalanceDestAddr string `json:"community_pool_balance_dest_addr,omitempty"` // Cudos address, funds are moved to destination chain community pool if not set - CommissionFetchAddr string `json:"commission_fetch_addr"` // Fetch Address for commission - ExtraSupplyFetchAddr string `json:"extra_supply_fetch_addr"` // Fetch Address for extra supply + CommissionFetchAddr string `json:"commission_fetch_addr"` // Fetch address for commission + ExtraSupplyFetchAddr string `json:"extra_supply_fetch_addr"` // Fetch address for extra supply VestingCollisionDestAddr string `json:"vesting_collision_dest_addr"` // This gets converted to raw Address, so it can be fetch or cudos Address VestingPeriod int64 `json:"vesting_period"` // Vesting period diff --git a/app/utils.go b/app/utils.go index 158219a8e..01781db3b 100644 --- a/app/utils.go +++ b/app/utils.go @@ -76,7 +76,7 @@ func VerifyAddressPrefix(addr string, expectedPrefix string) error { } if prefix != expectedPrefix { - return fmt.Errorf("invalid Address prefix: expected %s, got %s", expectedPrefix, prefix) + return fmt.Errorf("invalid address prefix: expected %s, got %s", expectedPrefix, prefix) } return nil From 39752a15bf1b9b1fb823950f8b4b40ec86f6a74c Mon Sep 17 00:00:00 2001 From: Jiri Date: Wed, 16 Oct 2024 11:56:31 +0200 Subject: [PATCH 06/11] Removed unwanted comments and strings changes --- app/upgrade_0_11_4_reconciliation.go | 2 +- app/upgrade_cudos.go | 14 +++++++------- app/upgrade_cudos_distribution.go | 2 +- app/upgrade_v_11_4_network_config.go | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/upgrade_0_11_4_reconciliation.go b/app/upgrade_0_11_4_reconciliation.go index ad5657ebf..ba93ba118 100644 --- a/app/upgrade_0_11_4_reconciliation.go +++ b/app/upgrade_0_11_4_reconciliation.go @@ -484,7 +484,7 @@ func (app *App) DeleteContractStates(ctx types.Context, networkInfo *NetworkConf func (app *App) getContractData(ctx types.Context, contractAddr string) (*types.AccAddress, *types.KVStore, *prefix.Store, error) { addr, err := types.AccAddressFromBech32(contractAddr) if err != nil { - return nil, nil, nil, fmt.Errorf("invalid contract Address: %v", err) + return nil, nil, nil, fmt.Errorf("invalid contract address: %v", err) } store := ctx.KVStore(app.keys[wasmTypes.StoreKey]) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index f3d333ddd..990335940 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -820,7 +820,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa currentValidatorInfo := genesisData.Validators.MustGet(validatorOperatorAddress) delegatorTokens := currentValidatorInfo.TokensFromShares(delegation.Shares).TruncateInt() - // Move balance to delegator Address + // Move balance to delegator address delegatorBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, delegatorTokens)) if delegatorTokens.IsZero() { @@ -860,7 +860,7 @@ func withdrawGenesisStakingDelegations(logger log.Logger, genesisData *GenesisDa for _, entry := range unbondingDelegation.Entries { unbondingDelegationBalance := sdk.NewCoins(sdk.NewCoin(genesisData.BondDenom, entry.Balance)) - // Move unbonding balance from not-bonded pool to delegator Address + // Move unbonding balance from not-bonded pool to delegator address err := moveGenesisBalance(genesisData, genesisData.NotBondedPoolAddress, resolvedDelegatorAddress, unbondingDelegationBalance, "unbonding_delegation", manifest, cudosCfg) if err != nil { return err @@ -1382,10 +1382,10 @@ func resolveIfContractAddressWithFallback(address string, contracts *OrderedMap[ } if resolvedAddress == nil || strings.TrimSpace(*resolvedAddress) == "" { - // Use fallback Address + // Use fallback address return cudosCfg.Config.ContractDestinationFallbackAddr, nil } else { - // Use resolved Address + // Use resolved address return *resolvedAddress, nil } } @@ -1757,7 +1757,7 @@ func GetAddressByName(genesisAccounts *OrderedMap[string, *AccountInfo], name st } - return "", fmt.Errorf("Address not found in genesis accounts: %s", name) + return "", fmt.Errorf("address not found in genesis accounts: %s", name) } func checkDecTolerance(coins sdk.DecCoins, maxToleratedDiff sdk.Int) error { @@ -1820,11 +1820,11 @@ func resolveNewBaseAccount(ctx sdk.Context, app *App, genesisAccount *AccountInf var newBaseAccount *authtypes.BaseAccount var err error - // Check for Pubkey collision + // Check for pubkey collision if existingAccount != nil { // Handle collision - // Set Pubkey from newAcc if is not in existingAccount + // Set pubkey from newAcc if is not in existingAccount if existingAccount.GetPubKey() == nil && genesisAccount.Pubkey != nil { err := existingAccount.SetPubKey(genesisAccount.Pubkey) if err != nil { diff --git a/app/upgrade_cudos_distribution.go b/app/upgrade_cudos_distribution.go index a4f945f56..2c7e2a894 100644 --- a/app/upgrade_cudos_distribution.go +++ b/app/upgrade_cudos_distribution.go @@ -388,7 +388,7 @@ func withdrawGenesisDistributionRewards(logger log.Logger, genesisData *GenesisD return err } - // Withdraw Community pool balance to Address if defined + // Withdraw Community pool balance to address if defined communityBalance, _ := genesisData.DistributionInfo.FeePool.CommunityPool.TruncateDecimal() distributionModuleAccount := genesisData.Accounts.MustGet(genesisData.DistributionInfo.DistributionModuleAccountAddress) diff --git a/app/upgrade_v_11_4_network_config.go b/app/upgrade_v_11_4_network_config.go index 1db8dfc73..d62b708e7 100644 --- a/app/upgrade_v_11_4_network_config.go +++ b/app/upgrade_v_11_4_network_config.go @@ -328,7 +328,7 @@ type CudosMergeConfigJSON struct { CommissionFetchAddr string `json:"commission_fetch_addr"` // Fetch address for commission ExtraSupplyFetchAddr string `json:"extra_supply_fetch_addr"` // Fetch address for extra supply - VestingCollisionDestAddr string `json:"vesting_collision_dest_addr"` // This gets converted to raw Address, so it can be fetch or cudos Address + VestingCollisionDestAddr string `json:"vesting_collision_dest_addr"` // This gets converted to raw address, so it can be fetch or cudos address VestingPeriod int64 `json:"vesting_period"` // Vesting period From 8d4984783e3196568615d466e246935f5eb29de5 Mon Sep 17 00:00:00 2001 From: Jiri Date: Thu, 17 Oct 2024 10:46:49 +0200 Subject: [PATCH 07/11] Manifest extension --- app/upgrade_cudos.go | 116 ++++++++++++++++++++++++++++++++- app/upgrade_v_11_4_manifest.go | 14 ++++ 2 files changed, 127 insertions(+), 3 deletions(-) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index 990335940..61a12cc9b 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -127,7 +127,8 @@ type GenesisData struct { GravityModuleAccountAddress string - CollisionMap *OrderedMap[string, string] + CollisionMap *OrderedMap[string, string] + MovedAccounts *OrderedMap[string, bool] } func LoadCudosGenesis(app *App, manifest *UpgradeManifest) (*map[string]interface{}, *tmtypes.GenesisDoc, error) { @@ -196,6 +197,94 @@ func ProcessSourceNetworkGenesis(logger log.Logger, cudosCfg *CudosMergeConfig, return nil } +func writeMovedBalancesToManifest(genesisData *GenesisData, manifest *UpgradeManifest) error { + var upgradeBalances []UpgradeBalances + + for _, address := range genesisData.MovedAccounts.Keys() { + var upgradeBalance UpgradeBalances + upgradeBalance.Address = address + + if account, exists := genesisData.Accounts.Get(address); exists { + upgradeBalance.BankBalance = account.Balance + } + + } + + manifest.MovedBalances = upgradeBalances + + return nil +} + +func writeInitialBalancesToManifest(genesisData *GenesisData, manifest *UpgradeManifest) error { + var upgradeBalances []UpgradeBalances + + for i := range genesisData.Accounts.Iterate() { + address, account := i.Key, i.Value + + var upgradeBalance UpgradeBalances + upgradeBalance.Address = address + + // Bank balance + upgradeBalance.BankBalance = account.Balance + + if account.OriginalVesting != nil { + upgradeBalance.VestedBalance = account.OriginalVesting + } + + // Bonded tokens + if delegations, exists := genesisData.Delegations.Get(address); exists { + totalBalance := sdk.Coins{} + for i := range delegations.Iterate() { + _, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalBalance = totalBalance.Add(delegatedBalance) + } + upgradeBalance.BondedStakingBalance = totalBalance + } + + // Unbonding tokens + if delegations, exists := genesisData.UnbondingDelegations.Get(address); exists { + totalBalance := sdk.Coins{} + for i := range delegations.Iterate() { + _, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalBalance = totalBalance.Add(delegatedBalance) + } + upgradeBalance.UnbondingStakingBalance = totalBalance + } + + // Unbonded tokens + if delegations, exists := genesisData.UnbondedDelegations.Get(address); exists { + totalBalance := sdk.Coins{} + for i := range delegations.Iterate() { + _, delegatedAmount := i.Key, i.Value + delegatedBalance := sdk.NewCoin(genesisData.BondDenom, delegatedAmount) + totalBalance = totalBalance.Add(delegatedBalance) + } + upgradeBalance.UnbondedStakingBalance = totalBalance + } + + // Get distribution module rewards + if DelegatorRewards, exists := genesisData.DistributionInfo.Rewards.Get(address); exists { + totalBalance := sdk.Coins{} + for j := range DelegatorRewards.Iterate() { + _, rewardDecAmount := j.Key, j.Value + rewardAmount, _ := rewardDecAmount.TruncateDecimal() + if !rewardAmount.IsZero() { + totalBalance = totalBalance.Add(rewardAmount...) + } + } + upgradeBalance.DistributionRewards = totalBalance + } + + upgradeBalances = append(upgradeBalances, upgradeBalance) + } + + manifest.InitialBalances = upgradeBalances + + return nil +} + func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeConfig, genesisData *GenesisData, manifest *UpgradeManifest) error { if cudosCfg == nil { return fmt.Errorf("cudos merge: cudos CudosMergeConfig not provided (null pointer passed in)") @@ -205,7 +294,12 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon return fmt.Errorf("cudos merge: cudos path not set") } - err := ProcessSourceNetworkGenesis(app.Logger(), cudosCfg, genesisData, manifest) + err := writeInitialBalancesToManifest(genesisData, manifest) + if err != nil { + return fmt.Errorf("cudos merge: failed to write initial balances to manifest: %w", err) + } + + err = ProcessSourceNetworkGenesis(app.Logger(), cudosCfg, genesisData, manifest) if err != nil { return err } @@ -220,6 +314,11 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon return fmt.Errorf("cudos merge: failed process delegations: %w", err) } + err = writeMovedBalancesToManifest(genesisData, manifest) + if err != nil { + return fmt.Errorf("cudos merge: failed to write moved balances to manifest") + } + err = verifySupply(app, ctx, cudosCfg, manifest) if err != nil { return fmt.Errorf("cudos merge: failed to verify supply: %w", err) @@ -1562,7 +1661,7 @@ func markAccountAsMigrated(genesisData *GenesisData, accountAddress string) erro return nil } -func registerBalanceMovement(fromAddress, toAddress string, sourceAmount sdk.Coins, destAmount sdk.Coins, memo string, manifest *UpgradeManifest) { +func registerMintedBalanceMovement(fromAddress, toAddress string, sourceAmount sdk.Coins, destAmount sdk.Coins, memo string, manifest *UpgradeManifest) { if manifest.MoveMintedBalance == nil { manifest.MoveMintedBalance = &UpgradeMoveMintedBalance{} @@ -1671,6 +1770,13 @@ func registerManifestBalanceMovement(fromAddress, toAddress string, amount sdk.C } +func markAccountBalanceAsMoved(genesisData *GenesisData, address string) { + if genesisData.MovedAccounts == nil { + genesisData.MovedAccounts = NewOrderedMap[string, bool]() + } + genesisData.MovedAccounts.Set(address, true) +} + func moveGenesisBalance(genesisData *GenesisData, fromAddress, toAddress string, amount sdk.Coins, memo string, manifest *UpgradeManifest, cudosCfg *CudosMergeConfig) error { // Check if fromAddress exists if _, ok := genesisData.Accounts.Get(fromAddress); !ok { @@ -1699,6 +1805,8 @@ func moveGenesisBalance(genesisData *GenesisData, fromAddress, toAddress string, genesisData.Accounts.Set(toAddress, genesisToBalance) genesisData.Accounts.Set(fromAddress, genesisFromBalance) + markAccountBalanceAsMoved(genesisData, fromAddress) + markAccountBalanceAsMoved(genesisData, toAddress) registerManifestBalanceMovement(fromAddress, toAddress, amount, memo, manifest) return nil @@ -1721,6 +1829,7 @@ func createGenesisBalance(genesisData *GenesisData, toAddress string, amount sdk genesisData.Accounts.Set(toAddress, genesisToBalance) + markAccountBalanceAsMoved(genesisData, toAddress) registerManifestBalanceMovement("", toAddress, amount, memo, manifest) return nil @@ -1741,6 +1850,7 @@ func removeGenesisBalance(genesisData *GenesisData, address string, amount sdk.C genesisData.Accounts.Set(address, genesisAccount) + markAccountBalanceAsMoved(genesisData, address) registerManifestBalanceMovement(address, "", amount, memo, manifest) return nil diff --git a/app/upgrade_v_11_4_manifest.go b/app/upgrade_v_11_4_manifest.go index d875ee73a..57038ee9e 100644 --- a/app/upgrade_v_11_4_manifest.go +++ b/app/upgrade_v_11_4_manifest.go @@ -13,6 +13,9 @@ import ( const manifestFilenameBase = "upgrade_manifest.json" type UpgradeManifest struct { + MovedBalances []UpgradeBalances `json:"moved_balances,omitempty"` + InitialBalances []UpgradeBalances `json:"initial_balances,omitempty"` + // Following 2 hash data members are intentionally without `omitempty` parameter in `json:...` decorator GenesisFileSha256 string `json:"genesis_file_sha256"` NetworkConfigFileSha256 string `json:"network_config_file_sha256"` @@ -178,6 +181,17 @@ type UpgradeAccountCreation struct { Reason string `json:"reason"` } +type UpgradeBalances struct { + Address string `json:"address"` + BankBalance types.Coins `json:"bank_balance"` + VestedBalance types.Coins `json:"vested_balance,omitempty"` + BondedStakingBalance types.Coins `json:"bonded_staking_balance,omitempty"` + UnbondedStakingBalance types.Coins `json:"unbonded_staking_balance,omitempty"` + UnbondingStakingBalance types.Coins `json:"unbonding_staking_balance,omitempty"` + DistributionRewards types.Coins `json:"distribution_rewards,omitempty"` + Memo string `json:"memo,omitempty"` +} + // app.UpgradeKeeper.GetUpgradeInfoPath() // if upgradeFilePath, err = app.UpgradeKeeper.GetUpgradeInfoPath(); err != nil { // return "", err From 4b0a092c035065a03f02a5d1a6a8247557d085d3 Mon Sep 17 00:00:00 2001 From: Jiri Date: Thu, 17 Oct 2024 13:20:37 +0200 Subject: [PATCH 08/11] Refactor fix --- app/upgrade_cudos.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index 61a12cc9b..070baf55c 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -164,7 +164,12 @@ func LoadCudosGenesis(app *App, manifest *UpgradeManifest) (*map[string]interfac } func ProcessSourceNetworkGenesis(logger log.Logger, cudosCfg *CudosMergeConfig, genesisData *GenesisData, manifest *UpgradeManifest) error { - err := genesisUpgradeWithdrawIBCChannelsBalances(genesisData, cudosCfg, manifest) + err := writeInitialBalancesToManifest(genesisData, manifest) + if err != nil { + return fmt.Errorf("cudos merge: failed to write initial balances to manifest: %w", err) + } + + err = genesisUpgradeWithdrawIBCChannelsBalances(genesisData, cudosCfg, manifest) if err != nil { return fmt.Errorf("cudos merge: failed to withdraw IBC channels balances: %w", err) } @@ -194,6 +199,11 @@ func ProcessSourceNetworkGenesis(logger log.Logger, cudosCfg *CudosMergeConfig, return fmt.Errorf("cudos merge: failed to move funds: %w", err) } + err = writeMovedBalancesToManifest(genesisData, manifest) + if err != nil { + return fmt.Errorf("cudos merge: failed to write moved balances to manifest") + } + return nil } @@ -294,12 +304,7 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon return fmt.Errorf("cudos merge: cudos path not set") } - err := writeInitialBalancesToManifest(genesisData, manifest) - if err != nil { - return fmt.Errorf("cudos merge: failed to write initial balances to manifest: %w", err) - } - - err = ProcessSourceNetworkGenesis(app.Logger(), cudosCfg, genesisData, manifest) + err := ProcessSourceNetworkGenesis(app.Logger(), cudosCfg, genesisData, manifest) if err != nil { return err } @@ -314,11 +319,6 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon return fmt.Errorf("cudos merge: failed process delegations: %w", err) } - err = writeMovedBalancesToManifest(genesisData, manifest) - if err != nil { - return fmt.Errorf("cudos merge: failed to write moved balances to manifest") - } - err = verifySupply(app, ctx, cudosCfg, manifest) if err != nil { return fmt.Errorf("cudos merge: failed to verify supply: %w", err) From e725b8932b373174c4f85ba7de576a85a67194b0 Mon Sep 17 00:00:00 2001 From: Jiri Date: Thu, 17 Oct 2024 16:16:13 +0200 Subject: [PATCH 09/11] fix --- app/upgrade_cudos.go | 1 + 1 file changed, 1 insertion(+) diff --git a/app/upgrade_cudos.go b/app/upgrade_cudos.go index 70bb685e5..c724ec1b1 100644 --- a/app/upgrade_cudos.go +++ b/app/upgrade_cudos.go @@ -217,6 +217,7 @@ func writeMovedBalancesToManifest(genesisData *GenesisData, manifest *UpgradeMan if account, exists := genesisData.Accounts.Get(address); exists { upgradeBalance.BankBalance = account.Balance } + upgradeBalances = append(upgradeBalances, upgradeBalance) } From a90e7a7f75b31e82039560651bf4637f4a7ea688 Mon Sep 17 00:00:00 2001 From: Jiri Date: Thu, 17 Oct 2024 16:34:34 +0200 Subject: [PATCH 10/11] manifest data cmd --- app/upgrade_v_11_4_manifest.go | 25 +++++++ cmd/fetchd/cmd/cudos_merge.go | 133 +++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) diff --git a/app/upgrade_v_11_4_manifest.go b/app/upgrade_v_11_4_manifest.go index a9e19718a..27e03a32b 100644 --- a/app/upgrade_v_11_4_manifest.go +++ b/app/upgrade_v_11_4_manifest.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "io" "os" "path" ) @@ -254,6 +255,30 @@ func SaveManifestToPath(manifest *UpgradeManifest, manifestFilePath string) erro return nil } +func LoadManifestFromPath(manifestFilePath string) (*UpgradeManifest, error) { + var manifest UpgradeManifest + + // Open the file + file, err := os.Open(manifestFilePath) + if err != nil { + return nil, fmt.Errorf("failed to open file \"%s\": %w", manifestFilePath, err) + } + defer file.Close() + + // Read the file contents + fileContents, err := io.ReadAll(file) + if err != nil { + return nil, fmt.Errorf("failed to read file \"%s\": %w", manifestFilePath, err) + } + + // Unmarshal the JSON content into the manifest + if err := json.Unmarshal(fileContents, &manifest); err != nil { + return nil, fmt.Errorf("failed to unmarshal manifest from file \"%s\": %w", manifestFilePath, err) + } + + return &manifest, nil +} + func RegisterVestingCollision(manifest *UpgradeManifest, originalAccount *AccountInfo, targetAccountFunds types.Coins, targetAccount authtypes.AccountI) error { if manifest.VestingCollision == nil { manifest.VestingCollision = &UpgradeVestingCollision{} diff --git a/cmd/fetchd/cmd/cudos_merge.go b/cmd/fetchd/cmd/cudos_merge.go index 5c427565a..3f741382c 100644 --- a/cmd/fetchd/cmd/cudos_merge.go +++ b/cmd/fetchd/cmd/cudos_merge.go @@ -116,6 +116,30 @@ It utilizes the provided network merge config and genesis JSON files to perform networkMergeCmd.AddCommand(cmd) } +func AddCommandManifestAddressInfo(networkMergeCmd *cobra.Command) { + cmd := &cobra.Command{ + Use: "manifest-address-info [manifest_file_path] [address]", + Short: "Extracts balance information for a specific address", + Long: `This command retrieves all balance information for a given address from almanac, including the amount delegated to validators, and rewards.`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := client.GetClientContextFromCmd(cmd) + + manifestFilePath := args[0] + address := args[1] + + // Call a function to extract address info + err := AlmanacAddressInfo(manifestFilePath, address, ctx) + if err != nil { + return err + } + return nil + }, + } + + networkMergeCmd.AddCommand(cmd) +} + func utilNetworkMergeCommand() *cobra.Command { cmd := &cobra.Command{ Use: "network-merge", @@ -127,6 +151,8 @@ func utilNetworkMergeCommand() *cobra.Command { AddCommandVerify(cmd) AddCommandExtractAddressInfo(cmd) + AddCommandManifestAddressInfo(cmd) + return cmd } @@ -414,3 +440,110 @@ func printAccInfo(genesisData *app.GenesisData, address string, ctx client.Conte return nil } + +type ManifestData struct { + InitialBalances *app.OrderedMap[string, app.UpgradeBalances] + MovedBalances *app.OrderedMap[string, app.UpgradeBalances] +} + +func parseManifestData(manifest *app.UpgradeManifest) (*ManifestData, error) { + manifestData := ManifestData{} + + manifestData.InitialBalances = app.NewOrderedMap[string, app.UpgradeBalances]() + for _, initialBalanceEntry := range manifest.InitialBalances { + manifestData.InitialBalances.SetNew(initialBalanceEntry.Address, initialBalanceEntry) + } + + manifestData.MovedBalances = app.NewOrderedMap[string, app.UpgradeBalances]() + for _, movedBalanceEntry := range manifest.MovedBalances { + manifestData.MovedBalances.SetNew(movedBalanceEntry.Address, movedBalanceEntry) + } + + return &manifestData, nil +} + +func printBalancesEntry(upgradeBalances app.UpgradeBalances, ctx client.Context) error { + if !upgradeBalances.BankBalance.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Bank balance: %s\n", upgradeBalances.BankBalance)) + if err != nil { + return err + } + } + + if !upgradeBalances.VestedBalance.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Vested balance: %s\n", upgradeBalances.VestedBalance)) + if err != nil { + return err + } + } + + if !upgradeBalances.BondedStakingBalance.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Bonded staking balance: %s\n", upgradeBalances.BondedStakingBalance)) + if err != nil { + return err + } + } + + if !upgradeBalances.UnbondedStakingBalance.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Unbonded staking balance: %s\n", upgradeBalances.UnbondedStakingBalance)) + if err != nil { + return err + } + } + + if !upgradeBalances.UnbondingStakingBalance.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Unbonding staking balance: %s\n", upgradeBalances.UnbondingStakingBalance)) + if err != nil { + return err + } + } + + if !upgradeBalances.DistributionRewards.IsZero() { + err := ctx.PrintString(fmt.Sprintf("Distribution rewards: %s\n", upgradeBalances.DistributionRewards)) + if err != nil { + return err + } + } + + return nil +} + +func AlmanacAddressInfo(almanacFilePath string, address string, ctx client.Context) error { + manifest := app.NewUpgradeManifest() + + manifest, err := app.LoadManifestFromPath(almanacFilePath) + if err != nil { + return err + } + + manifestData, err := parseManifestData(manifest) + if err != nil { + return err + } + + err = ctx.PrintString("Initial balances:\n") + if err != nil { + return err + } + + if InitialBalances, exists := manifestData.InitialBalances.Get(address); exists { + err = printBalancesEntry(InitialBalances, ctx) + if err != nil { + return err + } + } + + err = ctx.PrintString("Moved balances:\n") + if err != nil { + return err + } + + if MovedBalances, exists := manifestData.MovedBalances.Get(address); exists { + err = printBalancesEntry(MovedBalances, ctx) + if err != nil { + return err + } + } + + return nil +} From 52af58046b60e12275ddd02a227b4784458ed557 Mon Sep 17 00:00:00 2001 From: Peter Bukva Date: Fri, 18 Oct 2024 16:07:19 +0100 Subject: [PATCH 11/11] Resurrecting cleanup of Almanac & AName contracts state --- app/upgrade_0_11_4_reconciliation.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/upgrade_0_11_4_reconciliation.go b/app/upgrade_0_11_4_reconciliation.go index ba93ba118..e82359f28 100644 --- a/app/upgrade_0_11_4_reconciliation.go +++ b/app/upgrade_0_11_4_reconciliation.go @@ -466,9 +466,8 @@ func (app *App) DeleteContractStates(ctx types.Context, networkInfo *NetworkConf contractsToWipe = networkInfo.Contracts.Reconciliation.GetContracts(contractsToWipe) - // NOTE(jv): Commented out intentionally - //contractsToWipe = networkInfo.Contracts.Almanac.GetContracts(contractsToWipe) - //contractsToWipe = networkInfo.Contracts.AName.GetContracts(contractsToWipe) + contractsToWipe = networkInfo.Contracts.Almanac.GetContracts(contractsToWipe) + contractsToWipe = networkInfo.Contracts.AName.GetContracts(contractsToWipe) for _, contract := range contractsToWipe { err := app.DeleteContractState(ctx, contract, manifest)