Skip to content

Commit

Permalink
Claim module - April 5 rebase (osmosis-labs#72)
Browse files Browse the repository at this point in the history
* claim module + genesis generator command prototype

* Update x/claim/spec/README.md

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/spec/README.md

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/spec/README.md

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/keeper/claim.go

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/keeper/claim.go

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/keeper/claim.go

Co-authored-by: Dev Ojha <[email protected]>

* add description about claimables

* add prototype hooks

* add hooks

* modify numbers to enum

* implement withdraw by activity

* add spec for hooks, user actions, withdrawn hooks

* add comment about user withdrawables

* more description

* add queries for activity based withdraw

* add cli test for new query cmds

* compile errors fix for tests

* fix claim tests

* withdraw inside hook

* remove withdrawn actions flag and msgs

* remove lockup hook, add test TestDelegationAutoWithdrawAndDelegateMore

* Update cmd/osmosisd/cmd/genesis.go

Co-authored-by: Dev Ojha <[email protected]>

* Update x/claim/spec/README.md

Co-authored-by: Dev Ojha <[email protected]>

* fix comments

* in progress

* fix naming of file

* works

* export module account balance

* Update x/gamm/keeper/multihop_test.go

* address comments

* create EndAirdrop function

* fixed file name

Co-authored-by: Dev Ojha <[email protected]>
Co-authored-by: Sunny Aggarwal <[email protected]>
Co-authored-by: Sunny Aggarwal <[email protected]>
  • Loading branch information
4 people authored May 3, 2021
1 parent 4b03170 commit 9e4f397
Show file tree
Hide file tree
Showing 44 changed files with 4,797 additions and 37 deletions.
41 changes: 29 additions & 12 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import (

appparams "github.com/c-osmosis/osmosis/app/params"
_ "github.com/c-osmosis/osmosis/client/docs/statik"
"github.com/c-osmosis/osmosis/x/claim"
claimkeeper "github.com/c-osmosis/osmosis/x/claim/keeper"
claimtypes "github.com/c-osmosis/osmosis/x/claim/types"
"github.com/c-osmosis/osmosis/x/gamm"
gammkeeper "github.com/c-osmosis/osmosis/x/gamm/keeper"
gammtypes "github.com/c-osmosis/osmosis/x/gamm/types"
Expand Down Expand Up @@ -126,7 +129,7 @@ var (
gamm.AppModuleBasic{},
incentives.AppModuleBasic{},
lockup.AppModuleBasic{},
vesting.AppModuleBasic{},
claim.AppModuleBasic{},
)

// module account permissions
Expand All @@ -138,6 +141,7 @@ var (
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
govtypes.ModuleName: {authtypes.Burner},
ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner},
claimtypes.ModuleName: {authtypes.Minter, authtypes.Burner},
gammtypes.ModuleName: {authtypes.Minter, authtypes.Burner},
incentivestypes.ModuleName: {authtypes.Minter, authtypes.Burner},
lockuptypes.ModuleName: {authtypes.Minter, authtypes.Burner},
Expand Down Expand Up @@ -182,6 +186,7 @@ type OsmosisApp struct {
IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly
EvidenceKeeper evidencekeeper.Keeper
TransferKeeper ibctransferkeeper.Keeper
ClaimKeeper *claimkeeper.Keeper
GAMMKeeper gammkeeper.Keeper
IncentivesKeeper incentiveskeeper.Keeper
LockupKeeper lockupkeeper.Keeper
Expand Down Expand Up @@ -223,7 +228,7 @@ func NewOsmosisApp(
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey,
evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey,
gammtypes.StoreKey, incentivestypes.StoreKey, lockuptypes.StoreKey,
gammtypes.StoreKey, lockuptypes.StoreKey, claimtypes.StoreKey, incentivestypes.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
Expand Down Expand Up @@ -275,15 +280,9 @@ func NewOsmosisApp(
)
app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath)

// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
app.StakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()),
)

// Create IBC Keeper
app.IBCKeeper = ibckeeper.NewKeeper(
appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, scopedIBCKeeper,
appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), &stakingKeeper, scopedIBCKeeper,
)

