Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Cudos menifest block height and community pool balance refactor #385

Merged
merged 5 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ func New(

app.GovKeeper = *govKeeper.SetHooks(
govtypes.NewMultiGovHooks(
// register the governance hooks
// register the governance hooks
),
)

Expand Down Expand Up @@ -758,9 +758,6 @@ func getNetworkInfo(app *App, ctx *sdk.Context, manifest *UpgradeManifest, expec
return nil, fmt.Errorf("network info not found for chain id: %s", ctx.ChainID())
}

manifest.MergeSourceChainID = expectedChainIdOfMergeSourceGenesis
manifest.DestinationChainID = ctx.ChainID()

return networkInfo, nil
}

Expand All @@ -779,7 +776,7 @@ func LoadAndParseMergeSourceInputFiles(app *App, ctx *sdk.Context, manifest *Upg

cudosConfig := NewCudosMergeConfig(networkInfo.CudosMerge)

genesisData, err := parseGenesisData(*cudosJsonData, cudosConfig, manifest)
genesisData, err := parseGenesisData(*cudosJsonData, cudosGenDoc, cudosConfig, manifest)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse genesis data: %w", err)
}
Expand All @@ -801,6 +798,14 @@ func (app *App) RegisterUpgradeHandlers(cfg module.Configurator) {
return nil, fmt.Errorf("cudos merge: %w", err)
}

manifest.DestinationChainBlockHeight = cudosGenesisData.blockHeight
manifest.DestinationChainID = cudosGenesisData.chainId

manifest.SourceChainBlockHeight = ctx.BlockHeight()
manifest.MergeSourceChainID = ctx.ChainID()

MissingNO57 marked this conversation as resolved.
Show resolved Hide resolved
manifest.GovProposalUpgradePlanName = plan.Name

