Repository: osmosis-labs/osmosis
Pull request #362 (2021-06-30 15:05:22)

Move math function to separate directory

codecov-commenter: # [Codecov](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs) Report
> Merging [#362](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs) (3045df4) into [main](https://codecov.io/gh/osmosis-labs/osmosis/commit/cfcaab50781762cd363f30ea82eb8f565c99905d?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs) (cfcaab5) will **decrease** coverage by `0.03%`.
> The diff coverage is `67.30%`.

[![Impacted file tree graph](https://codecov.io/gh/osmosis-labs/osmosis/pull/362/graphs/tree.svg?width=650&height=150&src=pr&token=ajbfjA38Z2&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs)](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs)

```diff
@@            Coverage Diff             @@
##             main     #362      +/-   ##
==========================================
- Coverage   18.59%   18.55%   -0.04%     
==========================================
  Files         134      135       +1     
  Lines       21533    21533              
==========================================
- Hits         4003     3996       -7     
- Misses      16865    16870       +5     
- Partials      665      667       +2     
```


| [Impacted Files](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs) | Coverage Δ | |
|---|---|---|
| [x/gamm/keeper/invariants.go](https://codecov.io/gh/osmosis-labs/osmosis/pull/362/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs#diff-eC9nYW1tL2tlZXBlci9pbnZhcmlhbnRzLmdv) | `14.92% <0.00%> (ø)` | |
| [osmomath/math.go](https://codecov.io/gh/osmosis-labs/osmosis/pull/362/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs#diff-b3Ntb21hdGgvbWF0aC5nbw==) | `65.90% <65.90%> (ø)` | |
| [x/gamm/keeper/math.go](https://codecov.io/gh/osmosis-labs/osmosis/pull/362/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs#diff-eC9nYW1tL2tlZXBlci9tYXRoLmdv) | `100.00% <100.00%> (+7.27%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs). Last update [cfcaab5...3045df4](https://codecov.io/gh/osmosis-labs/osmosis/pull/362?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=osmosis-labs).


Patch:
diff --git a/.build.sh b/.build.sh
new file mode 100755
index 000000000..ebe23da62
--- /dev/null
+++ b/.build.sh
@@ -0,0 +1,45 @@
+
+#!/bin/bash
+
+set -ue
+
+# Expect the following envvars to be set:
+# - APP
+# - VERSION
+# - COMMIT
+# - TARGET_OS
+# - LEDGER_ENABLED
+# - DEBUG
+
+# Source builder's functions library
+. /usr/local/share/tendermint/buildlib.sh
+
+# These variables are now available
+# - BASEDIR
+# - OUTDIR
+
+# Build for each os-architecture pair
+for platform in ${TARGET_PLATFORMS} ; do
+    # This function sets GOOS, GOARCH, and OS_FILE_EXT environment variables
+    # according to the build target platform. OS_FILE_EXT is empty in all
+    # cases except when the target platform is 'windows'.
+    setup_build_env_for_platform "${platform}"
+
+    make clean
+    echo Building for $(go env GOOS)/$(go env GOARCH) >&2
+    GOROOT_FINAL="$(go env GOROOT)" \
+    make build \
+        LDFLAGS=-buildid=${VERSION} \
+        VERSION=${VERSION} \
+        COMMIT=${COMMIT} \
+        LEDGER_ENABLED=${LEDGER_ENABLED}
+    mv ./build/${APP}${OS_FILE_EXT} ${OUTDIR}/${APP}-${VERSION}-$(go env GOOS)-$(go env GOARCH)${OS_FILE_EXT}
+
+    # This function restore the build environment variables to their
+    # original state.
+    restore_build_env
+done
+
+# Generate and display build report.
+generate_build_report
+cat ${OUTDIR}/build_report
diff --git a/.gitignore b/.gitignore
index b4cf21814..13ba81316 100644
--- a/.gitignore
+++ b/.gitignore
@@ -192,5 +192,7 @@ $RECYCLE.BIN/
 *.lnk
 
 # End of https://www.toptal.com/developers/gitignore/api/intellij,vscode,macos,windows
+
 /osmosisd
 /.idea/
+/artifacts/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c16b275d..7d1f26571 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,14 +34,15 @@ Ref: https://keepachangelog.com/en/1.0.0/
 
 # Changelog
 
-## Pending
+## [v2.0.0](https://github.com/osmosis/osmosis-labs/releases/tag/v2.0.0) - 2021-06-28
 
 * Update the cosmos-sdk version we modify to v0.42.6
 * Fix a bug in the min commission rate code that allows validators to be created with commission rates less than the minimum.
 * Automatically upgrade any validator with less than the minimum comission rate to the minimum at upgrade time.
 * Fix bug in the lockup module code that caused it to take a linear amount of gas.
 * Make unbonding tokens from the lockup module get automatically claimed when unbonding is done.
-* Add events for all tx types in the gamm module
+* Add events for all tx types in the gamm module.
+* Make queries to bank total chain balance account for developer vesting correctly.
 
 ## [v1.0.2](https://github.com/osmosis/osmosis-labs/releases/tag/v1.0.2) - 2021-06-18
 
diff --git a/RELEASE.md b/RELEASE.md
new file mode 100644
index 000000000..d54e121fc
--- /dev/null
+++ b/RELEASE.md
@@ -0,0 +1,10 @@
+# Making releases
+
+run
+
+```sh
+make distclean build-reproducible
+```
+
+and then upload the binaries from the artifacts folder.
+
diff --git a/app/app.go b/app/app.go
index ba79882e8..a9f2fdcdb 100644
--- a/app/app.go
+++ b/app/app.go
@@ -319,7 +319,7 @@ func NewOsmosisApp(
 			minCommissionRate := app.StakingKeeper.GetParams(ctx).MinCommissionRate
 			for _, v := range validators {
 				if v.Commission.Rate.LT(minCommissionRate) {
-					comm, err := app.StakingKeeper.UpdateValidatorCommission(
+					comm, err := app.StakingKeeper.MustUpdateValidatorCommission(
 						ctx, v, minCommissionRate)
 					if err != nil {
 						panic(err)
@@ -332,6 +332,13 @@ func NewOsmosisApp(
 					app.StakingKeeper.SetValidator(ctx, v)
 				}
 			}
+
+			// Update distribution keeper parameters to remove proposer bonus
+			// as it doesn't make sense in the epoch'd staking setting
+			distrParams := app.DistrKeeper.GetParams(ctx)
+			distrParams.BaseProposerReward = sdk.ZeroDec()
+			distrParams.BonusProposerReward = sdk.ZeroDec()
+			app.DistrKeeper.SetParams(ctx, distrParams)
 		})
 
 	// Create IBC Keeper
diff --git a/go.mod b/go.mod
index 40efac6ec..abcc76636 100644
--- a/go.mod
+++ b/go.mod
@@ -29,4 +29,4 @@ replace google.golang.org/grpc => google.golang.org/grpc v1.33.2
 
 replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.2-alpha.regen.4
 
-replace github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210622202917-f4f6a08ac64b
+replace github.com/cosmos/cosmos-sdk => github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210630232304-f792e47135c3
diff --git a/go.sum b/go.sum
index 9ad9f5ecb..03dcce48b 100644
--- a/go.sum
+++ b/go.sum
@@ -408,8 +408,10 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
 github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
 github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
 github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
-github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210622202917-f4f6a08ac64b h1:dWlPU8X890OVLKSqfmEanCrJ7NYUSpoEVXaRVqLwpuo=
-github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210622202917-f4f6a08ac64b/go.mod h1:kh37gwYQoWdgR7N/9zeqW2rJ7cnP2W4A7nqIaf6m3zg=
+github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210628180307-261fe6ac5d31 h1:XlYFFBRX9vNdMQb+MCzBvlICoYR3c6ddAWTyrtgx1r8=
+github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210628180307-261fe6ac5d31/go.mod h1:kh37gwYQoWdgR7N/9zeqW2rJ7cnP2W4A7nqIaf6m3zg=
+github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210630232304-f792e47135c3 h1:RSmqvmlkqHf4AXwNDoRmerAVUFgjTkkujJiZVTtqNSA=
+github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210630232304-f792e47135c3/go.mod h1:kh37gwYQoWdgR7N/9zeqW2rJ7cnP2W4A7nqIaf6m3zg=
 github.com/otiai10/copy v1.6.0 h1:IinKAryFFuPONZ7cm6T6E2QX/vcJwSnlaA5lfoaXIiQ=
 github.com/otiai10/copy v1.6.0/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E=
 github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
diff --git a/osmomath/math.go b/osmomath/math.go
new file mode 100644
index 000000000..1889531af
--- /dev/null
+++ b/osmomath/math.go
@@ -0,0 +1,156 @@
+package osmomath
+
+import (
+	"fmt"
+
+	sdk "github.com/cosmos/cosmos-sdk/types"
+)
+
+// Don't EVER change after initializing
+// TODO: Analyze choice here
+var powPrecision, _ = sdk.NewDecFromStr("0.00000001")
+
+// Singletons
+var zero sdk.Dec = sdk.ZeroDec()
+var one_half sdk.Dec = sdk.MustNewDecFromStr("0.5")
+var one sdk.Dec = sdk.OneDec()
+var two sdk.Dec = sdk.MustNewDecFromStr("2")
+
+
+/*********************************************************/
+
+// AbsDifferenceWithSign returns | a - b |, (a - b).sign()
+// a is mutated and returned
+func AbsDifferenceWithSign(a, b sdk.Dec) (sdk.Dec, bool) {
+	if a.GTE(b) {
+		return a.SubMut(b), false
+	} else {
+		return a.NegMut().AddMut(b), true
+	}
+}
+
+// func largeBasePow(base sdk.Dec, exp sdk.Dec) sdk.Dec {
+// 	// pow requires the base to be <= 2
+// }
+
+// Pow computes base^(exp)
+// However since the exponent is not an integer, we must do an approximation algorithm.
+// TODO: In the future, lets add some optimized routines for common exponents, e.g. for common wIn / wOut ratios
+// Many simple exponents like 2:1 pools
+func Pow(base sdk.Dec, exp sdk.Dec) sdk.Dec {
+	// Exponentiation of a negative base with an arbitrary real exponent is not closed within the reals.
+	// You can see this by recalling that `i = (-1)^(.5)`. We have to go to complex numbers to define this.
+	// (And would have to implement complex logarithms)
+	// We don't have a need for negative bases, so we don't include any such logic.
+	if !base.IsPositive() {
+		panic(fmt.Errorf("base must be greater than 0"))
+	}
+	// TODO: Remove this if we want to generalize the function,
+	// we can adjust the algorithm in this setting.
+	if base.GTE(two) {
+		panic(fmt.Errorf("base must be lesser than two"))
+	}
+
+	// We will use an approximation algorithm to compute the power.
+	// Since computing an integer power is easy, we split up the exponent into
+	// an integer component and a fractional component.
+	integer := exp.TruncateDec()
+	fractional := exp.Sub(integer)
+
+	integerPow := base.Power(uint64(integer.TruncateInt64()))
+
+	if fractional.IsZero() {
+		return integerPow
+	}
+
+	fractionalPow := PowApprox(base, fractional, powPrecision)
+
+	return integerPow.Mul(fractionalPow)
+}
+
+// Contract: 0 < base <= 2
+// 0 < exp < 1
+func PowApprox(base sdk.Dec, exp sdk.Dec, precision sdk.Dec) sdk.Dec {
+	if exp.IsZero() {
+		return sdk.ZeroDec()
+	}
+
+	// Common case optimization
+	// Optimize for it being equal to one-half
+	if exp.Equal(one_half) {
+		output, err := base.ApproxSqrt()
+		if err != nil {
+			panic(err)
+		}
+		return output
+	}
+	// TODO: Make an approx-equal function, and then check if exp * 3 = 1, and do a check accordingly
+
+	// We compute this via taking the maclaurin series of (1 + x)^a
+	// where x = base - 1.
+	// The maclaurin series of (1 + x)^a = sum_{k=0}^{infty} binom(a, k) x^k
+	// Binom(a, k) takes the natural continuation on the first parameter, namely that
+	// Binom(a, k) = N/D, where D = k!, and N = a(a-1)(a-2)...(a-k+1)
+	// Next we show that the absolute value of each term is less than the last term.
+	// Note that the change in term n's value vs term n + 1 is a multiplicative factor of
+	// v_n = x(a - n) / (n+1)
+	// So if |v_n| < 1, we know that each term has a lesser impact on the result than the last.
+	// For our bounds on |x| < 1, |a| < 1,
+	// it suffices to see for what n is |v_n| < 1,
+	// in the worst parameterization of x = 1, a = -1.
+	// v_n = |(-1 + epsilon - n) / (n+1)|
+	// So |v_n| is always less than 1, as n ranges over the integers.
+	//
+	// Note that term_n of the expansion is 1 * prod_{i=0}^{n-1} v_i
+	// The error if we stop the expansion at term_n is:
+	// error_n = sum_{k=n+1}^{infty} term_k
+	// At this point we further restrict a >= 0, so 0 <= a < 1.
+	// Now we take the _INCORRECT_ assumption that if term_n < p, then
+	// error_n < p.
+	// This assumption is obviously wrong.
+	// However our usages of this function don't use the full domain.
+	// With a > 0, |x| << 1, and p sufficiently low, perhaps this actually is true.
+
+	// TODO: Check with our parameterization
+	// TODO: If theres a bug, balancer is also wrong here :thonk:
+
+	base = base.Clone()
+	x, xneg := AbsDifferenceWithSign(base, one)
+	term := sdk.OneDec()
+	sum := sdk.OneDec()
+	negative := false
+
+	a := exp.Clone()
+	bigK := sdk.NewDec(0)
+	// TODO: Document this computation via taylor expansion
+	for i := int64(1); term.GTE(precision); i++ {
+		// At each iteration, we need two values, i and i-1.
+		// To avoid expensive big.Int allocation, we reuse bigK variable.
+		// On this line, bigK == i-1.
+		c, cneg := AbsDifferenceWithSign(a, bigK)
+		// On this line, bigK == i.
+		bigK.Set(sdk.NewDec(i)) // TODO: O(n) bigint allocation happens
+		term.MulMut(c).MulMut(x).QuoMut(bigK)
+
+		// a is mutated on absDifferenceWithSign, reset
+		a.Set(exp)
+
+		if term.IsZero() {
+			break
+		}
+		if xneg {
+			negative = !negative
+		}
+
+		if cneg {
+			negative = !negative
+		}
+
+		if negative {
+			sum.SubMut(term)
+		} else {
+			sum.AddMut(term)
+		}
+	}
+	return sum
+}
diff --git a/proto/osmosis/gamm/v1beta1/genesis.proto b/proto/osmosis/gamm/v1beta1/genesis.proto
new file mode 100644
index 000000000..8f682fa18
--- /dev/null
+++ b/proto/osmosis/gamm/v1beta1/genesis.proto
@@ -0,0 +1,15 @@
+syntax = "proto3";
+package osmosis.gamm;
+
+import "gogoproto/gogo.proto";
+import "google/protobuf/any.proto";
+import "cosmos_proto/cosmos.proto";
+
+option go_package = "github.com/osmosis-labs/osmosis/x/gamm/types";
+
+// GenesisState defines the gamm module's genesis state.
+message GenesisState {
+    repeated google.protobuf.Any pools = 1
+        [ (cosmos_proto.accepts_interface) = "PoolI" ];
+    uint64 next_pool_number = 2;
+}
diff --git a/scripts/upgrade/upgrade_lockup.sh b/scripts/upgrade/upgrade_lockup.sh
index 3b01ef61e..f5fe14ab6 100644
--- a/scripts/upgrade/upgrade_lockup.sh
+++ b/scripts/upgrade/upgrade_lockup.sh
@@ -1,37 +1,96 @@
 # run old binary on terminal1
-git checkout 6574912d71c41d591859239964162a2d3ee3a57e
+go clean --modcache
+git stash
+git checkout v1.0.1
 go install ./cmd/osmosisd/
-Modify startnode.sh script to below`
+Run the below commands
+```
     #!/bin/bash
-
     rm -rf $HOME/.osmosisd/
-
     cd $HOME
-
     osmosisd init --chain-id=testing testing --home=$HOME/.osmosisd
     osmosisd keys add validator --keyring-backend=test --home=$HOME/.osmosisd
     osmosisd add-genesis-account $(osmosisd keys show validator -a --keyring-backend=test --home=$HOME/.osmosisd) 1000000000stake,1000000000valtoken --home=$HOME/.osmosisd
     osmosisd gentx validator 500000000stake --keyring-backend=test --home=$HOME/.osmosisd --chain-id=testing
+    osmosisd gentx validator 500000000stake --commission-rate="0.0" --keyring-backend=test --home=$HOME/.osmosisd --chain-id=testing
     osmosisd collect-gentxs --home=$HOME/.osmosisd
+    
+    cat $HOME/.osmosisd/config/genesis.json | jq '.app_state["gov"]["voting_params"]["voting_period"]="120s"' > $HOME/.osmosisd/config/tmp_genesis.json && mv $HOME/.osmosisd/config/tmp_genesis.json $HOME/.osmosisd/config/genesis.json
+    cat $HOME/.osmosisd/config/genesis.json | jq '.app_state["staking"]["params"]["min_commission_rate"]="0.050000000000000000"' > $HOME/.osmosisd/config/tmp_genesis.json && mv $HOME/.osmosisd/config/tmp_genesis.json $HOME/.osmosisd/config/genesis.json
 
-    cat $HOME/.osmosisd/config/genesis.json | jq '.app_state["gov"]["voting_params"]["voting_period"]="10s"' > $HOME/.osmosisd/config/tmp_genesis.json && mv $HOME/.osmosisd/config/tmp_genesis.json $HOME/.osmosisd/config/genesis.json
+```
 
-    osmosisd start --home=$HOME/.osmosisd
-`
-sh startnode.sh
+Create pool.json 
+```
+{
+  "weights": "1stake,1valtoken",
+  "initial-deposit": "100stake,20valtoken",
+  "swap-fee": "0.01",
+  "exit-fee": "0.01",
+  "future-governor": "168h"
+}
+```
+
+rm $HOME/.osmosisd/cosmovisor/current -rf
+cosmovisor start
 
 # operations on terminal2
 osmosisd tx lockup lock-tokens 100stake --duration="5s" --from=validator --chain-id=testing --keyring-backend=test --yes
+sleep 7
 osmosisd tx gov submit-proposal software-upgrade upgrade-lockup-module-store-management --title="lockup module upgrade" --description="lockup module upgrade for gas efficiency"  --from=validator --upgrade-height=10 --deposit=10000000stake --chain-id=testing --keyring-backend=test -y
+sleep 7
 osmosisd tx gov vote 1 yes --from=validator --keyring-backend=test --chain-id=testing --yes
+sleep 7
+osmosisd tx gamm create-pool --pool-file="./pool.json"  --gas=3000000 --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx lockup lock-tokens 1000stake --duration="100s" --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx lockup lock-tokens 2000stake --duration="200s" --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx lockup lock-tokens 3000stake --duration="1s" --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx lockup begin-unlock-by-id 1 --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx lockup begin-unlock-by-id 3 --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+sleep 7
+osmosisd tx gov submit-proposal software-upgrade "v2" --title="lockup module upgrade" --description="lockup module upgrade for gas efficiency"  --from=validator --upgrade-height=20 --deposit=10000000stake --chain-id=testing --keyring-backend=test --yes  --broadcast-mode=block
+sleep 7
+osmosisd tx gov vote 1 yes --from=validator --keyring-backend=test --chain-id=testing --yes --broadcast-mode=block
 osmosisd query gov proposal 1
 osmosisd query upgrade plan
+osmosisd query lockup account-locked-longer-duration $(osmosisd keys show -a --keyring-backend=test validator) 1s
+osmosisd query gamm pools
+osmosisd query staking validators
+osmosisd query staking params
 
 # on terminal1
 Wait until consensus failure happen and stop binary using Ctrl + C
 git checkout lockup_module_genesis_export
+git checkout main
+
+Update go mod file to use latest SDK changes: /Users/admin/go/pkg/mod/github.com/osmosis-labs/cosmos-sdk@v0.42.5-0.20210622202917-f4f6a08ac64b
+go get github.com/osmosis-labs/cosmos-sdk@ea1ec79c739ba39639b9a24f824127ecc6650887
+go: downloading github.com/osmosis-labs/cosmos-sdk v0.42.5-0.20210630100106-ea1ec79c739b
+Upgrade Osmosis Cosmos SDK version to `v0.42.5-0.20210630100106-ea1ec79c739b`
+go mod download github.com/cosmos/cosmos-sdk
+git stash
+git checkout min_commission_change_validation_change_ignore
 go install ./cmd/osmosisd/
 osmosisd start --home=$HOME/.osmosisd
 
 # check on terminal2
-osmosisd query lockup account-locked-longer-duration $(osmosisd keys show -a --keyring-backend=test validator) 1s
\ No newline at end of file
+osmosisd query lockup account-locked-longer-duration $(osmosisd keys show -a --keyring-backend=test validator) 1s
+osmosisd query lockup account-locked-longer-duration $(osmosisd keys show -a --keyring-backend=test validator) 1s
+osmosisd query lockup module-locked-amount
+osmosisd query gamm pools
+osmosisd query staking validators
+osmosisd query staking params
+osmosisd query bank balances $(osmosisd keys show -a --keyring-backend=test validator)
+osmosisd tx staking edit-validator --commission-rate="0.1"  --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+osmosisd tx staking edit-validator --commission-rate="0.08"  --from=validator --chain-id=testing --keyring-backend=test --yes --broadcast-mode=block
+
+Result:
+- pool exists
+- lockup processed all correctly
+- validator commission rate worked
+- chain did not panic 
\ No newline at end of file
diff --git a/x/epochs/types/genesis.go b/x/epochs/types/genesis.go
index f0a9bfdbb..3387ecac3 100644
--- a/x/epochs/types/genesis.go
+++ b/x/epochs/types/genesis.go
@@ -41,13 +41,18 @@ func DefaultGenesis() *GenesisState {
 // failure.
 func (gs GenesisState) Validate() error {
 	// TODO: Epochs identifiers should be unique
+	epochIdentifiers := map[string]bool{}
 	for _, epoch := range gs.Epochs {
 		if epoch.Identifier == "" {
 			return errors.New("epoch identifier should NOT be empty")
 		}
+		if epochIdentifiers[epoch.Identifier] {
+			return errors.New("epoch identifier should be unique")
+		}
 		if epoch.Duration == 0 {
 			return errors.New("epoch duration should NOT be 0")
 		}
+		epochIdentifiers[epoch.Identifier] = true
 	}
 	return nil
 }
diff --git a/x/gamm/README.md b/x/gamm/README.md
index 2d4ea9815..0ce77880d 100644
--- a/x/gamm/README.md
+++ b/x/gamm/README.md
@@ -1,5 +1,280 @@
-# GAMM module
+# GAMM Module
+This document introduces the [Queries](#queries) and [Transactions](#transactions) of the **G**eneralized **A**utomated **M**arket **M**aker (GAMM) module. The GAMM module provides the logic to create and interact with liquidity pools on the Osmosis DEX.
 
-The gamm module defines logic for defining weighted balancer pool.
 
-TODO (fill out rest of README)
\ No newline at end of file
+
+# Queries
+The **Query** submodule of the GAMM module provides the logic to request information from the liquidity pools. It contains the following functions:
+- [Estimate Swap Exact Amount In](#estimate-swap-exact-amount-in)
+- [Estimate Swap Exact Amount Out](#estimate-swap-exact-amount-out)
+- [Num Pools](#num-pools)
+- [Pool](#pool)
+- [Pool Assets](#pool-assets)
+- [Pool Params](#pool-params)
+- [Pools](#pools)
+- [Spot Price](#spot-price)
+- [Total Liquidity](#total-liquidity)
+- [Total Share](#total-share)
+
+## Estimate Swap Exact Amount In
+Query the estimated result of the [Swap Exact Amount In](#swap-exact-amount-in) transaction. Note that the flags *swap-route-pool* and *swap-route-denoms* are required.
+### Usage
+```sh
+osmosisd query gamm estimate-swap-exact-amount-in <poolID> <sender> <tokenIn> [flags]
+```
+### Example
+Query the amount of ATOM the sender would receive for swapping 1 OSMO in pool 1.
+```sh
+osmosisd query gamm estimate-swap-exact-amount-in 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000uosmo --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 
+```
+
+
+## Estimate Swap Exact Amount Out
+Query the estimated result of the [Swap Exact Amount Out](#swap-exact-amount-out) transaction. Note that the flags *swap-route-pool* and *swap-route-denoms* are required.
+### Usage
+```sh
+osmosisd query gamm estimate-swap-exact-amount-out <poolID> <sender> <tokenOut> [flags]
+```
+### Example
+Query the amount of OSMO the sender would require to swap 1 ATOM out of pool 1.
+```sh
+osmosisd query gamm estimate-swap-exact-amount-out 1 osmo123nfq6m8f88m4g3sky570unsnk4zng4uqv7cm8 1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --swap-route-pool-ids 1 --swap-route-denoms uosmo
+```
+
+
+## Num Pools
+Query the number of active pools.
+### Usage
+```sh
+osmosisd query gamm num-pools
+```
+
+
+## Pool
+Query the parameter and assets of a specific pool. 
+### Usage
+```sh
+osmosisd query gamm pool <poolID> [flags]
+```
+### Example
+Query parameters and assets from pool 1.
+```sh
+osmosisd query gamm pool 1
+```
+
+
+## Pool Assets
+Query the assets of a specific pool. This query is a reduced form of the [Pool](#pool) query.
+### Usage
+```sh
+osmosisd query gamm pool-assets <poolID> [flags]
+```
+Query the assets from pool 1.
+### Example
+```sh
+osmosisd query gamm pool-assets 1
+```
+
+
+## Pool Params
+Query the parameters of a specific pool. This query is a reduced form of the [Pool](#pool) query.
+### Usage
+```sh
+osmosisd query gamm pool-params <poolID> [flags]
+```
+Query the parameters from pool 1.
+### Example
+```sh
+osmosisd query gamm pool-params 1
+```
+
+
+## Pools
+Query parameters and assets of all active pools.
+### Usage
+```sh
+osmosisd query gamm pools
+```
+
+
+## Spot Price
+Query the spot price of a pool asset based on a specific pool it is in.
+### Usage
+```sh
+osmosisd query gamm spot-price <poolID> <tokenInDenom> <tokenOutDenom> [flags]
+```
+### Example
+Query the price of OSMO based on the price of ATOM in pool 1.
+```sh
+osmosisd query gamm spot-price 1 uosmo ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2
+```
+
+
+## Total Liquidity
+Query the total liquidity of all active pools.
+### Usage
+```sh
+osmosisd query gamm total-liquidity
+```
+
+
+## Total Share
+Query the total amount of GAMM shares of a specific pool.
+### Usage
+```sh
+osmosisd query gamm total-share <poolID> [flags]
+```
+### Example
+Query the total amount of GAMM shares of pool 1.
+```sh
+osmosisd query gamm total-share 1
+```
+
+
+
+
+# Transactions
+The **Transaction** submodule of the GAMM module provides the logic to create and interact with the liquidity pools. It contains the following functions:
+- [Create Pool](#create-pool)
+- [Join Pool](#join-pool)
+- [Exit Pool](#exit-pool)
+- [Join Swap Extern Amount In](#join-swap-extern-amount-in)
+- [Exit Swap Extern Amount Out](#exit-swap-extern-amount-out)
+- [Join Swap Share Amount Out](#join-swap-share-amount-out)
+- [Exit Swap Share Amount In](#exit-swap-share-amount-in)
+- [Swap Exact Amount In](#swap-exact-amount-in)
+- [Swap Exact Amount Out](#swap-exact-amount-out)
+
+
+## Create Pool
+Create a new liquidity pool and provide the initial liquidity to it. Pool initialization parameters must be provided through a JSON file using the flag *pool-file*.
+#### Usage
+```sh
+osmosisd tx gamm create-pool [flags]
+```
+The configuration file *config.json* must specify the following parameters.
+```sh
+{
+	"weights": [list weighted denoms],
+	"initial-deposit": [list of denoms with initial deposit amount],
+	"swap-fee": [swap fee in percentage],
+	"exit-fee": [exit fee in percentage],
+	"future-governor": [number of hours]
+}
+```
+### Example
+Create a new ATOM-OSMO liquidity pool with a swap and exit fee of 1%.
+```sh
+tx gamm create-pool --pool-file ../public/config.json --from myKeyringWallet
+```
+The configuration file contains the following parameters.
+```sh
+{
+	"weights": "5uatom,5uosmo",
+	"initial-deposit": "100uatom,100uosmo",
+	"swap-fee": "0.01",
+	"exit-fee": "0.01",
+	"future-governor": "168h"
+}
+```
+
+
+
+## Join Pool
+Join a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *max-amounts-in* and *share-amount-out* are required.
+#### Usage
+```sh
+osmosisd tx gamm join-pool [flags]
+```
+#### Example
+Join pool 1 with 1 OSMO and the respective amount of ATOM, using myKeyringWallet.
+```sh
+osmosisd tx gamm join-pool --pool-id 1 --max-amounts-in 1000000uosmo --share-amount-out 1000000 --from myKeyringWallet
+```
+
+
+## Exit Pool
+Exit a specific pool with a custom amount of tokens. Note that the flags *pool-id*, *min-amounts-out* and *share-amount-in* are required.
+#### Usage
+```sh
+osmosisd tx gamm exit-pool [flags]
+```
+#### Example
+Exit pool one with 1 OSMO and the respective amount of ATOM using myKeyringWallet.
+```sh
+osmosisd tx gamm exit-pool --pool-id 1 --min-amounts-out 1000000uosmo --share-amount-in 1000000 --from myKeyringWallet
+```
+
+
+## Join Swap Extern Amount In
+Note that the flags *pool-id* is required.
+#### Usage
+```sh
+osmosisd tx gamm join-swap-extern-amount-in [token-in] [share-out-min-amount] [flags]
+```
+#### Example
+```sh
+osmosisd tx gamm join-swap-extern-amount-in 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet
+```
+
+
+## Exit Swap Extern Amount Out
+Note that the flag *pool-id* is required.
+#### Usage
+```sh
+osmosisd tx gamm exit-swap-extern-amount-out [token-out] [share-in-max-amount] [flags]
+```
+#### Example
+```sh
+osmosisd tx gamm exit-swap-extern-amount-out 1000000uosmo 1000000 --pool-id 1 --from myKeyringWallet
+
+```
+
+
+## Join Swap Share Amount Out
+Note that the flag *pool-id* is required.
+#### Usage
+```sh
+osmosisd tx gamm join-swap-share-amount-out [token-in-denom] [token-in-max-amount] [share-out-amount] [flags]
+```
+#### Example
+```sh
+osmosisd tx gamm join-swap-share-amount-out uosmo 1000000 1000000 --pool-id 1 --from myKeyringWallet
+```
+
+
+## Exit Swap Share Amount In
+Note that the flag *pool-id* is required.
+#### Usage
+```sh
+osmosisd tx gamm exit-swap-share-amount-in [token-out-denom] [share-in-amount] [token-out-min-amount] [flags]
+```
+#### Example
+```sh
+osmosisd tx gamm exit-swap-share-amount-in uosmo 1000000 1000000 --pool-id 1 --from myKeyringWallet
+```
+
+## Swap Exact Amount In
+Swap an exact amount of tokens into a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required.
+#### Usage
+```sh
+osmosisd tx gamm swap-exact-amount-in [token-in] [token-out-min-amount] [flags]
+```
+#### Example
+Swap 1 OSMO through pool 1 into at least 0.3 ATOM using MyKeyringWallet.
+```sh
+osmosisd tx gamm swap-exact-amount-in 1000000uosmo 300000 --swap-route-pool-ids 1 --swap-route-denoms ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 --from MyKeyringWallet
+```
+
+
+## Swap Exact Amount Out
+Swap an exact amount of tokens out of a specific pool. Note that the flags *swap-route-pool-ids* and *swap-route-denoms* are required.
+#### Usage
+```sh
+osmosisd tx gamm swap-exact-amount-out [token-out] [token-out-max-amount] [flags]
+```
+#### Example
+Swap 1 ATOM through pool 1 into at most 2.5 OSMO using MyKeyringWallet.
+```sh
+osmosisd tx gamm swap-exact-amount-out 1000000ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2 250000 --swap-route-pool-ids 1 --swap-route-denoms uosmo --from MyKeyringWallet
+```
diff --git a/x/gamm/genesis.go b/x/gamm/genesis.go
new file mode 100644
index 000000000..37dcea8d5
--- /dev/null
+++ b/x/gamm/genesis.go
@@ -0,0 +1,60 @@
+package gamm
+
+import (
+	"fmt"
+
+	codectypes "github.com/cosmos/cosmos-sdk/codec/types"
+	sdk "github.com/cosmos/cosmos-sdk/types"
+	"github.com/osmosis-labs/osmosis/x/gamm/keeper"
+	"github.com/osmosis-labs/osmosis/x/gamm/types"
+)
+
+// InitGenesis initializes the capability module's state from a provided genesis
+// state.
+func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState, unpacker codectypes.AnyUnpacker) {
+	k.SetNextPoolNumber(ctx, genState.NextPoolNumber)
+
+	liquidity := sdk.Coins{}
+	for _, any := range genState.Pools {
+		var pool types.PoolI
+		err := unpacker.UnpackAny(any, &pool)
+		if err != nil {
+			panic(err)
+		}
+		err = k.SetPool(ctx, pool)
+		if err != nil {
+			panic(err)
+		}
+
+		poolAssets := pool.GetAllPoolAssets()
+		for _, asset := range poolAssets {
+			liquidity = liquidity.Add(asset.Token)
+		}
+	}
+
+	k.SetTotalLiquidity(ctx, liquidity)
+}
+
+// ExportGenesis returns the capability module's exported genesis.
+func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
+	pools, err := k.GetPools(ctx)
+	if err != nil {
+		panic(err)
+	}
+	poolAnys := []*codectypes.Any{}
+	for _, poolI := range pools {
+		pool, ok := poolI.(*types.Pool)
+		if !ok {
+			panic(fmt.Errorf("pool (%d) is not basic pool", poolI.GetId()))
+		}
+		any, err := codectypes.NewAnyWithValue(pool)
+		if err != nil {
+			panic(err)
+		}
+		poolAnys = append(poolAnys, any)
+	}
+	return &types.GenesisState{
+		NextPoolNumber: k.GetNextPoolNumber(ctx),
+		Pools:          poolAnys,
+	}
+}
diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go
index db767cbee..dad9b14b8 100644
--- a/x/gamm/keeper/grpc_query.go
+++ b/x/gamm/keeper/grpc_query.go
@@ -119,7 +119,7 @@ func (k Keeper) NumPools(
 	sdkCtx := sdk.UnwrapSDKContext(ctx)
 
 	return &types.QueryNumPoolsResponse{
-		NumPools: k.getNextPoolNumber(sdkCtx) - 1,
+		NumPools: k.GetNextPoolNumber(sdkCtx) - 1,
 	}, nil
 }
 
diff --git a/x/gamm/keeper/invariants.go b/x/gamm/keeper/invariants.go
index 012d58b8c..e8168964d 100644
--- a/x/gamm/keeper/invariants.go
+++ b/x/gamm/keeper/invariants.go
@@ -6,6 +6,8 @@ import (
 	"fmt"
 
 	sdk "github.com/cosmos/cosmos-sdk/types"
+
+	"github.com/osmosis-labs/osmosis/osmomath"
 	"github.com/osmosis-labs/osmosis/x/gamm/types"
 )
 
@@ -88,9 +90,9 @@ func PoolTotalWeightInvariant(keeper Keeper, bk types.BankKeeper) sdk.Invariant
 
 func genericPow(base, exp sdk.Dec) sdk.Dec {
 	if !base.GTE(sdk.NewDec(2)) {
-		return pow(base, exp)
+		return osmomath.Pow(base, exp)
 	}
-	return powApprox(sdk.OneDec().Quo(base), exp.Neg(), powPrecision)
+	return osmomath.PowApprox(sdk.OneDec().Quo(base), exp.Neg(), powPrecision)
 }
 
 // constantChange returns the multiplicative factor difference in the pool constant, between two different pools.
diff --git a/x/gamm/keeper/math.go b/x/gamm/keeper/math.go
index 83e1afa74..2132eca29 100644
--- a/x/gamm/keeper/math.go
+++ b/x/gamm/keeper/math.go
@@ -1,7 +1,7 @@
 package keeper
 
 import (
-	"fmt"
+	"github.com/osmosis-labs/osmosis/osmomath"
 
 	sdk "github.com/cosmos/cosmos-sdk/types"
 )
@@ -67,7 +67,7 @@ func calcOutGivenIn(
 	adjustedIn := sdk.OneDec().Sub(swapFee)
 	adjustedIn = tokenAmountIn.Mul(adjustedIn)
 	y := tokenBalanceIn.Quo(tokenBalanceIn.Add(adjustedIn))
-	foo := pow(y, weightRatio)
+	foo := osmomath.Pow(y, weightRatio)
 	bar := sdk.OneDec().Sub(foo)
 	return tokenBalanceOut.Mul(bar)
 }
@@ -84,7 +84,7 @@ func calcInGivenOut(
 	weightRatio := tokenWeightOut.Quo(tokenWeightIn)
 	diff := tokenBalanceOut.Sub(tokenAmountOut)
 	y := tokenBalanceOut.Quo(diff)
-	foo := pow(y, weightRatio)
+	foo := osmomath.Pow(y, weightRatio)
 	foo = foo.Sub(one)
 	tokenAmountIn := sdk.OneDec().Sub(swapFee)
 	return (tokenBalanceIn.Mul(foo)).Quo(tokenAmountIn)
@@ -108,7 +108,7 @@ func calcPoolOutGivenSingleIn(
 	tokenInRatio := newTokenBalanceIn.Quo(tokenBalanceIn)
 
 	// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
-	poolRatio := pow(tokenInRatio, normalizedWeight)
+	poolRatio := osmomath.Pow(tokenInRatio, normalizedWeight)
 	newPoolSupply := poolRatio.Mul(poolSupply)
 	return newPoolSupply.Sub(poolSupply)
 }
@@ -128,7 +128,7 @@ func calcSingleInGivenPoolOut(
 
 	//uint newBalTi = poolRatio^(1/weightTi) * balTi;
 	boo := sdk.OneDec().Quo(normalizedWeight)
-	tokenInRatio := pow(poolRatio, boo)
+	tokenInRatio := osmomath.Pow(poolRatio, boo)
 	newTokenBalanceIn := tokenInRatio.Mul(tokenBalanceIn)
 	tokenAmountInAfterFee := newTokenBalanceIn.Sub(tokenBalanceIn)
 	// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
@@ -157,7 +157,7 @@ func calcSingleOutGivenPoolIn(
 
 	// newBalTo = poolRatio^(1/weightTo) * balTo;
 
-	tokenOutRatio := pow(poolRatio, sdk.OneDec().Quo(normalizedWeight))
+	tokenOutRatio := osmomath.Pow(poolRatio, sdk.OneDec().Quo(normalizedWeight))
 	newTokenBalanceOut := tokenOutRatio.Mul(tokenBalanceOut)
 
 	tokenAmountOutBeforeSwapFee := tokenBalanceOut.Sub(newTokenBalanceOut)
@@ -190,7 +190,7 @@ func calcPoolInGivenSingleOut(
 	tokenOutRatio := newTokenBalanceOut.Quo(tokenBalanceOut)
 
 	//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
-	poolRatio := pow(tokenOutRatio, normalizedWeight)
+	poolRatio := osmomath.Pow(tokenOutRatio, normalizedWeight)
 	newPoolSupply := poolRatio.Mul(poolSupply)
 	poolAmountInAfterExitFee := poolSupply.Sub(newPoolSupply)
 
@@ -198,141 +198,3 @@ func calcPoolInGivenSingleOut(
 	// pAi = pAiAfterExitFee/(1-exitFee)
 	return poolAmountInAfterExitFee.Quo(sdk.OneDec().Sub(exitFee))
 }
-
-/*********************************************************/
-
-// absDifferenceWithSign returns | a - b |, (a - b).sign()
-// a is mutated and returned
-func absDifferenceWithSign(a, b sdk.Dec) (sdk.Dec, bool) {
-	if a.GTE(b) {
-		return a.SubMut(b), false
-	} else {
-		return a.NegMut().AddMut(b), true
-	}
-}
-
-// func largeBasePow(base sdk.Dec, exp sdk.Dec) sdk.Dec {
-// 	// pow requires the base to be <= 2
-// }
-
-// pow computes base^(exp)
-// However since the exponent is not an integer, we must do an approximation algorithm.
-// TODO: In the future, lets add some optimized routines for common exponents, e.g. for common wIn / wOut ratios
-// Many simple exponents like 2:1 pools
-func pow(base sdk.Dec, exp sdk.Dec) sdk.Dec {
-	// Exponentiation of a negative base with an arbitrary real exponent is not closed within the reals.
-	// You can see this by recalling that `i = (-1)^(.5)`. We have to go to complex numbers to define this.
-	// (And would have to implement complex logarithms)
-	// We don't have a need for negative bases, so we don't include any such logic.
-	if !base.IsPositive() {
-		panic(fmt.Errorf("base must be greater than 0"))
-	}
-	// TODO: Remove this if we want to generalize the function,
-	// we can adjust the algorithm in this setting.
-	if base.GTE(two) {
-		panic(fmt.Errorf("base must be lesser than two"))
-	}
-
-	// We will use an approximation algorithm to compute the power.
-	// Since computing an integer power is easy, we split up the exponent into
-	// an integer component and a fractional component.
-	integer := exp.TruncateDec()
-	fractional := exp.Sub(integer)
-
-	integerPow := base.Power(uint64(integer.TruncateInt64()))
-
-	if fractional.IsZero() {
-		return integerPow
-	}
-
-	fractionalPow := powApprox(base, fractional, powPrecision)
-
-	return integerPow.Mul(fractionalPow)
-}
-
-// Contract: 0 < base <= 2
-// 0 < exp < 1
-func powApprox(base sdk.Dec, exp sdk.Dec, precision sdk.Dec) sdk.Dec {
-	if exp.IsZero() {
-		return sdk.ZeroDec()
-	}
-
-	// Common case optimization
-	// Optimize for it being equal to one-half
-	if exp.Equal(one_half) {
-		output, err := base.ApproxSqrt()
-		if err != nil {
-			panic(err)
-		}
-		return output
-	}
-	// TODO: Make an approx-equal function, and then check if exp * 3 = 1, and do a check accordingly
-
-	// We compute this via taking the maclaurin series of (1 + x)^a
-	// where x = base - 1.
-	// The maclaurin series of (1 + x)^a = sum_{k=0}^{infty} binom(a, k) x^k
-	// Binom(a, k) takes the natural continuation on the first parameter, namely that
-	// Binom(a, k) = N/D, where D = k!, and N = a(a-1)(a-2)...(a-k+1)
-	// Next we show that the absolute value of each term is less than the last term.
-	// Note that the change in term n's value vs term n + 1 is a multiplicative factor of
-	// v_n = x(a - n) / (n+1)
-	// So if |v_n| < 1, we know that each term has a lesser impact on the result than the last.
-	// For our bounds on |x| < 1, |a| < 1,
-	// it suffices to see for what n is |v_n| < 1,
-	// in the worst parameterization of x = 1, a = -1.
-	// v_n = |(-1 + epsilon - n) / (n+1)|
-	// So |v_n| is always less than 1, as n ranges over the integers.
-	//
-	// Note that term_n of the expansion is 1 * prod_{i=0}^{n-1} v_i
-	// The error if we stop the expansion at term_n is:
-	// error_n = sum_{k=n+1}^{infty} term_k
-	// At this point we further restrict a >= 0, so 0 <= a < 1.
-	// Now we take the _INCORRECT_ assumption that if term_n < p, then
-	// error_n < p.
-	// This assumption is obviously wrong.
-	// However our usages of this function don't use the full domain.
-	// With a > 0, |x| << 1, and p sufficiently low, perhaps this actually is true.
-
-	// TODO: Check with our parameterization
-	// TODO: If theres a bug, balancer is also wrong here :thonk:
-
-	base = base.Clone()
-	x, xneg := absDifferenceWithSign(base, one)
-	term := sdk.OneDec()
-	sum := sdk.OneDec()
-	negative := false
-
-	a := exp.Clone()
-	bigK := sdk.NewDec(0)
-	// TODO: Document this computation via taylor expansion
-	for i := int64(1); term.GTE(precision); i++ {
-		// At each iteration, we need two values, i and i-1.
-		// To avoid expensive big.Int allocation, we reuse bigK variable.
-		// On this line, bigK == i-1.
-		c, cneg := absDifferenceWithSign(a, bigK)
-		// On this line, bigK == i.
-		bigK.Set(sdk.NewDec(i)) // TODO: O(n) bigint allocation happens
-		term.MulMut(c).MulMut(x).QuoMut(bigK)
-
-		// a is mutated on absDifferenceWithSign, reset
-		a.Set(exp)
-
-		if term.IsZero() {
-			break
-		}
-		if xneg {
-			negative = !negative
-		}
-
-		if cneg {
-			negative = !negative
-		}
-
-		if negative {
-			sum.SubMut(term)
-		} else {
-			sum.AddMut(term)
-		}
-	}
-	return sum
-}
diff --git a/x/gamm/keeper/pool.go b/x/gamm/keeper/pool.go
index 1617bd100..532fa12a5 100644
--- a/x/gamm/keeper/pool.go
+++ b/x/gamm/keeper/pool.go
@@ -82,7 +82,7 @@ func (k Keeper) SetPool(ctx sdk.Context, pool types.PoolI) error {
 // newPool is an internal function that creates a new Pool object with the provided
 // parameters, initial assets, and future governor.
 func (k Keeper) newPool(ctx sdk.Context, poolParams types.PoolParams, assets []types.PoolAsset, futureGovernor string) (types.PoolI, error) {
-	poolId := k.getNextPoolNumber(ctx)
+	poolId := k.GetNextPoolNumber(ctx)
 
 	pool, err := types.NewPool(poolId, poolParams, assets, futureGovernor, ctx.BlockTime())
 	if err != nil {
@@ -111,8 +111,15 @@ func (k Keeper) newPool(ctx sdk.Context, poolParams types.PoolParams, assets []t
 	return pool, nil
 }
 
-// getNextPoolNumber returns the next pool number
-func (k Keeper) getNextPoolNumber(ctx sdk.Context) uint64 {
+// SetNextPoolNumber sets next pool number
+func (k Keeper) SetNextPoolNumber(ctx sdk.Context, poolNumber uint64) {
+	store := ctx.KVStore(k.storeKey)
+	bz := k.cdc.MustMarshalBinaryBare(&gogotypes.UInt64Value{Value: poolNumber})
+	store.Set(types.KeyNextGlobalPoolNumber, bz)
+}
+
+// GetNextPoolNumber returns the next pool number
+func (k Keeper) GetNextPoolNumber(ctx sdk.Context) uint64 {
 	var poolNumber uint64
 	store := ctx.KVStore(k.storeKey)
 
@@ -131,9 +138,7 @@ func (k Keeper) getNextPoolNumber(ctx sdk.Context) uint64 {
 		poolNumber = val.GetValue()
 	}
 
-	bz = k.cdc.MustMarshalBinaryBare(&gogotypes.UInt64Value{Value: poolNumber + 1})
-	store.Set(types.KeyNextGlobalPoolNumber, bz)
-
+	k.SetNextPoolNumber(ctx, poolNumber+1)
 	return poolNumber
 }
 
diff --git a/x/gamm/module.go b/x/gamm/module.go
index a48327380..f3cfb208d 100644
--- a/x/gamm/module.go
+++ b/x/gamm/module.go
@@ -34,21 +34,21 @@ type AppModuleBasic struct {
 	cdc codec.Marshaler
 }
 
-// Name returns the bank module's name.
+// Name returns the gamm module's name.
 func (AppModuleBasic) Name() string { return types.ModuleName }
 
-// RegisterLegacyAminoCodec registers the bank module's types on the LegacyAmino codec.
+// RegisterLegacyAminoCodec registers the gamm module's types on the LegacyAmino codec.
 func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
 	types.RegisterLegacyAminoCodec(cdc)
 }
 
-// DefaultGenesis returns default genesis state as raw bytes for the bank
+// DefaultGenesis returns default genesis state as raw bytes for the gamm
 // module.
 func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
 	return nil
 }
 
-// ValidateGenesis performs genesis state validation for the bank module.
+// ValidateGenesis performs genesis state validation for the gamm module.
 func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage) error {
 	return nil
 }
@@ -71,7 +71,7 @@ func (b AppModuleBasic) GetQueryCmd() *cobra.Command {
 	return cli.GetQueryCmd()
 }
 
-// RegisterInterfaces registers interfaces and implementations of the bank module.
+// RegisterInterfaces registers interfaces and implementations of the gamm module.
 func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
 	types.RegisterInterfaces(registry)
 }
@@ -102,40 +102,45 @@ func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper,
 	}
 }
 
-// RegisterInvariants registers the bank module invariants.
+// RegisterInvariants registers the gamm module invariants.
 func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {
 	keeper.RegisterInvariants(ir, am.keeper, am.bk)
 }
 
-// Route returns the message routing key for the bank module.
+// Route returns the message routing key for the gamm module.
 func (am AppModule) Route() sdk.Route {
 	return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper))
 }
 
-// QuerierRoute returns the bank module's querier route name.
+// QuerierRoute returns the gamm module's querier route name.
 func (AppModule) QuerierRoute() string { return types.RouterKey }
 
-// LegacyQuerierHandler returns the bank module sdk.Querier.
+// LegacyQuerierHandler returns the gamm module sdk.Querier.
 func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier {
 	return nil
 }
 
-// InitGenesis performs genesis initialization for the bank module. It returns
+// InitGenesis performs genesis initialization for the gamm module. It returns
 // no validator updates.
-func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
-	return nil
+func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, gs json.RawMessage) []abci.ValidatorUpdate {
+	var genState types.GenesisState
+	// Initialize global index to index in genesis state
+	cdc.MustUnmarshalJSON(gs, &genState)
+	InitGenesis(ctx, am.keeper, genState, am.cdc)
+	return []abci.ValidatorUpdate{}
 }
 
-// ExportGenesis returns the exported genesis state as raw bytes for the bank
+// ExportGenesis returns the exported genesis state as raw bytes for the gamm
 // module.
 func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
-	return nil
+	genState := ExportGenesis(ctx, am.keeper)
+	return cdc.MustMarshalJSON(genState)
 }
 
 // BeginBlock performs a no-op.
 func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {}
 
-// EndBlock returns the end blocker for the bank module. It returns no validator
+// EndBlock returns the end blocker for the gamm module. It returns no validator
 // updates.
 func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate {
 	return []abci.ValidatorUpdate{}
diff --git a/x/gamm/types/genesis.pb.go b/x/gamm/types/genesis.pb.go
new file mode 100644
index 000000000..4022360b6
--- /dev/null
+++ b/x/gamm/types/genesis.pb.go
@@ -0,0 +1,376 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: osmosis/gamm/v1beta1/genesis.proto
+
+package types
+
+import (
+	fmt "fmt"
+	types "github.com/cosmos/cosmos-sdk/codec/types"
+	_ "github.com/gogo/protobuf/gogoproto"
+	proto "github.com/gogo/protobuf/proto"
+	_ "github.com/regen-network/cosmos-proto"
+	io "io"
+	math "math"
+	math_bits "math/bits"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+// GenesisState defines the gamm module's genesis state.
+type GenesisState struct {
+	Pools          []*types.Any `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools,omitempty"`
+	NextPoolNumber uint64       `protobuf:"varint,2,opt,name=next_pool_number,json=nextPoolNumber,proto3" json:"next_pool_number,omitempty"`
+}
+
+func (m *GenesisState) Reset()         { *m = GenesisState{} }
+func (m *GenesisState) String() string { return proto.CompactTextString(m) }
+func (*GenesisState) ProtoMessage()    {}
+func (*GenesisState) Descriptor() ([]byte, []int) {
+	return fileDescriptor_5a324eb7f1dd793e, []int{0}
+}
+func (m *GenesisState) XXX_Unmarshal(b []byte) error {
+	return m.Unmarshal(b)
+}
+func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+	if deterministic {
+		return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic)
+	} else {
+		b = b[:cap(b)]
+		n, err := m.MarshalToSizedBuffer(b)
+		if err != nil {
+			return nil, err
+		}
+		return b[:n], nil
+	}
+}
+func (m *GenesisState) XXX_Merge(src proto.Message) {
+	xxx_messageInfo_GenesisState.Merge(m, src)
+}
+func (m *GenesisState) XXX_Size() int {
+	return m.Size()
+}
+func (m *GenesisState) XXX_DiscardUnknown() {
+	xxx_messageInfo_GenesisState.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_GenesisState proto.InternalMessageInfo
+
+func (m *GenesisState) GetPools() []*types.Any {
+	if m != nil {
+		return m.Pools
+	}
+	return nil
+}
+
+func (m *GenesisState) GetNextPoolNumber() uint64 {
+	if m != nil {
+		return m.NextPoolNumber
+	}
+	return 0
+}
+
+func init() {
+	proto.RegisterType((*GenesisState)(nil), "osmosis.gamm.GenesisState")
+}
+
+func init() {
+	proto.RegisterFile("osmosis/gamm/v1beta1/genesis.proto", fileDescriptor_5a324eb7f1dd793e)
+}
+
+var fileDescriptor_5a324eb7f1dd793e = []byte{
+	// 259 bytes of a gzipped FileDescriptorProto
+	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x2f, 0xce, 0xcd,
+	0x2f, 0xce, 0x2c, 0xd6, 0x4f, 0x4f, 0xcc, 0xcd, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34,
+	0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2,
+	0x81, 0xaa, 0xd1, 0x03, 0xa9, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x4b, 0xe8, 0x83, 0x58,
+	0x10, 0x35, 0x52, 0x92, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, 0x60, 0x5e, 0x52, 0x69, 0x9a,
+	0x7e, 0x62, 0x5e, 0x25, 0x4c, 0x2a, 0x19, 0xac, 0x3f, 0x1e, 0xa2, 0x07, 0xc2, 0x81, 0x48, 0x29,
+	0xe5, 0x73, 0xf1, 0xb8, 0x43, 0xac, 0x0a, 0x2e, 0x49, 0x2c, 0x49, 0x15, 0x32, 0xe5, 0x62, 0x2d,
+	0xc8, 0xcf, 0xcf, 0x29, 0x96, 0x60, 0x54, 0x60, 0xd6, 0xe0, 0x36, 0x12, 0xd1, 0x83, 0x98, 0xaa,
+	0x07, 0x33, 0x55, 0xcf, 0x31, 0xaf, 0xd2, 0x89, 0xf3, 0xd4, 0x16, 0x5d, 0xd6, 0x80, 0xfc, 0xfc,
+	0x1c, 0xcf, 0x20, 0x88, 0x6a, 0x21, 0x0d, 0x2e, 0x81, 0xbc, 0xd4, 0x8a, 0x92, 0x78, 0x10, 0x2f,
+	0x3e, 0xaf, 0x34, 0x37, 0x29, 0xb5, 0x48, 0x82, 0x49, 0x81, 0x51, 0x83, 0x25, 0x88, 0x0f, 0x24,
+	0x0e, 0x52, 0xeb, 0x07, 0x16, 0x75, 0x72, 0x3b, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6,
+	0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39,
+	0x86, 0x28, 0x9d, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, 0x7f,
+	0x75, 0x73, 0x12, 0x93, 0x8a, 0x61, 0x1c, 0xfd, 0x0a, 0x48, 0x10, 0x95, 0x54, 0x16, 0xa4, 0x16,
+	0x27, 0xb1, 0x81, 0x5d, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x16, 0xaa, 0x73, 0x98, 0x3f,
+	0x01, 0x00, 0x00,
+}
+
+func (m *GenesisState) Marshal() (dAtA []byte, err error) {
+	size := m.Size()
+	dAtA = make([]byte, size)
+	n, err := m.MarshalToSizedBuffer(dAtA[:size])
+	if err != nil {
+		return nil, err
+	}
+	return dAtA[:n], nil
+}
+
+func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) {
+	size := m.Size()
+	return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+	i := len(dAtA)
+	_ = i
+	var l int
+	_ = l
+	if m.NextPoolNumber != 0 {
+		i = encodeVarintGenesis(dAtA, i, uint64(m.NextPoolNumber))
+		i--
+		dAtA[i] = 0x10
+	}
+	if len(m.Pools) > 0 {
+		for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- {
+			{
+				size, err := m.Pools[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+				if err != nil {
+					return 0, err
+				}
+				i -= size
+				i = encodeVarintGenesis(dAtA, i, uint64(size))
+			}
+			i--
+			dAtA[i] = 0xa
+		}
+	}
+	return len(dAtA) - i, nil
+}
+
+func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int {
+	offset -= sovGenesis(v)
+	base := offset
+	for v >= 1<<7 {
+		dAtA[offset] = uint8(v&0x7f | 0x80)
+		v >>= 7
+		offset++
+	}
+	dAtA[offset] = uint8(v)
+	return base
+}
+func (m *GenesisState) Size() (n int) {
+	if m == nil {
+		return 0
+	}
+	var l int
+	_ = l
+	if len(m.Pools) > 0 {
+		for _, e := range m.Pools {
+			l = e.Size()
+			n += 1 + l + sovGenesis(uint64(l))
+		}
+	}
+	if m.NextPoolNumber != 0 {
+		n += 1 + sovGenesis(uint64(m.NextPoolNumber))
+	}
+	return n
+}
+
+func sovGenesis(x uint64) (n int) {
+	return (math_bits.Len64(x|1) + 6) / 7
+}
+func sozGenesis(x uint64) (n int) {
+	return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *GenesisState) Unmarshal(dAtA []byte) error {
+	l := len(dAtA)
+	iNdEx := 0
+	for iNdEx < l {
+		preIndex := iNdEx
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return ErrIntOverflowGenesis
+			}
+			if iNdEx >= l {
+				return io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= uint64(b&0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		fieldNum := int32(wire >> 3)
+		wireType := int(wire & 0x7)
+		if wireType == 4 {
+			return fmt.Errorf("proto: GenesisState: wiretype end group for non-group")
+		}
+		if fieldNum <= 0 {
+			return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire)
+		}
+		switch fieldNum {
+		case 1:
+			if wireType != 2 {
+				return fmt.Errorf("proto: wrong wireType = %d for field Pools", wireType)
+			}
+			var msglen int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenesis
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				msglen |= int(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if msglen < 0 {
+				return ErrInvalidLengthGenesis
+			}
+			postIndex := iNdEx + msglen
+			if postIndex < 0 {
+				return ErrInvalidLengthGenesis
+			}
+			if postIndex > l {
+				return io.ErrUnexpectedEOF
+			}
+			m.Pools = append(m.Pools, &types.Any{})
+			if err := m.Pools[len(m.Pools)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+				return err
+			}
+			iNdEx = postIndex
+		case 2:
+			if wireType != 0 {
+				return fmt.Errorf("proto: wrong wireType = %d for field NextPoolNumber", wireType)
+			}
+			m.NextPoolNumber = 0
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return ErrIntOverflowGenesis
+				}
+				if iNdEx >= l {
+					return io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				m.NextPoolNumber |= uint64(b&0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+		default:
+			iNdEx = preIndex
+			skippy, err := skipGenesis(dAtA[iNdEx:])
+			if err != nil {
+				return err
+			}
+			if skippy < 0 {
+				return ErrInvalidLengthGenesis
+			}
+			if (iNdEx + skippy) < 0 {
+				return ErrInvalidLengthGenesis
+			}
+			if (iNdEx + skippy) > l {
+				return io.ErrUnexpectedEOF
+			}
+			iNdEx += skippy
+		}
+	}
+
+	if iNdEx > l {
+		return io.ErrUnexpectedEOF
+	}
+	return nil
+}
+func skipGenesis(dAtA []byte) (n int, err error) {
+	l := len(dAtA)
+	iNdEx := 0
+	depth := 0
+	for iNdEx < l {
+		var wire uint64
+		for shift := uint(0); ; shift += 7 {
+			if shift >= 64 {
+				return 0, ErrIntOverflowGenesis
+			}
+			if iNdEx >= l {
+				return 0, io.ErrUnexpectedEOF
+			}
+			b := dAtA[iNdEx]
+			iNdEx++
+			wire |= (uint64(b) & 0x7F) << shift
+			if b < 0x80 {
+				break
+			}
+		}
+		wireType := int(wire & 0x7)
+		switch wireType {
+		case 0:
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowGenesis
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				iNdEx++
+				if dAtA[iNdEx-1] < 0x80 {
+					break
+				}
+			}
+		case 1:
+			iNdEx += 8
+		case 2:
+			var length int
+			for shift := uint(0); ; shift += 7 {
+				if shift >= 64 {
+					return 0, ErrIntOverflowGenesis
+				}
+				if iNdEx >= l {
+					return 0, io.ErrUnexpectedEOF
+				}
+				b := dAtA[iNdEx]
+				iNdEx++
+				length |= (int(b) & 0x7F) << shift
+				if b < 0x80 {
+					break
+				}
+			}
+			if length < 0 {
+				return 0, ErrInvalidLengthGenesis
+			}
+			iNdEx += length
+		case 3:
+			depth++
+		case 4:
+			if depth == 0 {
+				return 0, ErrUnexpectedEndOfGroupGenesis
+			}
+			depth--
+		case 5:
+			iNdEx += 4
+		default:
+			return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+		}
+		if iNdEx < 0 {
+			return 0, ErrInvalidLengthGenesis
+		}
+		if depth == 0 {
+			return iNdEx, nil
+		}
+	}
+	return 0, io.ErrUnexpectedEOF
+}
+
+var (
+	ErrInvalidLengthGenesis        = fmt.Errorf("proto: negative length found during unmarshaling")
+	ErrIntOverflowGenesis          = fmt.Errorf("proto: integer overflow")
+	ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group")
+)
diff --git a/x/gamm/types/pool.go b/x/gamm/types/pool.go
index 1889f2580..383f95a02 100644
--- a/x/gamm/types/pool.go
+++ b/x/gamm/types/pool.go
@@ -7,10 +7,9 @@ import (
 	"strings"
 	"time"
 
+	sdk "github.com/cosmos/cosmos-sdk/types"
 	proto "github.com/gogo/protobuf/proto"
 	"github.com/osmosis-labs/osmosis/v043_temp/address"
-
-	sdk "github.com/cosmos/cosmos-sdk/types"
 )
 
 // PoolI defines an interface for pools that hold tokens.
diff --git a/x/incentives/client/cli/tx.go b/x/incentives/client/cli/tx.go
index e11997f47..90ae8769f 100644
--- a/x/incentives/client/cli/tx.go
+++ b/x/incentives/client/cli/tx.go
@@ -59,7 +59,7 @@ func NewCreateGaugeCmd() *cobra.Command {
 				return err
 			}
 			if timeStr == "" { // empty start time
-				// do nothing
+				startTime = time.Unix(0, 0)
 			} else if timeUnix, err := strconv.ParseInt(timeStr, 10, 64); err == nil { // unix time
 				startTime = time.Unix(timeUnix, 0)
 			} else if timeRFC, err := time.Parse(time.RFC3339, timeStr); err == nil { // RFC time
@@ -126,7 +126,7 @@ func NewAddToGaugeCmd() *cobra.Command {
 
 			txf := tx.NewFactoryCLI(clientCtx, cmd.Flags()).WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever)
 
-			gaugeId, err := strconv.ParseUint(args[1], 10, 64)
+			gaugeId, err := strconv.ParseUint(args[0], 10, 64)
 			if err != nil {
 				return err
 			}
diff --git a/x/lockup/abci.go b/x/lockup/abci.go
index c12981eab..3a2ee0cc5 100644
--- a/x/lockup/abci.go
+++ b/x/lockup/abci.go
@@ -13,6 +13,11 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper)
 
 // Called every block to automatically unlock matured locks
 func EndBlocker(ctx sdk.Context, k keeper.Keeper) []abci.ValidatorUpdate {
+	// disable automatic withdraw before specific block height
+	// it is actually for testing with legacy
+	if ctx.BlockHeight() < 6 {
+		return []abci.ValidatorUpdate{}
+	}
 	k.WithdrawAllMaturedLocks(ctx)
 	return []abci.ValidatorUpdate{}
 }
diff --git a/x/lockup/keeper/lock.go b/x/lockup/keeper/lock.go
index 1776e04c8..bdfd99025 100644
--- a/x/lockup/keeper/lock.go
+++ b/x/lockup/keeper/lock.go
@@ -421,7 +421,10 @@ func (k Keeper) Unlock(ctx sdk.Context, lock types.PeriodLock) error {
 	store.Delete(lockStoreKey(lock.ID))
 
 	// delete lock refs from the unlocking queue
-	k.deleteLockRefs(ctx, types.KeyPrefixUnlocking, lock)
+	err = k.deleteLockRefs(ctx, types.KeyPrefixUnlocking, lock)
+	if err != nil {
+		return err
+	}
 
 	k.hooks.OnTokenUnlocked(ctx, owner, lock.ID, lock.Coins, lock.Duration, lock.EndTime)
 	return nil
diff --git a/x/pool-incentives/client/cli/query.go b/x/pool-incentives/client/cli/query.go
index d91d16d78..a0cb6c049 100644
--- a/x/pool-incentives/client/cli/query.go
+++ b/x/pool-incentives/client/cli/query.go
@@ -25,6 +25,10 @@ func GetQueryCmd(queryRoute string) *cobra.Command {
 
 	cmd.AddCommand(
 		GetCmdGaugeIds(),
+		GetCmdDistrInfo(),
+		GetCmdParams(),
+		GetCmdLockableDurations(),
+		GetCmdIncentivizedPools(),
 	)
 
 	return cmd
@@ -73,7 +77,7 @@ $ %s query pool-incentives gauge-ids 1
 	return cmd
 }
 
-// GetCmdDistrInfo takes the pool id and returns the matching gauge ids and durations
+// GetCmdDistrInfo takes the pool id and returns the matching gauge ids and weights
 func GetCmdDistrInfo() *cobra.Command {
 	cmd := &cobra.Command{
 		Use:   "distr-info",


Test patch:
diff --git a/osmomath/math_test.go b/osmomath/math_test.go
new file mode 100644
index 000000000..096a685a2
--- /dev/null
+++ b/osmomath/math_test.go
@@ -0,0 +1,59 @@
+package osmomath
+
+import (
+	"testing"
+
+	sdk "github.com/cosmos/cosmos-sdk/types"
+
+	"github.com/stretchr/testify/require"
+)
+
+func TestAbsDifferenceWithSign(t *testing.T) {
+	decA, err := sdk.NewDecFromStr("3.2")
+	require.NoError(t, err)
+	decB, err := sdk.NewDecFromStr("4.3432389")
+	require.NoError(t, err)
+
+	s, b := AbsDifferenceWithSign(decA, decB)
+	require.True(t, b)
+
+	expectedDec, err := sdk.NewDecFromStr("1.1432389")
+	require.NoError(t, err)
+	require.Equal(t, expectedDec, s)
+}
+
+func TestPowApprox(t *testing.T) {
+	base, err := sdk.NewDecFromStr("0.8")
+	require.NoError(t, err)
+	exp, err := sdk.NewDecFromStr("0.32")
+	require.NoError(t, err)
+
+	s := PowApprox(base, exp, powPrecision)
+	expectedDec, err := sdk.NewDecFromStr("0.93108385")
+	require.NoError(t, err)
+
+	require.True(
+		t,
+		expectedDec.Sub(s).Abs().LTE(powPrecision),
+		"expected value & actual value's difference should less than precision",
+	)
+}
+
+func TestPow(t *testing.T) {
+	base, err := sdk.NewDecFromStr("1.68")
+	require.NoError(t, err)
+	exp, err := sdk.NewDecFromStr("0.32")
+	require.NoError(t, err)
+
+	s := Pow(base, exp)
+	expectedDec, err := sdk.NewDecFromStr("1.18058965")
+	require.NoError(t, err)
+
+	require.True(
+		t,
+		expectedDec.Sub(s).Abs().LTE(powPrecision),
+		"expected value & actual value's difference should less than precision",
+	)
+}
+
+
diff --git a/x/gamm/keeper/pow_bench_test.go b/osmomath/pow_bench_test.go
similarity index 95%
rename from x/gamm/keeper/pow_bench_test.go
rename to osmomath/pow_bench_test.go
index 0af73bb36..51c4095cc 100644
--- a/x/gamm/keeper/pow_bench_test.go
+++ b/osmomath/pow_bench_test.go
@@ -1,4 +1,4 @@
-package keeper
+package osmomath
 
 import (
 	"testing"
@@ -56,7 +56,7 @@ func BenchmarkPow(b *testing.B) {
 
 	for i := 0; i < b.N; i++ {
 		for _, test := range tests {
-			pow(test.base, test.exp)
+			Pow(test.base, test.exp)
 		}
 	}
 }
@@ -80,7 +80,7 @@ func BenchmarkSqrtPow(b *testing.B) {
 
 	for i := 0; i < b.N; i++ {
 		for _, test := range tests {
-			pow(test.base, one_half)
+			Pow(test.base, one_half)
 		}
 	}
 }
diff --git a/x/epochs/genesis_test.go b/x/epochs/genesis_test.go
index 050b6ec21..60673004c 100644
--- a/x/epochs/genesis_test.go
+++ b/x/epochs/genesis_test.go
@@ -51,7 +51,8 @@ func TestEpochsInitGenesis(t *testing.T) {
 	ctx = ctx.WithBlockHeight(1)
 	ctx = ctx.WithBlockTime(now)
 
-	epochs.InitGenesis(ctx, app.EpochsKeeper, types.GenesisState{
+	//test genesisState validation
+	genesisState := types.GenesisState{
 		Epochs: []types.EpochInfo{
 			{
 				Identifier:            "monthly",
@@ -62,9 +63,34 @@ func TestEpochsInitGenesis(t *testing.T) {
 				EpochCountingStarted:  true,
 				CurrentEpochEnded:     true,
 			},
+			{
+				Identifier:            "monthly",
+				StartTime:             time.Time{},
+				Duration:              time.Hour * 24,
+				CurrentEpoch:          0,
+				CurrentEpochStartTime: time.Time{},
+				EpochCountingStarted:  true,
+				CurrentEpochEnded:     true,
+			},
 		},
-	})
+	}
+	require.EqualError(t, genesisState.Validate(), "epoch identifier should be unique")
+
+	genesisState = types.GenesisState{
+		Epochs: []types.EpochInfo{
+			{
+				Identifier:            "monthly",
+				StartTime:             time.Time{},
+				Duration:              time.Hour * 24,
+				CurrentEpoch:          0,
+				CurrentEpochStartTime: time.Time{},
+				EpochCountingStarted:  true,
+				CurrentEpochEnded:     true,
+			},
+		},
+	}
 
+	epochs.InitGenesis(ctx, app.EpochsKeeper, genesisState)
 	epochInfo := app.EpochsKeeper.GetEpochInfo(ctx, "monthly")
 	require.Equal(t, epochInfo.Identifier, "monthly")
 	require.Equal(t, epochInfo.StartTime.UTC().String(), now.UTC().String())
diff --git a/x/gamm/genesis_test.go b/x/gamm/genesis_test.go
new file mode 100644
index 000000000..eac860593
--- /dev/null
+++ b/x/gamm/genesis_test.go
@@ -0,0 +1,133 @@
+package gamm_test
+
+import (
+	"testing"
+
+	codectypes "github.com/cosmos/cosmos-sdk/codec/types"
+	sdk "github.com/cosmos/cosmos-sdk/types"
+	simapp "github.com/osmosis-labs/osmosis/app"
+	"github.com/osmosis-labs/osmosis/x/gamm"
+	"github.com/osmosis-labs/osmosis/x/gamm/types"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"github.com/tendermint/tendermint/crypto/ed25519"
+	tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
+)
+
+func TestGammInitGenesis(t *testing.T) {
+	app := simapp.Setup(false)
+	ctx := app.BaseApp.NewContext(false, tmproto.Header{})
+
+	poolI, err := types.NewPool(1, types.PoolParams{
+		SwapFee: sdk.NewDecWithPrec(1, 2),
+		ExitFee: sdk.NewDecWithPrec(1, 2),
+	}, []types.PoolAsset{
+		{
+			Weight: sdk.NewInt(1),
+			Token:  sdk.NewInt64Coin(sdk.DefaultBondDenom, 10),
+		},
+		{
+			Weight: sdk.NewInt(1),
+			Token:  sdk.NewInt64Coin("nodetoken", 10),
+		},
+	}, "", ctx.BlockTime())
+	require.NoError(t, err)
+
+	pool, ok := poolI.(*types.Pool)
+	require.True(t, ok)
+
+	any, err := codectypes.NewAnyWithValue(pool)
+	require.NoError(t, err)
+
+	gamm.InitGenesis(ctx, app.GAMMKeeper, types.GenesisState{
+		Pools:          []*codectypes.Any{any},
+		NextPoolNumber: 2,
+	}, app.AppCodec())
+
+	require.Equal(t, app.GAMMKeeper.GetNextPoolNumber(ctx), uint64(2))
+	poolStored, err := app.GAMMKeeper.GetPool(ctx, 1)
+	require.NoError(t, err)
+	require.Equal(t, pool.GetId(), poolStored.GetId())
+	require.Equal(t, pool.GetAddress(), poolStored.GetAddress())
+	require.Equal(t, pool.GetPoolParams(), poolStored.GetPoolParams())
+	require.Equal(t, pool.GetTotalWeight(), poolStored.GetTotalWeight())
+	require.Equal(t, pool.GetTotalShares(), poolStored.GetTotalShares())
+	require.Equal(t, pool.GetAllPoolAssets(), poolStored.GetAllPoolAssets())
+	require.Equal(t, pool.String(), poolStored.String())
+
+	_, err = app.GAMMKeeper.GetPool(ctx, 2)
+	require.Error(t, err)
+
+	liquidity := app.GAMMKeeper.GetTotalLiquidity(ctx)
+	require.Equal(t, liquidity, sdk.Coins{sdk.NewInt64Coin("nodetoken", 10), sdk.NewInt64Coin(sdk.DefaultBondDenom, 10)})
+}
+
+func TestGammExportGenesis(t *testing.T) {
+	app := simapp.Setup(false)
+	ctx := app.BaseApp.NewContext(false, tmproto.Header{})
+
+	acc1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes())
+	app.BankKeeper.SetBalances(ctx, acc1, sdk.Coins{
+		sdk.NewInt64Coin("foo", 100000),
+		sdk.NewInt64Coin("bar", 100000),
+	})
+
+	_, err := app.GAMMKeeper.CreatePool(ctx, acc1, types.PoolParams{
+		SwapFee: sdk.NewDecWithPrec(1, 2),
+		ExitFee: sdk.NewDecWithPrec(1, 2),
+	}, []types.PoolAsset{{
+		Weight: sdk.NewInt(100),
+		Token:  sdk.NewCoin("foo", sdk.NewInt(10000)),
+	}, {
+		Weight: sdk.NewInt(100),
+		Token:  sdk.NewCoin("bar", sdk.NewInt(10000)),
+	}}, "")
+	require.NoError(t, err)
+
+	_, err = app.GAMMKeeper.CreatePool(ctx, acc1, types.PoolParams{
+		SwapFee: sdk.NewDecWithPrec(1, 2),
+		ExitFee: sdk.NewDecWithPrec(1, 2),
+	}, []types.PoolAsset{{
+		Weight: sdk.NewInt(70),
+		Token:  sdk.NewCoin("foo", sdk.NewInt(10000)),
+	}, {
+		Weight: sdk.NewInt(100),
+		Token:  sdk.NewCoin("bar", sdk.NewInt(10000)),
+	}}, "")
+	require.NoError(t, err)
+
+	genesis := gamm.ExportGenesis(ctx, app.GAMMKeeper)
+	require.Equal(t, genesis.NextPoolNumber, uint64(3))
+	require.Len(t, genesis.Pools, 2)
+}
+
+func TestMarshalUnmarshalGenesis(t *testing.T) {
+	app := simapp.Setup(false)
+	ctx := app.BaseApp.NewContext(false, tmproto.Header{})
+
+	encodingConfig := simapp.MakeEncodingConfig()
+	appCodec := encodingConfig.Marshaler
+	am := gamm.NewAppModule(appCodec, app.GAMMKeeper, app.AccountKeeper, app.BankKeeper)
+	acc1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes())
+	app.BankKeeper.SetBalances(ctx, acc1, sdk.Coins{
+		sdk.NewInt64Coin("foo", 100000),
+		sdk.NewInt64Coin("bar", 100000),
+	})
+
+	_, err := app.GAMMKeeper.CreatePool(ctx, acc1, types.PoolParams{
+		SwapFee: sdk.NewDecWithPrec(1, 2),
+		ExitFee: sdk.NewDecWithPrec(1, 2),
+	}, []types.PoolAsset{{
+		Weight: sdk.NewInt(100),
+		Token:  sdk.NewCoin("foo", sdk.NewInt(10000)),
+	}, {
+		Weight: sdk.NewInt(100),
+		Token:  sdk.NewCoin("bar", sdk.NewInt(10000)),
+	}}, "")
+	require.NoError(t, err)
+
+	genesis := am.ExportGenesis(ctx, appCodec)
+	assert.NotPanics(t, func() {
+		am.InitGenesis(ctx, appCodec, genesis)
+	})
+}
diff --git a/x/gamm/keeper/math_test.go b/x/gamm/keeper/math_test.go
index 7660beb69..0c400c053 100644
--- a/x/gamm/keeper/math_test.go
+++ b/x/gamm/keeper/math_test.go
@@ -8,54 +8,6 @@ import (
 	"github.com/stretchr/testify/require"
 )
 
-func TestAbsDifferenceWithSign(t *testing.T) {
-	decA, err := sdk.NewDecFromStr("3.2")
-	require.NoError(t, err)
-	decB, err := sdk.NewDecFromStr("4.3432389")
-	require.NoError(t, err)
-
-	s, b := absDifferenceWithSign(decA, decB)
-	require.True(t, b)
-
-	expectedDec, err := sdk.NewDecFromStr("1.1432389")
-	require.NoError(t, err)
-	require.Equal(t, expectedDec, s)
-}
-
-func TestPowApprox(t *testing.T) {
-	base, err := sdk.NewDecFromStr("0.8")
-	require.NoError(t, err)
-	exp, err := sdk.NewDecFromStr("0.32")
-	require.NoError(t, err)
-
-	s := powApprox(base, exp, powPrecision)
-	expectedDec, err := sdk.NewDecFromStr("0.93108385")
-	require.NoError(t, err)
-
-	require.True(
-		t,
-		expectedDec.Sub(s).Abs().LTE(powPrecision),
-		"expected value & actual value's difference should less than precision",
-	)
-}
-
-func TestPow(t *testing.T) {
-	base, err := sdk.NewDecFromStr("1.68")
-	require.NoError(t, err)
-	exp, err := sdk.NewDecFromStr("0.32")
-	require.NoError(t, err)
-
-	s := pow(base, exp)
-	expectedDec, err := sdk.NewDecFromStr("1.18058965")
-	require.NoError(t, err)
-
-	require.True(
-		t,
-		expectedDec.Sub(s).Abs().LTE(powPrecision),
-		"expected value & actual value's difference should less than precision",
-	)
-}
-
 func TestCalcSpotPrice(t *testing.T) {
 	// TODO: Change test to be table driven
 	tokenBalanceIn, err := sdk.NewDecFromStr("100")
diff --git a/x/lockup/keeper/upgrade_test.go b/x/lockup/keeper/upgrade_test.go
index 1d4f533af..dce991a4b 100644
--- a/x/lockup/keeper/upgrade_test.go
+++ b/x/lockup/keeper/upgrade_test.go
@@ -7,6 +7,7 @@ import (
 	sdk "github.com/cosmos/cosmos-sdk/types"
 	upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
 	lockuptypes "github.com/osmosis-labs/osmosis/x/lockup/types"
+	"github.com/tendermint/tendermint/abci/types"
 )
 
 func (suite *KeeperTestSuite) LegacyLockTokens(addr sdk.AccAddress, coins sdk.Coins, duration time.Duration) {
@@ -16,10 +17,16 @@ func (suite *KeeperTestSuite) LegacyLockTokens(addr sdk.AccAddress, coins sdk.Co
 }
 
 func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
+	addr1 := sdk.AccAddress([]byte("addr1---------------"))
+	addr2 := sdk.AccAddress([]byte("addr2---------------"))
+	addr3 := sdk.AccAddress([]byte("addr3---------------"))
+
 	testCases := []struct {
-		msg      string
-		malleate func()
-		expPass  bool
+		msg         string
+		pre_update  func()
+		update      func()
+		post_update func()
+		expPass     bool
 	}{
 		{
 			"with current upgrade plan",
@@ -27,12 +34,9 @@ func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
 				coins := sdk.Coins{sdk.NewInt64Coin("stake", 10)}
 
 				// lock coins
-				addr1 := sdk.AccAddress([]byte("addr1---------------"))
-				suite.LegacyLockTokens(addr1, coins, time.Second)
-				addr2 := sdk.AccAddress([]byte("addr2---------------"))
-				suite.LegacyLockTokens(addr2, coins, time.Second)
-				addr3 := sdk.AccAddress([]byte("addr3---------------"))
-				suite.LegacyLockTokens(addr3, coins, time.Second)
+				suite.LegacyLockTokens(addr1, coins, 10*time.Second)
+				suite.LegacyLockTokens(addr2, coins, 200*time.Second)
+				suite.LegacyLockTokens(addr3, coins, 50*time.Second)
 
 				// check locks
 				locks, err := suite.app.LockupKeeper.GetLegacyPeriodLocks(suite.ctx)
@@ -43,6 +47,18 @@ func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
 				err = suite.app.LockupKeeper.LegacyBeginUnlock(suite.ctx, locks[0])
 				suite.Require().NoError(err)
 
+				err = suite.app.LockupKeeper.LegacyBeginUnlock(suite.ctx, locks[2])
+				suite.Require().NoError(err)
+			},
+			func() {
+				// run block 20 seconds into future
+				suite.app.BeginBlocker(suite.ctx, types.RequestBeginBlock{})
+				suite.app.EndBlocker(suite.ctx, types.RequestEndBlock{suite.ctx.BlockHeight()})
+				suite.ctx = suite.ctx.WithBlockTime(
+					suite.ctx.BlockTime().Add(20 * time.Second))
+				suite.app.BeginBlocker(suite.ctx, types.RequestBeginBlock{})
+				suite.app.EndBlocker(suite.ctx, types.RequestEndBlock{suite.ctx.BlockHeight()})
+
 				// run upgrades
 				plan := upgradetypes.Plan{Name: "v2", Height: 5}
 				suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan)
@@ -51,12 +67,24 @@ func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
 				suite.Assert().NotPanics(func() {
 					suite.app.UpgradeKeeper.ApplyUpgrade(suite.ctx.WithBlockHeight(5), plan)
 				})
+			},
+			func() {
+				// check all queries just after upgrade
+				locks, err := suite.app.LockupKeeper.GetPeriodLocks(suite.ctx)
+				suite.Require().NoError(err)
+				suite.Require().Len(locks, 3)
 
-				// check all queries
+				// run a next block
+				suite.ctx = suite.ctx.WithBlockHeight(6).WithBlockTime(suite.ctx.BlockTime().Add(5 * time.Second))
+				suite.app.BeginBlocker(suite.ctx, types.RequestBeginBlock{})
+				suite.app.EndBlocker(suite.ctx, types.RequestEndBlock{suite.ctx.BlockHeight()})
+
+				// check all remainings
 				locks, err = suite.app.LockupKeeper.GetPeriodLocks(suite.ctx)
 				suite.Require().NoError(err)
-				suite.Require().Len(locks, 3)
+				suite.Require().Len(locks, 2)
 
+				// TODO: Update the rest of these queries
 				locks = suite.app.LockupKeeper.GetAccountLockedPastTimeNotUnlockingOnly(suite.ctx, addr1, suite.ctx.BlockTime())
 				suite.Require().Len(locks, 0)
 
@@ -64,35 +92,38 @@ func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
 				suite.Require().Len(locks, 0)
 
 				locks = suite.app.LockupKeeper.GetAccountLockedPastTimeDenom(suite.ctx, addr1, "stake", suite.ctx.BlockTime())
-				suite.Require().Len(locks, 1)
+				suite.Require().Len(locks, 0)
 
-				locks = suite.app.LockupKeeper.GetAccountLockedLongerDuration(suite.ctx, addr1, time.Second)
+				locks = suite.app.LockupKeeper.GetAccountLockedLongerDuration(suite.ctx, addr2, time.Second)
 				suite.Require().Len(locks, 1)
 
 				locks = suite.app.LockupKeeper.GetAccountLockedLongerDurationNotUnlockingOnly(suite.ctx, addr1, time.Second)
 				suite.Require().Len(locks, 0)
 
-				locks = suite.app.LockupKeeper.GetAccountLockedLongerDurationDenom(suite.ctx, addr1, "stake", time.Second)
+				locks = suite.app.LockupKeeper.GetAccountLockedLongerDurationDenom(suite.ctx, addr2, "stake", time.Second)
 				suite.Require().Len(locks, 1)
 
 				locks = suite.app.LockupKeeper.GetLocksPastTimeDenom(suite.ctx, "stake", suite.ctx.BlockTime())
-				suite.Require().Len(locks, 3)
+				suite.Require().Len(locks, 2)
 
 				locks = suite.app.LockupKeeper.GetLocksLongerThanDurationDenom(suite.ctx, "stake", time.Second)
-				suite.Require().Len(locks, 3)
+				suite.Require().Len(locks, 2)
 
 				_, err = suite.app.LockupKeeper.GetLockByID(suite.ctx, 1)
+				suite.Require().Error(err)
+
+				_, err = suite.app.LockupKeeper.GetLockByID(suite.ctx, 2)
 				suite.Require().NoError(err)
 
 				locks = suite.app.LockupKeeper.GetAccountPeriodLocks(suite.ctx, addr1)
-				suite.Require().Len(locks, 1)
+				suite.Require().Len(locks, 0)
 
 				accum := suite.app.LockupKeeper.GetPeriodLocksAccumulation(suite.ctx, lockuptypes.QueryCondition{
 					LockQueryType: lockuptypes.ByDuration,
 					Denom:         "stake",
 					Duration:      time.Second,
 				})
-				suite.Require().Equal(accum.String(), "20")
+				suite.Require().Equal(accum.String(), "10")
 			},
 			true,
 		},
@@ -102,7 +133,9 @@ func (suite *KeeperTestSuite) TestUpgradeStoreManagement() {
 		suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
 			suite.SetupTest() // reset
 
-			tc.malleate()
+			tc.pre_update()
+			tc.update()
+			tc.post_update()
 
 		})
 	}