// register the proposal types
Expand All @@ -293,7 +292,8 @@ func NewOsmosisApp(
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)).
AddRoute(ibchost.RouterKey, ibcclient.NewClientUpdateProposalHandler(app.IBCKeeper.ClientKeeper))
app.GovKeeper = govkeeper.NewKeeper(

govKeeper := govkeeper.NewKeeper(
appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, govRouter,
)
Expand All @@ -313,18 +313,26 @@ func NewOsmosisApp(

// create evidence keeper with router
evidenceKeeper := evidencekeeper.NewKeeper(
appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, app.SlashingKeeper,
appCodec, keys[evidencetypes.StoreKey], &stakingKeeper, app.SlashingKeeper,
)
// If evidence needs to be handled for the app, set routes in router here and seal
app.EvidenceKeeper = *evidenceKeeper

app.ClaimKeeper = claimkeeper.NewKeeper(appCodec, keys[claimtypes.StoreKey], app.AccountKeeper, app.BankKeeper, stakingKeeper, app.DistrKeeper)

// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
app.StakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks(), app.ClaimKeeper.Hooks()),
)
gammKeeper := gammkeeper.NewKeeper(appCodec, keys[gammtypes.StoreKey], app.AccountKeeper, app.BankKeeper)
lockupKeeper := lockupkeeper.NewKeeper(appCodec, keys[lockuptypes.StoreKey], app.AccountKeeper, app.BankKeeper)
incentivesKeeper := incentiveskeeper.NewKeeper(appCodec, keys[incentivestypes.StoreKey], app.GetSubspace(incentivestypes.ModuleName), app.AccountKeeper, app.BankKeeper, *lockupKeeper)

app.GAMMKeeper = *gammKeeper.SetHooks(
gammtypes.NewMultiGammHooks(
// insert gamm hooks receivers here
// insert gamm hooks receivers here
app.ClaimKeeper.Hooks(),
),
)

Expand All @@ -340,6 +348,13 @@ func NewOsmosisApp(
),
)

app.GovKeeper = *govKeeper.SetHooks(
govtypes.NewMultiGovHooks(
// insert governance hooks receivers here
app.ClaimKeeper.Hooks(),
),
)

/**** Module Options ****/

// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
Expand Down Expand Up @@ -368,6 +383,7 @@ func NewOsmosisApp(
ibc.NewAppModule(app.IBCKeeper),
params.NewAppModule(app.ParamsKeeper),
transferModule,
claim.NewAppModule(appCodec, *app.ClaimKeeper),
gamm.NewAppModule(appCodec, app.GAMMKeeper),
incentives.NewAppModule(appCodec, app.IncentivesKeeper),
lockup.NewAppModule(appCodec, app.LockupKeeper),
Expand All @@ -392,6 +408,7 @@ func NewOsmosisApp(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName,
slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName,
claimtypes.ModuleName,
incentivestypes.ModuleName,
)

Expand Down
25 changes: 25 additions & 0 deletions app/params/prefix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package params

import (
sdk "github.com/cosmos/cosmos-sdk/types"
)

// configurations
var (
AccountAddressPrefix = "osm1"
AccountPubKeyPrefix = "osm1pub"

ValidatorAddressPrefix = "osm1valoper"
ValidatorPubKeyPrefix = "osm1valoperpub"

ConsNodeAddressPrefix = "osm1valcons"
ConsNodePubKeyPrefix = "osm1valconspub"
)

// SetBech32Prefixes set bech32 prefixes
func SetBech32Prefixes() {
config := sdk.GetConfig()
config.SetBech32PrefixForAccount(AccountAddressPrefix, AccountPubKeyPrefix)
config.SetBech32PrefixForValidator(ValidatorAddressPrefix, ValidatorPubKeyPrefix)
config.SetBech32PrefixForConsensusNode(ConsNodeAddressPrefix, ConsNodePubKeyPrefix)
}
30 changes: 11 additions & 19 deletions cmd/osmosisd/cmd/airdrop.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import (
"io/ioutil"
"os"

"github.com/spf13/cobra"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
v036genaccounts "github.com/cosmos/cosmos-sdk/x/genaccounts/legacy/v036"
v036staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v036"
"github.com/spf13/cobra"
)

const (
Expand All @@ -32,22 +31,16 @@ type AppStateV036 struct {

// SnapshotFields provide fields of snapshot per account
type SnapshotFields struct {
AtomAddress string `json:"atom_address"`
// Atom Balance = AtomStakedBalance + AtomUnstakedBalance
AtomAddress string `json:"atom_address"` // Atom Balance = AtomStakedBalance + AtomUnstakedBalance
AtomBalance sdk.Int `json:"atom_balance"`
AtomStakedBalance sdk.Int `json:"atom_staked_balance"`
AtomUnstakedBalance sdk.Int `json:"atom_unstaked_balance"`
// AtomStakedPercent = AtomStakedBalance / AtomBalance
AtomUnstakedBalance sdk.Int `json:"atom_unstaked_balance"` // AtomStakedPercent = AtomStakedBalance / AtomBalance
AtomStakedPercent sdk.Dec `json:"atom_staked_percent"`
AtomOwnershipPercent sdk.Dec `json:"atom_ownership_percent"`
OsmoNormalizedBalance sdk.Int `json:"osmo_balance_normalized"`
// OsmoBalance = sqrt( AtomBalance ) * (1 + 1.5 * atom staked percent)
OsmoBalance sdk.Int `json:"osmo_balance"`
// OsmoBalanceBonus = OsmoBalanceBase * (1.5 * atom staked percent)
OsmoBalanceBonus sdk.Int `json:"osmo_balance_bonus"`
// OsmoBalanceBase = sqrt(atom balance)
OsmoBalanceBase sdk.Int `json:"osmo_balance_base"`
// OsmoPercent = OsmoNormalizedBalance / TotalOsmoSupply
OsmoNormalizedBalance sdk.Int `json:"osmo_balance_normalized"` // OsmoBalance = sqrt( AtomBalance ) * (1 + 1.5 * atom staked percent)
OsmoBalance sdk.Int `json:"osmo_balance"` // OsmoBalanceBonus = OsmoBalanceBase * (1.5 * atom staked percent)
OsmoBalanceBonus sdk.Int `json:"osmo_balance_bonus"` // OsmoBalanceBase = sqrt(atom balance)
OsmoBalanceBase sdk.Int `json:"osmo_balance_base"` // OsmoPercent = OsmoNormalizedBalance / TotalOsmoSupply
OsmoPercent sdk.Dec `json:"osmo_ownership_percent"`
}

Expand Down Expand Up @@ -99,7 +92,7 @@ Example:
return fmt.Errorf("failed to parse osmo supply: %s", osmoSupplyStr)
}

// Read genesis file
// Read genesis file
genesisJson, err := os.Open(genesisFile)
if err != nil {
return err
Expand Down Expand Up @@ -179,7 +172,6 @@ Example:
}

totalOsmoBalance := sdk.NewInt(0)

onePointFive := sdk.MustNewDecFromStr("1.5")

for address, acc := range snapshot {
Expand Down Expand Up @@ -210,7 +202,7 @@ Example:
acc.OsmoBalanceBonus = bonusOsmo.RoundInt()

allOsmo := baseOsmo.Add(bonusOsmo)
// OsmoBalance = sqrt( all atoms) * (1 + 1.5) * (staked atom percent) =
// OsmoBalance = sqrt( all atoms) * (1 + 1.5) * (staked atom percent) =
acc.OsmoBalance = allOsmo.RoundInt()

totalOsmoBalance = totalOsmoBalance.Add(allOsmo.RoundInt())
Expand All @@ -225,12 +217,12 @@ Example:
}

// normalize to desired genesis osmo supply
noarmalizationFactor := osmoSupply.ToDec().Quo(totalOsmoBalance.ToDec())
normalizationFactor := osmoSupply.ToDec().Quo(totalOsmoBalance.ToDec())

for address, acc := range snapshot {
acc.OsmoPercent = acc.OsmoBalance.ToDec().Quo(totalOsmoBalance.ToDec())

acc.OsmoNormalizedBalance = acc.OsmoBalance.ToDec().Mul(noarmalizationFactor).RoundInt()
acc.OsmoNormalizedBalance = acc.OsmoBalance.ToDec().Mul(normalizationFactor).RoundInt()

snapshot[address] = acc
}
Expand Down
151 changes: 151 additions & 0 deletions cmd/osmosisd/cmd/genesis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package cmd

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"

appparams "github.com/c-osmosis/osmosis/app/params"
claimtypes "github.com/c-osmosis/osmosis/x/claim/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra"
)

func GenerateGenesisCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "export-genesis [input-snapshot-file]",
Short: "Export a genesis from fairdrop snapshot",
Long: `Export a genesis from fairdrop snapshot
Example:
osmosisd export-genesis ../snapshot.json
- Check input genesis:
file is at ~/.gaiad/config/genesis.json
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
depCdc := clientCtx.JSONMarshaler
cdc := depCdc.(codec.Marshaler)
aminoCodec := clientCtx.LegacyAmino.Amino

serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config

config.SetRoot(clientCtx.HomeDir)

snapshotInput := args[0]

genFile := config.GenesisFile()
appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile)
if err != nil {
return fmt.Errorf("failed to unmarshal genesis state: %w", err)
}

authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState)

accs, err := authtypes.UnpackAccounts(authGenState.Accounts)
if err != nil {
return fmt.Errorf("failed to get accounts from any: %w", err)
}

// Read snapshot file
snapshotJson, err := os.Open(snapshotInput)
if err != nil {
return err
}
defer snapshotJson.Close()

byteValue, _ := ioutil.ReadAll(snapshotJson)

// Produce the map of address to total atom balance, both staked and unstaked
snapshot := make(map[string]SnapshotFields)
err = aminoCodec.UnmarshalJSON(byteValue, &snapshot)
if err != nil {
return err
}

balances := []banktypes.Balance{}
feeBalances := []banktypes.Balance{}

totalNormalizedOsmoBalance := sdk.NewInt(0)
for _, acc := range snapshot {
// calculate total osmo balance
totalNormalizedOsmoBalance = totalNormalizedOsmoBalance.Add(acc.OsmoNormalizedBalance)

// set atom bech32 prefixes
setCosmosBech32Prefixes()

// read address from snapshot
address, err := sdk.AccAddressFromBech32(acc.AtomAddress)
if err != nil {
return err
}

// set osmo bech32 prefixes
appparams.SetBech32Prefixes()

// airdrop balances
coins := sdk.NewCoins(sdk.NewCoin(claimtypes.OsmoBondDenom, acc.OsmoNormalizedBalance))
balances = append(balances, banktypes.Balance{Address: address.String(), Coins: coins})

// transaction fee balances
feeCoins := claimtypes.DefaultClaimModuleAcctBalance
feeBalances = append(feeBalances, banktypes.Balance{Address: address.String(), Coins: feeCoins})
}

// auth module genesis
genAccs, err := authtypes.PackAccounts(accs)
if err != nil {
return fmt.Errorf("failed to convert accounts into any's: %w", err)
}
authGenState.Accounts = genAccs
authGenStateBz, err := cdc.MarshalJSON(&authGenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}
appState[authtypes.ModuleName] = authGenStateBz

// bank module genesis
bankGenState := banktypes.GetGenesisStateFromAppState(depCdc, appState)
bankGenState.Balances = banktypes.SanitizeGenesisBalances(feeBalances)
bankGenStateBz, err := cdc.MarshalJSON(bankGenState)
if err != nil {
return fmt.Errorf("failed to marshal bank genesis state: %w", err)
}
appState[banktypes.ModuleName] = bankGenStateBz

// claim module genesis
claimGenState := claimtypes.DefaultGenesis()
claimGenState.ModuleAccountBalance = sdk.NewCoin(sdk.DefaultBondDenom, totalNormalizedOsmoBalance)
claimGenState.InitialClaimables = balances
claimGenStateBz, err := cdc.MarshalJSON(claimGenState)
if err != nil {
return fmt.Errorf("failed to marshal claim genesis state: %w", err)
}
appState[claimtypes.ModuleName] = claimGenStateBz

appStateJSON, err := json.Marshal(appState)
if err != nil {
return fmt.Errorf("failed to marshal application genesis state: %w", err)
}
genDoc.AppState = appStateJSON

err = genutil.ExportGenesisFile(genDoc, genFile)
return err
},
}

cmd.Flags().String(flagOsmoSupply, "", "OSMO total genesis supply")
flags.AddQueryFlagsToCmd(cmd)

return cmd
}
Loading

0 comments on commit 9e4f397

Please sign in to comment.