err = app.DeleteContractStates(ctx, networkInfo, manifest)
if err != nil {
return nil, err
Expand Down
95 changes: 51 additions & 44 deletions app/upgrade_cudos.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
Expand All @@ -35,8 +34,6 @@ const (
ValAddressPrefix = "valoper"
ConsAddressPrefix = "valcons"

NewAddrPrefix = "fetch"

FlagGenesisTime = "genesis-time"

ModuleAccount = "/cosmos.auth.v1beta1.ModuleAccount"
Expand Down Expand Up @@ -65,24 +62,6 @@ const (
RecursionDepthLimit = 50
)

func convertAddressToFetch(addr string, addressPrefix string) (string, error) {
_, decodedAddrData, err := bech32.DecodeAndConvert(addr)
if err != nil {
return "", err
}

newAddress, err := bech32.ConvertAndEncode(NewAddrPrefix+addressPrefix, decodedAddrData)
if err != nil {
return "", err
}

err = sdk.VerifyAddressFormat(decodedAddrData)
if err != nil {
return "", err
}

return newAddress, nil
}
func convertAddressPrefix(addr string, newPrefix string) (string, error) {
_, decodedAddrData, err := bech32.DecodeAndConvert(addr)
if err != nil {
Expand All @@ -100,7 +79,7 @@ func convertAddressPrefix(addr string, newPrefix string) (string, error) {
func convertAddressToRaw(addr string, cudosCfg *CudosMergeConfig) (sdk.AccAddress, error) {
prefix, decodedAddrData, err := bech32.DecodeAndConvert(addr)

if prefix != cudosCfg.config.OldAddrPrefix {
if prefix != cudosCfg.config.SourceChainAddressPrefix {
return nil, fmt.Errorf("unknown prefix: %s", prefix)
}

Expand All @@ -126,6 +105,8 @@ const (

type GenesisData struct {
totalSupply sdk.Coins
blockHeight int64
chainId string

accounts *OrderedMap[string, *AccountInfo]
contracts *OrderedMap[string, *ContractInfo]
Expand Down Expand Up @@ -233,11 +214,6 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon
return fmt.Errorf("cudos merge: failed process delegations: %w", err)
}

err = fundCommunityPool(ctx, app, genesisData, cudosCfg, manifest)
if err != nil {
return fmt.Errorf("cudos merge: failed to fund community pool: %w", err)
}

err = verifySupply(genesisData, cudosCfg, manifest)
if err != nil {
return fmt.Errorf("cudos merge: failed to verify supply: %w", err)
Expand All @@ -246,14 +222,16 @@ func CudosMergeUpgradeHandler(app *App, ctx sdk.Context, cudosCfg *CudosMergeCon
return nil
}

func parseGenesisData(jsonData map[string]interface{}, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) (*GenesisData, error) {
func parseGenesisData(jsonData map[string]interface{}, genDoc *tmtypes.GenesisDoc, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) (*GenesisData, error) {
genesisData := GenesisData{}

totalSupply, err := parseGenesisTotalSupply(jsonData)
if err != nil {
return nil, fmt.Errorf("failed to get total supply: %w", err)
}
genesisData.totalSupply = totalSupply
genesisData.blockHeight = genDoc.InitialHeight
genesisData.chainId = genDoc.ChainID

genesisData.contracts, err = parseGenesisWasmContracts(jsonData)
if err != nil {
Expand Down Expand Up @@ -880,39 +858,43 @@ func createDelegation(ctx sdk.Context, app *App, originalValidator string, newDe
return nil
}

func fundCommunityPool(ctx sdk.Context, app *App, genesisData *GenesisData, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error {
// Fund community pool
func handleCommunityPoolBalance(ctx sdk.Context, app *App, genesisData *GenesisData, cudosCfg *CudosMergeConfig, manifest *UpgradeManifest) error {

// Get addresses and amounts
RemainingDistributionBalanceAccount := genesisData.accounts.MustGet(cudosCfg.config.RemainingDistributionBalanceAddr)
communityPoolBalance, _ := genesisData.distributionInfo.feePool.communityPool.TruncateDecimal()
convertedCommunityPoolBalance, err := convertBalance(communityPoolBalance, cudosCfg)
if err != nil {
return err
}

communityPoolSourceAccountRawAddress := genesisData.accounts.MustGet(cudosCfg.config.RemainingDistributionBalanceAddr).rawAddress

if cudosCfg.config.CommunityPoolBalanceDestAddr == "" {
// Move balance to community pool if destination address is not set
// If community pool balance destination address is not we move community pool balance to destination chain community pool

err = app.DistrKeeper.FundCommunityPool(ctx, convertedCommunityPoolBalance, communityPoolSourceAccountRawAddress)
// 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
}

registerBalanceMovement(cudosCfg.config.RemainingDistributionBalanceAddr, distrtypes.ModuleName, communityPoolBalance, convertedCommunityPoolBalance, "community_pool_balance", manifest)

} else {
// Move balance to given account

destAccRawAddr, err := convertAddressToRaw(cudosCfg.config.CommunityPoolBalanceDestAddr, cudosCfg)
// Move balance to destination chain community pool
err = app.DistrKeeper.FundCommunityPool(ctx, convertedCommunityPoolBalance, RemainingDistributionBalanceAccount.rawAddress)
if err != nil {
return err
}

err = app.BankKeeper.SendCoins(ctx, communityPoolSourceAccountRawAddress, destAccRawAddr, convertedCommunityPoolBalance)
// Subtract balance from genesis balances
err = removeGenesisBalance(genesisData, cudosCfg.config.RemainingDistributionBalanceAddr, communityPoolBalance, "community_pool_balance", manifest)
if err != nil {
return err
}
registerBalanceMovement(cudosCfg.config.RemainingDistributionBalanceAddr, cudosCfg.config.CommunityPoolBalanceDestAddr, communityPoolBalance, convertedCommunityPoolBalance, "community_pool_balance", manifest)

} 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)
if err != nil {
return fmt.Errorf("failed to move community pool balance %w", err)
}

}

Expand Down Expand Up @@ -1208,7 +1190,7 @@ func parseGenesisIBCAccounts(jsonData map[string]interface{}, cudosCfg *CudosMer
}

rawAddr := ibctransfertypes.GetEscrowAddress(portId, channelId)
channelAddr, err := sdk.Bech32ifyAddressBytes(cudosCfg.config.OldAddrPrefix, rawAddr)
channelAddr, err := sdk.Bech32ifyAddressBytes(cudosCfg.config.SourceChainAddressPrefix, rawAddr)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -1596,6 +1578,26 @@ func createGenesisBalance(genesisData *GenesisData, toAddress string, amount sdk
return nil
}

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)
}

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)

genesisData.accounts.Set(address, genesisAccount)

registerManifestBalanceMovement(address, "", amount, memo, manifest)

return nil
}

func GetAddressByName(genesisAccounts *OrderedMap[string, *AccountInfo], name string) (string, error) {

for _, accAddress := range genesisAccounts.Keys() {
Expand Down Expand Up @@ -1786,7 +1788,7 @@ func MigrateGenesisAccounts(genesisData *GenesisData, ctx sdk.Context, app *App,
err = migrateToAccount(ctx, app, "mint_module", commissionRawAcc, sdk.NewCoins(), totalCommission, "total_commission", manifest)

extraSupplyInCudos := cudosCfg.config.TotalCudosSupply.Sub(genesisData.totalSupply.AmountOf(cudosCfg.config.OriginalDenom))
extraSupplyCudosAddress, err := convertAddressPrefix(cudosCfg.config.ExtraSupplyFetchAddr, cudosCfg.config.OldAddrPrefix)
extraSupplyCudosAddress, err := convertAddressPrefix(cudosCfg.config.ExtraSupplyFetchAddr, cudosCfg.config.SourceChainAddressPrefix)
if err != nil {
return err
}
Expand All @@ -1798,6 +1800,11 @@ func MigrateGenesisAccounts(genesisData *GenesisData, ctx sdk.Context, app *App,
return err
}

err = handleCommunityPoolBalance(ctx, app, genesisData, cudosCfg, manifest)
if err != nil {
return fmt.Errorf("failed to handle community pool balance: %w", err)
}

// Mint the rest of the supply
for _, genesisAccountAddress := range genesisData.accounts.Keys() {
genesisAccount := genesisData.accounts.MustGet(genesisAccountAddress)
Expand Down
10 changes: 6 additions & 4 deletions app/upgrade_cudos_distribution.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,11 +391,13 @@ func withdrawGenesisDistributionRewards(app *App, genesisData *GenesisData, cudo
return err
}

// Withdraw remaining balance
// Withdraw Community pool balance to address if defined
communityBalance, _ := genesisData.distributionInfo.feePool.communityPool.TruncateDecimal()
distributionModuleAccount := genesisData.accounts.MustGet(genesisData.distributionInfo.distributionModuleAccountAddress)

communityBalance, _ := genesisData.distributionInfo.feePool.communityPool.TruncateDecimal()
remainingBalance := distributionModuleAccount.balance.Sub(communityBalance)

// Withdraw remaining balance
app.Logger().Info("cudos merge: remaining dist balance", "amount", remainingBalance.String())

// TODO: Write to manifest?
Expand All @@ -417,7 +419,7 @@ func withdrawAccumulatedCommissions(genesisData *GenesisData, cudosCfg *CudosMer
for _, validatorAddress := range genesisData.distributionInfo.validatorAccumulatedCommissions.Keys() {
accumulatedCommission := genesisData.distributionInfo.validatorAccumulatedCommissions.MustGet(validatorAddress)

accountAddress, err := convertAddressPrefix(validatorAddress, cudosCfg.config.OldAddrPrefix)
accountAddress, err := convertAddressPrefix(validatorAddress, cudosCfg.config.SourceChainAddressPrefix)
if err != nil {
return err
}
Expand All @@ -438,7 +440,7 @@ func withdrawValidatorOutstandingRewards(genesisData *GenesisData, cudosCfg *Cud
for _, validatorAddress := range genesisData.distributionInfo.outstandingRewards.Keys() {
outstandingRewards := genesisData.distributionInfo.outstandingRewards.MustGet(validatorAddress)

accountAddress, err := convertAddressPrefix(validatorAddress, cudosCfg.config.OldAddrPrefix)
accountAddress, err := convertAddressPrefix(validatorAddress, cudosCfg.config.SourceChainAddressPrefix)
if err != nil {
return err
}
Expand Down
32 changes: 18 additions & 14 deletions app/upgrade_v_11_4_manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,24 @@ const manifestFilenameBase = "upgrade_manifest.json"

type UpgradeManifest struct {
// 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"`
MergeSourceChainID string `json:"merge_source_chain_id"`
DestinationChainID string `json:"destination_chain_id"`
Reconciliation *UpgradeReconciliation `json:"reconciliation,omitempty"`
Contracts *Contracts `json:"contracts,omitempty"`
IBC *UpgradeIBCTransfers `json:"ibc,omitempty"`
Migration *UpgradeMigation `json:"migration,omitempty"`
MoveGenesisBalance *UpgradeMoveGenesisBalance `json:"move_genesis_balance,omitempty"`
Delegate *UpgradeDelegate `json:"delegate,omitempty"`
MoveMintedBalance *UpgradeMoveMintedBalance `json:"move_minted_balance,omitempty"`
VestingCollision *UpgradeVestingCollision `json:"vesting_collision,omitempty"`
MoveDelegations *UpgradeMoveDelegations `json:"move_delegation,omitempty"`
CreatedAccounts *UpgradeCreatedAccounts `json:"created_accounts,omitempty"`
GenesisFileSha256 string `json:"genesis_file_sha256"`
NetworkConfigFileSha256 string `json:"network_config_file_sha256"`
MergeSourceChainID string `json:"merge_source_chain_id"`
DestinationChainID string `json:"destination_chain_id"`
SourceChainBlockHeight int64 `json:"source_chain_block_height"`
DestinationChainBlockHeight int64 `json:"destination_chain_block_height"`
GovProposalUpgradePlanName string `json:"gov_proposal_upgrade_plan_name"`

MissingNO57 marked this conversation as resolved.
Show resolved Hide resolved
Reconciliation *UpgradeReconciliation `json:"reconciliation,omitempty"`
Contracts *Contracts `json:"contracts,omitempty"`
IBC *UpgradeIBCTransfers `json:"ibc,omitempty"`
Migration *UpgradeMigation `json:"migration,omitempty"`
MoveGenesisBalance *UpgradeMoveGenesisBalance `json:"move_genesis_balance,omitempty"`
Delegate *UpgradeDelegate `json:"delegate,omitempty"`
MoveMintedBalance *UpgradeMoveMintedBalance `json:"move_minted_balance,omitempty"`
VestingCollision *UpgradeVestingCollision `json:"vesting_collision,omitempty"`
MoveDelegations *UpgradeMoveDelegations `json:"move_delegation,omitempty"`
CreatedAccounts *UpgradeCreatedAccounts `json:"created_accounts,omitempty"`
}

func NewUpgradeManifest() *UpgradeManifest {
Expand Down
42 changes: 13 additions & 29 deletions app/upgrade_v_11_4_network_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ var NetworkInfos = map[string]NetworkConfig{
VestingCollisionDestAddr: "fetch122j02czdt5ca8cf576wy2hassyxyx67wg5xmgc", // Replace!!
CommunityPoolBalanceDestAddr: "cudos1nj49l56x7sss5hqyvfmctxr3mq64whg273g3x5",

NewAddrPrefix: "fetch",
OldAddrPrefix: "cudos",
SourceChainAddressPrefix: "cudos",

OriginalDenom: "acudos",
ConvertedDenom: "afet",
Expand Down Expand Up @@ -145,8 +144,7 @@ var NetworkInfos = map[string]NetworkConfig{
VestingCollisionDestAddr: "cudos1nj49l56x7sss5hqyvfmctxr3mq64whg273g3x5",
CommunityPoolBalanceDestAddr: "cudos1dslwarknhfsw3pfjzxxf5mn28q3ewfectw0gta",

NewAddrPrefix: "fetch",
OldAddrPrefix: "cudos",
SourceChainAddressPrefix: "cudos",

OriginalDenom: "acudos",
ConvertedDenom: "atestfet",
Expand Down Expand Up @@ -314,14 +312,13 @@ type CudosMergeConfigJSON struct {
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"` // 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
CommunityPoolBalanceDestAddr string `json:"community_pool_balance_dest_addr"` // This gets converted to raw address, so it can be fetch or cudos address
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

NewAddrPrefix string `json:"new_addr_prefix"`
OldAddrPrefix string `json:"old_addr_prefix"`
SourceChainAddressPrefix string `json:"old_addr_prefix"`

OriginalDenom string `json:"original_denom"`
ConvertedDenom string `json:"converted_denom"`
Expand Down Expand Up @@ -365,25 +362,12 @@ func NewCudosMergeConfig(config *CudosMergeConfigJSON) *CudosMergeConfig {
retval.MovedAccounts = NewOrderedMapFromPairs(config.MovedAccounts)
retval.validatorsMap = NewOrderedMapFromPairs(config.ValidatorsMap)

//for _, exchangeRate := range config.BalanceConversionConstants {
// retval.BalanceConversionConstants.SetNew(exchangeRate.Denom, exchangeRate.ExchangeRate)
//}

//for _, account := range config.NotVestedAccounts {
// retval.NotVestedAccounts.SetNew(account, true)
//}

//for _, account := range config.NotDelegatedAccounts {
// retval.NotDelegatedAccounts.SetNew(account, true)
//}

//for _, account := range config.MovedAccounts {
// retval.MovedAccounts.SetNew(account.FromAccountAddr, account.ToAccountAddr)
//}

//for _, validator := range config.ValidatorsMap {
// retval.ValidatorsMap.SetNew(validator.FromCudosValidatorOperatorAddr, validator.ToFetchValidatorOperatorOperAddr)
//}
// Ensure that commission address won't be vested
commissionCudosAddress, err := convertAddressPrefix(config.CommissionFetchAddr, config.SourceChainAddressPrefix)
if err != nil {
return nil
}
retval.notVestedAccounts.Set(commissionCudosAddress, true)

return retval
}
Expand Down
Loading