diff --git a/app/app.go b/app/app.go index d1b5ccd57..30c350fcb 100644 --- a/app/app.go +++ b/app/app.go @@ -59,10 +59,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" - distr "github.com/ODIN-PROTOCOL/odin-core/x/distribution" - distrclient "github.com/ODIN-PROTOCOL/odin-core/x/distribution/client" - distrkeeper "github.com/ODIN-PROTOCOL/odin-core/x/distribution/keeper" - distrtypes "github.com/ODIN-PROTOCOL/odin-core/x/distribution/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" diff --git a/app/genesis.go b/app/genesis.go index f26b8d8d5..347a794ec 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -15,7 +15,7 @@ import ( ibc "github.com/cosmos/ibc-go/v7/modules/core" ibchost "github.com/cosmos/ibc-go/v7/modules/core/24-host" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/go.mod b/go.mod index 50e1e0f83..0bc4448ef 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,6 @@ require ( github.com/CosmWasm/wasmd v0.44.0 github.com/Masterminds/squirrel v1.5.2 github.com/cometbft/cometbft v0.38.0 - - // github.com/tendermint/tendermint v0.34.27 github.com/cometbft/cometbft-db v0.8.0 github.com/confio/ics23/go v0.9.0 github.com/cosmos/cosmos-sdk v0.47.5 @@ -223,9 +221,9 @@ require ( ) replace ( - github.com/ODIN-PROTOCOL/odin-core => github.com/ODIN-PROTOCOL/odin-core/tree/v047-dep-update v0.7.1 + github.com/ODIN-PROTOCOL/odin-core => github.com/ODIN-PROTOCOL/odin-core/tree/v047-dep-update v0.7.2 github.com/confio/ics23/go => github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 - github.com/tendermint/tendermint => github.com/cometbft/cometbft v0.34.27 + github.com/tendermint/tendermint => github.com/cometbft/cometbft v0.37.2 google.golang.org/grpc => google.golang.org/grpc v1.59.0 ) diff --git a/go.sum b/go.sum index ae2a2a1a2..9612c3eba 100644 --- a/go.sum +++ b/go.sum @@ -941,6 +941,7 @@ github.com/Microsoft/hcsshim v0.8.20/go.mod h1:+w2gRZ5ReXQhFOrvSQeNfhrYB/dg3oDwT github.com/Microsoft/hcsshim v0.8.21/go.mod h1:+w2gRZ5ReXQhFOrvSQeNfhrYB/dg3oDwTOcER2fw4I4= github.com/Microsoft/hcsshim v0.8.23/go.mod h1:4zegtUJth7lAvFyc6cH2gGQ5B3OFQim01nnU2M8jKDg= github.com/Microsoft/hcsshim v0.9.2/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= +github.com/Microsoft/hcsshim v0.9.3/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= github.com/Microsoft/hcsshim v0.9.4/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= github.com/Microsoft/hcsshim/test v0.0.0-20200826032352-301c83a30e7c/go.mod h1:30A5igQ91GEmhYJF8TaRP79pMBOYynRsyOByfVV0dU4= github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU= @@ -966,7 +967,6 @@ github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrU github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= -github.com/Workiva/go-datastructures v1.0.53/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= github.com/Zilliqa/gozilliqa-sdk v1.2.1-0.20201201074141-dd0ecada1be6/go.mod h1:eSYp2T6f0apnuW8TzhV3f6Aff2SE8Dwio++U4ha4yEM= github.com/a8m/expect v1.0.0/go.mod h1:4IwSCMumY49ScypDnjNbYEjgVeqy1/U2cEs3Lat96eA= github.com/acomagu/bufpipe v1.0.3/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ2sYmHc4= @@ -1140,9 +1140,9 @@ github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= -github.com/bufbuild/buf v1.9.0/go.mod h1:1Q+rMHiMVcfgScEF/GOldxmu4o9TrQ2sQQh58K6MscE= +github.com/bufbuild/buf v1.7.0/go.mod h1:Go40fMAF46PnPLC7jJgTQhAI95pmC0+VtxFKVC0qLq0= +github.com/bufbuild/connect-go v0.2.0/go.mod h1:4efZ2eXFENwd4p7tuLaL9m0qtTsCOzuBvrohvRGevDM= github.com/bufbuild/connect-go v1.0.0/go.mod h1:9iNvh/NOsfhNBUH5CtvXeVUskQO1xsrEviH7ZArwZ3I= -github.com/bufbuild/protocompile v0.1.0/go.mod h1:ix/MMMdsT3fzxfw91dvbfzKW3fRRnuPCP47kpAm5m/4= github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= github.com/buger/jsonparser v0.0.0-20180808090653-f4dd9f5a6b44/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= @@ -1151,7 +1151,6 @@ github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0Bsq github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= github.com/butuzov/ireturn v0.1.1/go.mod h1:Wh6Zl3IMtTpaIKbmwzqi6olnM9ptYQxxVacMsOEFPoc= github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/bwesterb/go-ristretto v1.2.2/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/c-bata/go-prompt v0.2.2/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= github.com/caarlos0/ctrlc v1.0.0/go.mod h1:CdXpj4rmq0q/1Eb44M9zi2nKB0QraNKuRGYGrrHhcQw= github.com/campoy/unique v0.0.0-20180121183637-88950e537e7e/go.mod h1:9IOqJGCPMSc6E5ydlp5NIonxObaeu/Iub/X03EKPVYo= @@ -1205,7 +1204,6 @@ github.com/clbanning/mxj v1.8.4/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5P github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I= -github.com/cloudflare/circl v1.3.1/go.mod h1:+CauBF6R70Jqcyl8N2hC8pAXYbWkGIezuSbuGLtRhnw= github.com/cloudflare/cloudflare-go v0.14.0/go.mod h1:EnwdgGMaFOruiPZRFSgn+TsQ3hQ7C/YWzIGLeu5c304= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= github.com/cncf/udpa/go v0.0.0-20220112060539-c52dc94e7fbe/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= @@ -1238,7 +1236,7 @@ github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE github.com/coinbase/kryptology v1.8.0/go.mod h1:RYXOAPdzOGUe3qlSFkMGn58i3xUA8hmxYHksuq+8ciI= github.com/coinbase/rosetta-sdk-go v0.7.9 h1:lqllBjMnazTjIqYrOGv8h8jxjg9+hJazIGZr9ZvoCcA= github.com/coinbase/rosetta-sdk-go v0.7.9/go.mod h1:0/knutI7XGVqXmmH4OQD8OckFrbQ8yMsUZTG7FXCR2M= -github.com/cometbft/cometbft v0.34.27/go.mod h1:BcCbhKv7ieM0KEddnYXvQZR+pZykTKReJJYf7YC7qhw= +github.com/cometbft/cometbft v0.37.2/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= github.com/cometbft/cometbft v0.38.0 h1:ogKnpiPX7gxCvqTEF4ly25/wAxUqf181t30P3vqdpdc= github.com/cometbft/cometbft v0.38.0/go.mod h1:5Jz0Z8YsHSf0ZaAqGvi/ifioSdVFPtEGrm8Y9T/993k= github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= @@ -1290,6 +1288,7 @@ github.com/containerd/containerd v1.5.7/go.mod h1:gyvv6+ugqY25TiXxcZC3L5yOeYgEw0 github.com/containerd/containerd v1.5.8/go.mod h1:YdFSv5bTFLpG2HIYmfqDpSYYTDX+mc5qtSuYx1YUb/s= github.com/containerd/containerd v1.6.1/go.mod h1:1nJz5xCZPusx6jJU8Frfct988y0NpumIq9ODB0kLtoE= github.com/containerd/containerd v1.6.3-0.20220401172941-5ff8fce1fcc6/go.mod h1:WSt2SnDLAGWlu+Vl+EWay37seZLKqgRt6XLjIMy8SYM= +github.com/containerd/containerd v1.6.6/go.mod h1:ZoP1geJldzCVY3Tonoz7b1IXk8rIX0Nltt5QE4OMNk0= github.com/containerd/containerd v1.6.8/go.mod h1:By6p5KqPK0/7/CgO/A6t/Gz+CUYUu2zf1hUaaymVXB0= github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= github.com/containerd/continuity v0.0.0-20190815185530-f2a389ac0a02/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= @@ -1400,6 +1399,7 @@ github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= +github.com/cosmos/gogoproto v1.4.1/go.mod h1:Ac9lzL4vFpBMcptJROQ6dQ4M3pOEK5Z/l0Q9p+LoCr4= github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= github.com/cosmos/gogoproto v1.4.11 h1:LZcMHrx4FjUgrqQSWeaGC1v/TeuVFqSLa43CC6aWR2g= github.com/cosmos/gogoproto v1.4.11/go.mod h1:/g39Mh8m17X8Q/GDEs5zYTSNaNnInBSohtaxzQnYq1Y= @@ -1497,6 +1497,7 @@ github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TT github.com/docker/distribution v2.6.0-rc.1.0.20180327202408-83389a148052+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/distribution v2.8.0+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= @@ -1644,8 +1645,9 @@ github.com/go-fonts/liberation v0.2.0/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2H github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= github.com/go-git/go-billy/v5 v5.3.1/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= +github.com/go-git/go-billy/v5 v5.4.0/go.mod h1:vjbugF6Fz7JIflbVpl1hJsGjSHNltrSw45YK/ukIvQg= github.com/go-git/go-git-fixtures/v4 v4.3.1/go.mod h1:8LHG1a3SRW71ettAD/jW13h8c6AqjVSeL11RAdgaqpo= -github.com/go-git/go-git/v5 v5.5.1/go.mod h1:uz5PQ3d0gz7mSgzZhSJToM6ALPaKCdSnl58/Xb5hzr8= +github.com/go-git/go-git/v5 v5.5.2/go.mod h1:BE5hUJ5yaV2YMxhmaP4l6RBQ08kMxKSPD4BlxtH7OjI= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -1758,6 +1760,7 @@ github.com/gofrs/flock v0.0.0-20190320160742-5135e617513b/go.mod h1:F1TvTiK9OcQq github.com/gofrs/flock v0.7.3/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= github.com/gogo/googleapis v1.3.2/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c= @@ -2005,7 +2008,6 @@ github.com/gostaticanalysis/forcetypeassert v0.1.0/go.mod h1:qZEedyP/sY1lTGV1uJ3 github.com/gostaticanalysis/nilerr v0.1.1/go.mod h1:wZYb6YI5YAxxq0i1+VJbY0s2YONW0HU0GPE3+5PWN4A= github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M= github.com/gostaticanalysis/testutil v0.4.0/go.mod h1:bLIoPefWXrRi/ssLFWX1dx7Repi5x3CuviD3dgAZaBU= -github.com/gotestyourself/gotestyourself v1.4.0/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY= github.com/graph-gophers/graphql-go v1.3.0/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= @@ -2187,6 +2189,7 @@ github.com/ipfs/go-log/v2 v2.0.3/go.mod h1:O7P1lJt27vWHhOwQmcFEvlmo49ry2VY2+JfBW github.com/ipfs/go-log/v2 v2.0.5/go.mod h1:eZs4Xt4ZUJQFM3DlanGhy7TkwwawCZcSByscwkWG+dw= github.com/ipfs/go-log/v2 v2.1.1/go.mod h1:2v2nsGfZsvvAJz13SyFzf9ObaqwHiHxsPLEHntrv9KM= github.com/ishidawataru/sctp v0.0.0-20191218070446-00ab2ac2db07/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= +github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/j-keck/arping v1.0.2/go.mod h1:aJbELhR92bSk7tp79AWM/ftfc90EfEi2bQJrbBFOsPw= github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= @@ -2209,10 +2212,11 @@ github.com/jgautheron/goconst v1.5.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7H github.com/jhump/gopoet v0.0.0-20190322174617-17282ff210b3/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ= +github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f/go.mod h1:qr2b5kx4HbFS7/g4uYO5qv9ei8303JMsC7ESbYiqr2Q= github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= github.com/jhump/protoreflect v1.6.1/go.mod h1:RZQ/lnuN+zqeRVpQigTwO6o0AJUkxbnSnpuG7toUTG4= github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E= -github.com/jhump/protoreflect v1.13.1-0.20220928232736-101791cb1b4c/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= +github.com/jhump/protoreflect v1.12.1-0.20220721211354-060cc04fc18b/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= github.com/jhump/protoreflect v1.15.3 h1:6SFRuqU45u9hIZPJAoZ8c28T3nK64BNdp9w6jFonzls= github.com/jingyugao/rowserrcheck v0.0.0-20191204022205-72ab7603b68a/go.mod h1:xRskid8CManxVta/ALEhJha/pweKBaVG6fWgc0yH25s= github.com/jingyugao/rowserrcheck v1.1.1/go.mod h1:4yvlZSDb3IyDTUZJUmpZfm2Hwok+Dtp+nu2qOq+er9c= @@ -2555,6 +2559,7 @@ github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8oh github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/buildkit v0.8.1/go.mod h1:/kyU1hKy/aYCuP39GZA9MaKioovHku57N6cqlKZIaiQ= +github.com/moby/buildkit v0.10.3/go.mod h1:jxeOuly98l9gWHai0Ojrbnczrk/rf+o9/JqNhY+UCSo= github.com/moby/buildkit v0.10.4/go.mod h1:Yajz9vt1Zw5q9Pp4pdb3TCSUXJBIroIQGQ3TTs/sLug= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= @@ -2811,7 +2816,6 @@ github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 h1:hDSdbBuw3Lefr6 github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= -github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= @@ -2839,6 +2843,9 @@ github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5/go.mod h1:eCbImbZ95eXtAUI github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pointlander/compress v1.1.1-0.20190518213731-ff44bd196cc3/go.mod h1:q5NXNGzqj5uPnVuhGkZfmgHqNUhf15VLi6L9kW0VEc0= +github.com/pointlander/jetset v1.0.1-0.20190518214125-eee7eff80bd4/go.mod h1:RdR1j20Aj5pB6+fw6Y9Ur7lMHpegTEjY1vc19hEZL40= +github.com/pointlander/peg v1.0.1/go.mod h1:5hsGDQR2oZI4QoWz0/Kdg3VSVEC31iJw/b7WjqCBGRI= github.com/polyfloyd/go-errorlint v1.0.5/go.mod h1:APVvOesVSAnne5SClsPxPdfvZTVDojXh1/G3qb5wjGI= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= @@ -3004,7 +3011,6 @@ github.com/segmentio/kafka-go v0.4.25 h1:QVx9yz12syKBFkxR+dVDDwTO0ItHgnjjhIdBfqi github.com/segmentio/kafka-go v0.4.25/go.mod h1:XzMcoMjSzDGHcIwpWUI7GB43iKZ2fTVmryPSGLf/MPg= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/serialx/hashring v0.0.0-20190422032157-8b2912629002/go.mod h1:/yeG0My1xr/u+HZrFQ1tOQQQQrOawfyMUH13ai5brBc= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= github.com/shirou/gopsutil v0.0.0-20190901111213-e4ec7b275ada/go.mod h1:WWnYX4lzhCH5h/3YBfyVA3VbLYjlMZZAQcW9ojMexNc= @@ -3072,6 +3078,7 @@ github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHN github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/cobra v1.3.0/go.mod h1:BrRVncBjOJa/eUcVVm9CE+oC6as8k+VYr4NY7WCi9V4= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= +github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= github.com/spf13/cobra v1.6.0/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= @@ -3177,7 +3184,6 @@ github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiff github.com/timonwong/loggercheck v0.9.3/go.mod h1:wUqnk9yAOIKtGA39l1KLE9Iz0QiTocu/YZoOf+OzFdw= github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= github.com/tinylib/msgp v1.1.0/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= -github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= github.com/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0= github.com/tj/go-elastic v0.0.0-20171221160941-36157cbbebc2/go.mod h1:WjeM0Oo1eNAjXGDx2yma7uG2XoyRZTq1uv3M/o7imD0= github.com/tj/go-kinesis v0.0.0-20171128231115-08b17f58cb1b/go.mod h1:/yhzCV0xPfx6jb1bBgRFjl5lytqVqZXEaeqWP8lTEao= @@ -3201,7 +3207,6 @@ github.com/tonistiigi/go-actions-cache v0.0.0-20220404170428-0bdeb6e1eac7/go.mod github.com/tonistiigi/go-archvariant v1.0.0/go.mod h1:TxFmO5VS6vMq2kvs3ht04iPXtu2rUT/erOnGFYfk5Ho= github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea/go.mod h1:WPnis/6cRcDZSUvVmezrxJPkiO87ThFYsoUiMwWNDJk= github.com/tonistiigi/vt100 v0.0.0-20210615222946-8066bb97264f/go.mod h1:ulncasL3N9uLrVann0m+CDlJKWsIAP34MPcOJF6VRvc= -github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c/go.mod h1:hzIxponao9Kjc7aWznkXaL4U4TWaDSs8zcsY4Ka08nM= github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= @@ -3360,6 +3365,7 @@ go.opentelemetry.io/contrib v0.20.0/go.mod h1:G/EtFaa6qaN7+LxqfIAT3GiZa7Wv5DTBUz go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.20.0/go.mod h1:oVGt1LRbBOBq1A5BQLlUg9UaU/54aiHw8cgjV3aWZ/E= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.28.0/go.mod h1:vEhqr0m4eTc+DWxfsXoXue2GBgV2uUwVznkGIHW/e5w= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0/go.mod h1:LsankqVDx4W+RhZNA5uWarULII/MBhF5qwCYxTuyXjs= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.33.0/go.mod h1:y/SlJpJQPd2UzfBCj0E9Flk9FDCtTyqUmaCB41qFrWI= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.36.3/go.mod h1:Dts42MGkzZne2yCru741+bFiTMWkIj/LLRizad7b9tw= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0/go.mod h1:vHItvsnJtp7ES++nFLLFBzUWny7fJQSvTlxFcqQGUr4= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.20.0/go.mod h1:2AboqHi0CiIZU0qwhtUfCYD1GeUzvvIXWNkhDt7ZMG4= @@ -3368,6 +3374,7 @@ go.opentelemetry.io/otel v0.20.0/go.mod h1:Y3ugLH2oa81t5QO+Lty+zXf8zC9L26ax4Nzox go.opentelemetry.io/otel v1.3.0/go.mod h1:PWIKzi6JCp7sM0k9yZ43VX+T345uNbAkDKwHVjb2PTs= go.opentelemetry.io/otel v1.4.0/go.mod h1:jeAqMFKy2uLIxCtKxoFj0FAL5zAPKQagc3+GtBWakzk= go.opentelemetry.io/otel v1.4.1/go.mod h1:StM6F/0fSwpd8dKWDCdRr7uRvEPYdW0hBSlbdTiUde4= +go.opentelemetry.io/otel v1.8.0/go.mod h1:2pkj+iMj0o03Y+cW6/m8Y4WkRdYN3AvCXCnzRMp9yvM= go.opentelemetry.io/otel v1.11.0/go.mod h1:H2KtuEphyMvlhZ+F7tg9GRhAOe60moNx61Ex+WmiKkk= go.opentelemetry.io/otel/exporters/jaeger v1.4.1/go.mod h1:ZW7vkOu9nC1CxsD8bHNHCia5JUbwP39vxgd1q4Z5rCI= go.opentelemetry.io/otel/exporters/otlp v0.20.0/go.mod h1:YIieizyaN77rtLJra0buKiNBOm9XQfkPEKBeuhoMwAM= @@ -3382,7 +3389,6 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1/go.mod h1 go.opentelemetry.io/otel/internal/metric v0.27.0/go.mod h1:n1CVxRqKqYZtqyTh9U/onvKapPGv7y/rpyOTI+LFNzw= go.opentelemetry.io/otel/metric v0.20.0/go.mod h1:598I5tYlH1vzBjn+BTuhzTCSb/9debfNp6R3s7Pr1eU= go.opentelemetry.io/otel/metric v0.27.0/go.mod h1:raXDJ7uP2/Jc0nVZWQjJtzoyssOYWu/+pjZqRzfvZ7g= -go.opentelemetry.io/otel/metric v0.32.3/go.mod h1:pgiGmKohxHyTPHGOff+vrtIH39/R9fiO/WoenUQ3kcc= go.opentelemetry.io/otel/oteltest v0.20.0/go.mod h1:L7bgKf9ZB7qCwT9Up7i9/pn0PWIa9FqQ2IQ8LoxiGnw= go.opentelemetry.io/otel/sdk v0.20.0/go.mod h1:g/IcepuwNsoiX5Byy2nNV0ySUF1em498m7hBWC279Yc= go.opentelemetry.io/otel/sdk v1.3.0/go.mod h1:rIo4suHNhQwBIPg9axF8V9CA72Wz2mKF1teNrup8yzs= @@ -3393,6 +3399,7 @@ go.opentelemetry.io/otel/trace v0.20.0/go.mod h1:6GjCW8zgDjwGHGa6GkyeB8+/5vjT16g go.opentelemetry.io/otel/trace v1.3.0/go.mod h1:c/VDhno8888bvQYmbYLqe41/Ldmr/KKunbvWM4/fEjk= go.opentelemetry.io/otel/trace v1.4.0/go.mod h1:uc3eRsqDfWs9R7b92xbQbU42/eTNz4N+gLP8qJCi4aE= go.opentelemetry.io/otel/trace v1.4.1/go.mod h1:iYEVbroFCNut9QkwEczV9vMRPHNKSSwYZjulEtsmhFc= +go.opentelemetry.io/otel/trace v1.8.0/go.mod h1:0Bt3PXY8w+3pheS3hQUt+wow8b1ojPaTBoTCh2zIFI4= go.opentelemetry.io/otel/trace v1.11.0/go.mod h1:nyYjis9jy0gytE9LXGU+/m1sHTKbRY0fX0hulNNDP1U= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.11.0/go.mod h1:QpEjXPrNQzrFDZgoTo49dgHR9RYRSrg3NAKnUGl9YpQ= @@ -3426,6 +3433,7 @@ go.uber.org/zap v1.14.1/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= gocloud.dev v0.19.0/go.mod h1:SmKwiR8YwIMMJvQBKLsC3fHNyMwXLw3PMDO+VVteJMI= @@ -3658,14 +3666,13 @@ golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220617184016-355a448f1bc9/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220726230323-06994584191e/go.mod h1:AaygXjzTFtRAg2ttMY5RMuhpJ3cNnI0XpyFJD1iQRSM= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221012135044-0b7e1fb9d458/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= -golang.org/x/net v0.0.0-20221017152216-f25eb7ecb193/go.mod h1:RpDiru2p0u2F0lLpEoqnP2+7xs0ifAuOcJ442g6GU2s= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= @@ -3908,6 +3915,7 @@ golang.org/x/sys v0.0.0-20220627191245-f75cf1eec38b/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220702020025-31831981b65f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220727055044-e65921a090b8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -3915,7 +3923,6 @@ golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220915200043-7b5979e65e41/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20221013171732-95e765b1cc43/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -3936,7 +3943,6 @@ golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuX golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220526004731-065cf7ba2467/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.0.0-20220919170432-7a66f970e087/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= @@ -4084,7 +4090,6 @@ golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82u golang.org/x/tools v0.0.0-20200916195026-c9a70fc28ce3/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201001104356-43ebab892c4c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201002184944-ecd9fd270d5d/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= -golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201023174141-c8cfbd0f21e6/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201028025901-8cd080b735b3/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -4115,7 +4120,6 @@ golang.org/x/tools v0.1.12-0.20220628192153-7743d1d949f1/go.mod h1:SgwaegtQh8clI golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= -golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= @@ -4349,6 +4353,7 @@ google.golang.org/genproto v0.0.0-20220617124728-180714bec0ad/go.mod h1:KEWEmljW google.golang.org/genproto v0.0.0-20220624142145-8cd45d7dbd1f/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220722212130-b98a9ff5e252/go.mod h1:GkXuJDJ6aQ7lnJcRF+SJVgFdQhypqgl3LB1C9vabdRE= +google.golang.org/genproto v0.0.0-20220725144611-272f38e5d71b/go.mod h1:iHe1svFLAZg9VWz891+QbRMwUv9O/1Ww+/mngYeThbc= google.golang.org/genproto v0.0.0-20220801145646-83ce21fca29f/go.mod h1:iHe1svFLAZg9VWz891+QbRMwUv9O/1Ww+/mngYeThbc= google.golang.org/genproto v0.0.0-20220815135757-37a418bb8959/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= google.golang.org/genproto v0.0.0-20220817144833-d7fd3f11b9b1/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= @@ -4446,6 +4451,7 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= diff --git a/hooks/emitter/distribution.go b/hooks/emitter/distribution.go index 711de90a0..2733fb84e 100644 --- a/hooks/emitter/distribution.go +++ b/hooks/emitter/distribution.go @@ -1,7 +1,7 @@ package emitter import ( - "x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index f2da3e5fe..6d8e232f7 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -12,7 +12,7 @@ import ( tmjson "github.com/cometbft/cometbft/libs/json" "github.com/segmentio/kafka-go" - distrkeeper "x/distribution/keeper" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 845c47cbf..2692dc7e0 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -4,7 +4,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" diff --git a/x/bank/README.md b/x/bank/README.md deleted file mode 100644 index 1e9e154bc..000000000 --- a/x/bank/README.md +++ /dev/null @@ -1,950 +0,0 @@ ---- -sidebar_position: 1 ---- - -# `x/bank` - -## Abstract - -This document specifies the bank module of the Cosmos SDK. - -The bank module is responsible for handling multi-asset coin transfers between -accounts and tracking special-case pseudo-transfers which must work differently -with particular kinds of accounts (notably delegating/undelegating for vesting -accounts). It exposes several interfaces with varying capabilities for secure -interaction with other modules which must alter user balances. - -In addition, the bank module tracks and provides query support for the total -supply of all assets used in the application. - -This module is used in the Cosmos Hub. - -## Contents - -* [Supply](#supply) - * [Total Supply](#total-supply) -* [Module Accounts](#module-accounts) - * [Permissions](#permissions) -* [State](#state) -* [Params](#params) -* [Keepers](#keepers) -* [Messages](#messages) -* [Events](#events) - * [Message Events](#message-events) - * [Keeper Events](#keeper-events) -* [Parameters](#parameters) - * [SendEnabled](#sendenabled) - * [DefaultSendEnabled](#defaultsendenabled) -* [Client](#client) - * [CLI](#cli) - * [Query](#query) - * [Transactions](#transactions) -* [gRPC](#grpc) - -## Supply - -The `supply` functionality: - -* passively tracks the total supply of coins within a chain, -* provides a pattern for modules to hold/interact with `Coins`, and -* introduces the invariant check to verify a chain's total supply. - -### Total Supply - -The total `Supply` of the network is equal to the sum of all coins from the -account. The total supply is updated every time a `Coin` is minted (eg: as part -of the inflation mechanism) or burned (eg: due to slashing or if a governance -proposal is vetoed). - -## Module Accounts - -The supply functionality introduces a new type of `auth.Account` which can be used by -modules to allocate tokens and in special cases mint or burn tokens. At a base -level these module accounts are capable of sending/receiving tokens to and from -`auth.Account`s and other module accounts. This design replaces previous -alternative designs where, to hold tokens, modules would burn the incoming -tokens from the sender account, and then track those tokens internally. Later, -in order to send tokens, the module would need to effectively mint tokens -within a destination account. The new design removes duplicate logic between -modules to perform this accounting. - -The `ModuleAccount` interface is defined as follows: - -```go -type ModuleAccount interface { - auth.Account // same methods as the Account interface - - GetName() string // name of the module; used to obtain the address - GetPermissions() []string // permissions of module account - HasPermission(string) bool -} -``` - -> **WARNING!** -> Any module or message handler that allows either direct or indirect sending of funds must explicitly guarantee those funds cannot be sent to module accounts (unless allowed). - -The supply `Keeper` also introduces new wrapper functions for the auth `Keeper` -and the bank `Keeper` that are related to `ModuleAccount`s in order to be able -to: - -* Get and set `ModuleAccount`s by providing the `Name`. -* Send coins from and to other `ModuleAccount`s or standard `Account`s - (`BaseAccount` or `VestingAccount`) by passing only the `Name`. -* `Mint` or `Burn` coins for a `ModuleAccount` (restricted to its permissions). - -### Permissions - -Each `ModuleAccount` has a different set of permissions that provide different -object capabilities to perform certain actions. Permissions need to be -registered upon the creation of the supply `Keeper` so that every time a -`ModuleAccount` calls the allowed functions, the `Keeper` can lookup the -permissions to that specific account and perform or not perform the action. - -The available permissions are: - -* `Minter`: allows for a module to mint a specific amount of coins. -* `Burner`: allows for a module to burn a specific amount of coins. -* `Staking`: allows for a module to delegate and undelegate a specific amount of coins. - -## State - -The `x/bank` module keeps state of the following primary objects: - -1. Account balances -2. Denomination metadata -3. The total supply of all balances -4. Information on which denominations are allowed to be sent. - -In addition, the `x/bank` module keeps the following indexes to manage the -aforementioned state: - -* Supply Index: `0x0 | byte(denom) -> byte(amount)` -* Denom Metadata Index: `0x1 | byte(denom) -> ProtocolBuffer(Metadata)` -* Balances Index: `0x2 | byte(address length) | []byte(address) | []byte(balance.Denom) -> ProtocolBuffer(balance)` -* Reverse Denomination to Address Index: `0x03 | byte(denom) | 0x00 | []byte(address) -> 0` - -## Params - -The bank module stores it's params in state with the prefix of `0x05`, -it can be updated with governance or the address with authority. - -* Params: `0x05 | ProtocolBuffer(Params)` - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/bank.proto#L12-L23 -``` - -## Keepers - -The bank module provides these exported keeper interfaces that can be -passed to other modules that read or update account balances. Modules -should use the least-permissive interface that provides the functionality they -require. - -Best practices dictate careful review of `bank` module code to ensure that -permissions are limited in the way that you expect. - -### Denied Addresses - -The `x/bank` module accepts a map of addresses that are considered blocklisted -from directly and explicitly receiving funds through means such as `MsgSend` and -`MsgMultiSend` and direct API calls like `SendCoinsFromModuleToAccount`. - -Typically, these addresses are module accounts. If these addresses receive funds -outside the expected rules of the state machine, invariants are likely to be -broken and could result in a halted network. - -By providing the `x/bank` module with a blocklisted set of addresses, an error occurs for the operation if a user or client attempts to directly or indirectly send funds to a blocklisted account, for example, by using [IBC](https://ibc.cosmos.network). - -### Common Types - -#### Input - -An input of a multiparty transfer - -```protobuf -// Input models transaction input. -message Input { - string address = 1; - repeated cosmos.base.v1beta1.Coin coins = 2; -} -``` - -#### Output - -An output of a multiparty transfer. - -```protobuf -// Output models transaction outputs. -message Output { - string address = 1; - repeated cosmos.base.v1beta1.Coin coins = 2; -} -``` - -### BaseKeeper - -The base keeper provides full-permission access: the ability to arbitrary modify any account's balance and mint or burn coins. - -Restricted permission to mint per module could be achieved by using baseKeeper with `WithMintCoinsRestriction` to give specific restrictions to mint (e.g. only minting certain denom). - -```go -// Keeper defines a module interface that facilitates the transfer of coins -// between accounts. -type Keeper interface { - SendKeeper - WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper - - InitGenesis(sdk.Context, *types.GenesisState) - ExportGenesis(sdk.Context) *types.GenesisState - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - HasSupply(ctx sdk.Context, denom string) bool - GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) - IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) - GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool) - HasDenomMetaData(ctx sdk.Context, denom string) bool - SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metadata) - IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool) - - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - DelegateCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - - DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error - UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error - - // GetAuthority gets the address capable of executing governance proposal messages. Usually the gov module account. - GetAuthority() string - - types.QueryServer -} -``` - -### SendKeeper - -The send keeper provides access to account balances and the ability to transfer coins between -accounts. The send keeper does not alter the total supply (mint or burn coins). - -```go -// SendKeeper defines a module interface that facilitates the transfer of coins -// between accounts without the possibility of creating coins. -type SendKeeper interface { - ViewKeeper - - InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error - - GetParams(ctx sdk.Context) types.Params - SetParams(ctx sdk.Context, params types.Params) error - - IsSendEnabledDenom(ctx sdk.Context, denom string) bool - SetSendEnabled(ctx sdk.Context, denom string, value bool) - SetAllSendEnabled(ctx sdk.Context, sendEnableds []*types.SendEnabled) - DeleteSendEnabled(ctx sdk.Context, denom string) - IterateSendEnabledEntries(ctx sdk.Context, cb func(denom string, sendEnabled bool) (stop bool)) - GetAllSendEnabledEntries(ctx sdk.Context) []types.SendEnabled - - IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool - IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - - BlockedAddr(addr sdk.AccAddress) bool -} -``` - -### ViewKeeper - -The view keeper provides read-only access to account balances. The view keeper does not have balance alteration functionality. All balance lookups are `O(1)`. - -```go -// ViewKeeper defines a module interface that facilitates read only access to -// account balances. -type ViewKeeper interface { - ValidateBalance(ctx sdk.Context, addr sdk.AccAddress) error - HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool - - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetAccountsBalances(ctx sdk.Context) []types.Balance - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - LockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoin(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - - IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddress, cb func(coin sdk.Coin) (stop bool)) - IterateAllBalances(ctx sdk.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) -} -``` - -## Messages - -### MsgSend - -Send coins from one address to another. - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L38-L53 -``` - -The message will fail under the following conditions: - -* The coins do not have sending enabled -* The `to` address is restricted - -### MsgMultiSend - -Send coins from one sender and to a series of different address. If any of the receiving addresses do not correspond to an existing account, a new account is created. - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L58-L69 -``` - -The message will fail under the following conditions: - -* Any of the coins do not have sending enabled -* Any of the `to` addresses are restricted -* Any of the coins are locked -* The inputs and outputs do not correctly correspond to one another - -### MsgUpdateParams - -The `bank` module params can be updated through `MsgUpdateParams`, which can be done using governance proposal. The signer will always be the `gov` module account address. - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L74-L88 -``` - -The message handling can fail if: - -* signer is not the gov module account address. - -### MsgSetSendEnabled - -Used with the x/gov module to set create/edit SendEnabled entries. - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L96-L117 -``` - -The message will fail under the following conditions: - -* The authority is not a bech32 address. -* The authority is not x/gov module's address. -* There are multiple SendEnabled entries with the same Denom. -* One or more SendEnabled entries has an invalid Denom. - -## Events - -The bank module emits the following events: - -### Message Events - -#### MsgSend - -| Type | Attribute Key | Attribute Value | -| -------- | ------------- | ------------------ | -| transfer | recipient | {recipientAddress} | -| transfer | amount | {amount} | -| message | module | bank | -| message | action | send | -| message | sender | {senderAddress} | - -#### MsgMultiSend - -| Type | Attribute Key | Attribute Value | -| -------- | ------------- | ------------------ | -| transfer | recipient | {recipientAddress} | -| transfer | amount | {amount} | -| message | module | bank | -| message | action | multisend | -| message | sender | {senderAddress} | - -### Keeper Events - -In addition to message events, the bank keeper will produce events when the following methods are called (or any method which ends up calling them) - -#### MintCoins - -```json -{ - "type": "coinbase", - "attributes": [ - { - "key": "minter", - "value": "{{sdk.AccAddress of the module minting coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being minted}}", - "index": true - } - ] -} -``` - -```json -{ - "type": "coin_received", - "attributes": [ - { - "key": "receiver", - "value": "{{sdk.AccAddress of the module minting coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being received}}", - "index": true - } - ] -} -``` - -#### BurnCoins - -```json -{ - "type": "burn", - "attributes": [ - { - "key": "burner", - "value": "{{sdk.AccAddress of the module burning coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being burned}}", - "index": true - } - ] -} -``` - -```json -{ - "type": "coin_spent", - "attributes": [ - { - "key": "spender", - "value": "{{sdk.AccAddress of the module burning coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being burned}}", - "index": true - } - ] -} -``` - -#### addCoins - -```json -{ - "type": "coin_received", - "attributes": [ - { - "key": "receiver", - "value": "{{sdk.AccAddress of the address beneficiary of the coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being received}}", - "index": true - } - ] -} -``` - -#### subUnlockedCoins/DelegateCoins - -```json -{ - "type": "coin_spent", - "attributes": [ - { - "key": "spender", - "value": "{{sdk.AccAddress of the address which is spending coins}}", - "index": true - }, - { - "key": "amount", - "value": "{{sdk.Coins being spent}}", - "index": true - } - ] -} -``` - -## Parameters - -The bank module contains the following parameters - -### SendEnabled - -The SendEnabled parameter is now deprecated and not to be use. It is replaced -with state store records. - - -### DefaultSendEnabled - -The default send enabled value controls send transfer capability for all -coin denominations unless specifically included in the array of `SendEnabled` -parameters. - -## Client - -### CLI - -A user can query and interact with the `bank` module using the CLI. - -#### Query - -The `query` commands allow users to query `bank` state. - -```shell -simd query bank --help -``` - -##### balances - -The `balances` command allows users to query account balances by address. - -```shell -simd query bank balances [address] [flags] -``` - -Example: - -```shell -simd query bank balances cosmos1.. -``` - -Example Output: - -```yml -balances: -- amount: "1000000000" - denom: stake -pagination: - next_key: null - total: "0" -``` - -##### denom-metadata - -The `denom-metadata` command allows users to query metadata for coin denominations. A user can query metadata for a single denomination using the `--denom` flag or all denominations without it. - -```shell -simd query bank denom-metadata [flags] -``` - -Example: - -```shell -simd query bank denom-metadata --denom stake -``` - -Example Output: - -```yml -metadata: - base: stake - denom_units: - - aliases: - - STAKE - denom: stake - description: native staking token of simulation app - display: stake - name: SimApp Token - symbol: STK -``` - -##### total - -The `total` command allows users to query the total supply of coins. A user can query the total supply for a single coin using the `--denom` flag or all coins without it. - -```shell -simd query bank total [flags] -``` - -Example: - -```shell -simd query bank total --denom stake -``` - -Example Output: - -```yml -amount: "10000000000" -denom: stake -``` - -##### send-enabled - -The `send-enabled` command allows users to query for all or some SendEnabled entries. - -```shell -simd query bank send-enabled [denom1 ...] [flags] -``` - -Example: - -```shell -simd query bank send-enabled -``` - -Example output: - -```yml -send_enabled: -- denom: foocoin - enabled: true -- denom: barcoin -pagination: - next-key: null - total: 2 -``` - -#### Transactions - -The `tx` commands allow users to interact with the `bank` module. - -```shell -simd tx bank --help -``` - -##### send - -The `send` command allows users to send funds from one account to another. - -```shell -simd tx bank send [from_key_or_address] [to_address] [amount] [flags] -``` - -Example: - -```shell -simd tx bank send cosmos1.. cosmos1.. 100stake -``` - -## gRPC - -A user can query the `bank` module using gRPC endpoints. - -### Balance - -The `Balance` endpoint allows users to query account balance by address for a given denomination. - -```shell -cosmos.bank.v1beta1.Query/Balance -``` - -Example: - -```shell -grpcurl -plaintext \ - -d '{"address":"cosmos1..","denom":"stake"}' \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/Balance -``` - -Example Output: - -```json -{ - "balance": { - "denom": "stake", - "amount": "1000000000" - } -} -``` - -### AllBalances - -The `AllBalances` endpoint allows users to query account balance by address for all denominations. - -```shell -cosmos.bank.v1beta1.Query/AllBalances -``` - -Example: - -```shell -grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/AllBalances -``` - -Example Output: - -```json -{ - "balances": [ - { - "denom": "stake", - "amount": "1000000000" - } - ], - "pagination": { - "total": "1" - } -} -``` - -### DenomMetadata - -The `DenomMetadata` endpoint allows users to query metadata for a single coin denomination. - -```shell -cosmos.bank.v1beta1.Query/DenomMetadata -``` - -Example: - -```shell -grpcurl -plaintext \ - -d '{"denom":"stake"}' \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/DenomMetadata -``` - -Example Output: - -```json -{ - "metadata": { - "description": "native staking token of simulation app", - "denomUnits": [ - { - "denom": "stake", - "aliases": [ - "STAKE" - ] - } - ], - "base": "stake", - "display": "stake", - "name": "SimApp Token", - "symbol": "STK" - } -} -``` - -### DenomsMetadata - -The `DenomsMetadata` endpoint allows users to query metadata for all coin denominations. - -```shell -cosmos.bank.v1beta1.Query/DenomsMetadata -``` - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/DenomsMetadata -``` - -Example Output: - -```json -{ - "metadatas": [ - { - "description": "native staking token of simulation app", - "denomUnits": [ - { - "denom": "stake", - "aliases": [ - "STAKE" - ] - } - ], - "base": "stake", - "display": "stake", - "name": "SimApp Token", - "symbol": "STK" - } - ], - "pagination": { - "total": "1" - } -} -``` - -### DenomOwners - -The `DenomOwners` endpoint allows users to query metadata for a single coin denomination. - -```shell -cosmos.bank.v1beta1.Query/DenomOwners -``` - -Example: - -```shell -grpcurl -plaintext \ - -d '{"denom":"stake"}' \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/DenomOwners -``` - -Example Output: - -```json -{ - "denomOwners": [ - { - "address": "cosmos1..", - "balance": { - "denom": "stake", - "amount": "5000000000" - } - }, - { - "address": "cosmos1..", - "balance": { - "denom": "stake", - "amount": "5000000000" - } - }, - ], - "pagination": { - "total": "2" - } -} -``` - -### TotalSupply - -The `TotalSupply` endpoint allows users to query the total supply of all coins. - -```shell -cosmos.bank.v1beta1.Query/TotalSupply -``` - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/TotalSupply -``` - -Example Output: - -```json -{ - "supply": [ - { - "denom": "stake", - "amount": "10000000000" - } - ], - "pagination": { - "total": "1" - } -} -``` - -### SupplyOf - -The `SupplyOf` endpoint allows users to query the total supply of a single coin. - -```shell -cosmos.bank.v1beta1.Query/SupplyOf -``` - -Example: - -```shell -grpcurl -plaintext \ - -d '{"denom":"stake"}' \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/SupplyOf -``` - -Example Output: - -```json -{ - "amount": { - "denom": "stake", - "amount": "10000000000" - } -} -``` - -### Params - -The `Params` endpoint allows users to query the parameters of the `bank` module. - -```shell -cosmos.bank.v1beta1.Query/Params -``` - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/Params -``` - -Example Output: - -```json -{ - "params": { - "defaultSendEnabled": true - } -} -``` - -### SendEnabled - -The `SendEnabled` enpoints allows users to query the SendEnabled entries of the `bank` module. - -Any denominations NOT returned, use the `Params.DefaultSendEnabled` value. - -```shell -cosmos.bank.v1beta1.Query/SendEnabled -``` - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.bank.v1beta1.Query/SendEnabled -``` - -Example Output: - -```json -{ - "send_enabled": [ - { - "denom": "foocoin", - "enabled": true - }, - { - "denom": "barcoin" - } - ], - "pagination": { - "next-key": null, - "total": 2 - } -} -``` diff --git a/x/bank/app_test.go b/x/bank/app_test.go deleted file mode 100644 index 86f9f9ff0..000000000 --- a/x/bank/app_test.go +++ /dev/null @@ -1,449 +0,0 @@ -package bank_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - _ "github.com/cosmos/cosmos-sdk/x/auth" - _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/bank/types" - _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/gov" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - _ "github.com/cosmos/cosmos-sdk/x/params" - _ "github.com/cosmos/cosmos-sdk/x/staking" -) - -type ( - expectedBalance struct { - addr sdk.AccAddress - coins sdk.Coins - } - - appTestCase struct { - desc string - expSimPass bool - expPass bool - msgs []sdk.Msg - accNums []uint64 - accSeqs []uint64 - privKeys []cryptotypes.PrivKey - expectedBalances []expectedBalance - expInError []string - } -) - -var ( - priv1 = secp256k1.GenPrivKey() - addr1 = sdk.AccAddress(priv1.PubKey().Address()) - priv2 = secp256k1.GenPrivKey() - addr2 = sdk.AccAddress(priv2.PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} - halfCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 5)} - - sendMsg1 = types.NewMsgSend(addr1, addr2, coins) - - multiSendMsg1 = &types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(addr1, coins)}, - Outputs: []types.Output{types.NewOutput(addr2, coins)}, - } - multiSendMsg2 = &types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(addr1, coins)}, - Outputs: []types.Output{ - types.NewOutput(addr2, halfCoins), - types.NewOutput(addr3, halfCoins), - }, - } - multiSendMsg3 = &types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(addr2, coins)}, - Outputs: []types.Output{ - types.NewOutput(addr1, coins), - }, - } - multiSendMsg4 = &types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(addr1, coins)}, - Outputs: []types.Output{ - types.NewOutput(moduleAccAddr, coins), - }, - } - invalidMultiSendMsg = &types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(addr1, coins), types.NewInput(addr2, coins)}, - Outputs: []types.Output{}, - } -) - -type suite struct { - BankKeeper bankkeeper.Keeper - AccountKeeper types.AccountKeeper - App *runtime.App -} - -func createTestSuite(t *testing.T, genesisAccounts []authtypes.GenesisAccount) suite { - res := suite{} - - var genAccounts []simtestutil.GenesisAccount - for _, acc := range genesisAccounts { - genAccounts = append(genAccounts, simtestutil.GenesisAccount{GenesisAccount: acc}) - } - - startupCfg := simtestutil.DefaultStartUpConfig() - startupCfg.GenesisAccounts = genAccounts - - app, err := simtestutil.SetupWithConfiguration(configurator.NewAppConfig( - configurator.ParamsModule(), - configurator.AuthModule(), - configurator.StakingModule(), - configurator.TxModule(), - configurator.ConsensusModule(), - configurator.BankModule(), - configurator.GovModule(), - ), - startupCfg, &res.BankKeeper, &res.AccountKeeper) - - res.App = app - - require.NoError(t, err) - return res -} - -// CheckBalance checks the balance of an account. -func checkBalance(t *testing.T, baseApp *baseapp.BaseApp, addr sdk.AccAddress, balances sdk.Coins, keeper bankkeeper.Keeper) { - ctxCheck := baseApp.NewContext(true, tmproto.Header{}) - require.True(t, balances.IsEqual(keeper.GetAllBalances(ctxCheck, addr))) -} - -func TestSendNotEnoughBalance(t *testing.T) { - acc := &authtypes.BaseAccount{ - Address: addr1.String(), - } - - genAccs := []authtypes.GenesisAccount{acc} - s := createTestSuite(t, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67)))) - - baseApp.Commit() - - res1 := s.AccountKeeper.GetAccount(ctx, addr1) - require.NotNil(t, res1) - require.Equal(t, acc, res1.(*authtypes.BaseAccount)) - - origAccNum := res1.GetAccountNumber() - origSeq := res1.GetSequence() - - sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) - header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig - _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, []sdk.Msg{sendMsg}, "", []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) - require.Error(t, err) - - checkBalance(t, baseApp, addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 67)}, s.BankKeeper) - - ctx2 := baseApp.NewContext(true, tmproto.Header{}) - res2 := s.AccountKeeper.GetAccount(ctx2, addr1) - require.NotNil(t, res2) - - require.Equal(t, origAccNum, res2.GetAccountNumber()) - require.Equal(t, origSeq+1, res2.GetSequence()) -} - -func TestMsgMultiSendWithAccounts(t *testing.T) { - acc := &authtypes.BaseAccount{ - Address: addr1.String(), - } - - genAccs := []authtypes.GenesisAccount{acc} - s := createTestSuite(t, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67)))) - - baseApp.Commit() - - res1 := s.AccountKeeper.GetAccount(ctx, addr1) - require.NotNil(t, res1) - require.Equal(t, acc, res1.(*authtypes.BaseAccount)) - - testCases := []appTestCase{ - { - desc: "make a valid tx", - msgs: []sdk.Msg{multiSendMsg1}, - accNums: []uint64{0}, - accSeqs: []uint64{0}, - expSimPass: true, - expPass: true, - privKeys: []cryptotypes.PrivKey{priv1}, - expectedBalances: []expectedBalance{ - {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 57)}}, - {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}}, - }, - }, - { - desc: "wrong accNum should pass Simulate, but not Deliver", - msgs: []sdk.Msg{multiSendMsg1, multiSendMsg2}, - accNums: []uint64{1}, // wrong account number - accSeqs: []uint64{1}, - expSimPass: true, // doesn't check signature - expPass: false, - privKeys: []cryptotypes.PrivKey{priv1}, - }, - { - desc: "wrong accSeq should not pass Simulate", - msgs: []sdk.Msg{multiSendMsg4}, - accNums: []uint64{0}, - accSeqs: []uint64{0}, // wrong account sequence - expSimPass: false, - expPass: false, - privKeys: []cryptotypes.PrivKey{priv1}, - }, - { - desc: "multiple inputs not allowed", - msgs: []sdk.Msg{invalidMultiSendMsg}, - accNums: []uint64{0}, - accSeqs: []uint64{0}, - expSimPass: false, - expPass: false, - privKeys: []cryptotypes.PrivKey{priv1}, - }, - } - - for _, tc := range testCases { - header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig - _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - - for _, eb := range tc.expectedBalances { - checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper) - } - } -} - -func TestMsgMultiSendMultipleOut(t *testing.T) { - acc1 := &authtypes.BaseAccount{ - Address: addr1.String(), - } - acc2 := &authtypes.BaseAccount{ - Address: addr2.String(), - } - - genAccs := []authtypes.GenesisAccount{acc1, acc2} - s := createTestSuite(t, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42)))) - - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42)))) - - baseApp.Commit() - - testCases := []appTestCase{ - { - msgs: []sdk.Msg{multiSendMsg2}, - accNums: []uint64{0}, - accSeqs: []uint64{0}, - expSimPass: true, - expPass: true, - privKeys: []cryptotypes.PrivKey{priv1}, - expectedBalances: []expectedBalance{ - {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, - {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 47)}}, - {addr3, sdk.Coins{sdk.NewInt64Coin("foocoin", 5)}}, - }, - }, - } - - for _, tc := range testCases { - header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig - _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) - require.NoError(t, err) - - for _, eb := range tc.expectedBalances { - checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper) - } - } -} - -func TestMsgMultiSendDependent(t *testing.T) { - acc1 := authtypes.NewBaseAccountWithAddress(addr1) - acc2 := authtypes.NewBaseAccountWithAddress(addr2) - err := acc2.SetAccountNumber(1) - require.NoError(t, err) - - genAccs := []authtypes.GenesisAccount{acc1, acc2} - s := createTestSuite(t, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42)))) - - baseApp.Commit() - - testCases := []appTestCase{ - { - msgs: []sdk.Msg{multiSendMsg1}, - accNums: []uint64{0}, - accSeqs: []uint64{0}, - expSimPass: true, - expPass: true, - privKeys: []cryptotypes.PrivKey{priv1}, - expectedBalances: []expectedBalance{ - {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, - {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}}, - }, - }, - { - msgs: []sdk.Msg{multiSendMsg3}, - accNums: []uint64{1}, - accSeqs: []uint64{0}, - expSimPass: true, - expPass: true, - privKeys: []cryptotypes.PrivKey{priv2}, - expectedBalances: []expectedBalance{ - {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 42)}}, - }, - }, - } - - for _, tc := range testCases { - header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1} - txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig - _, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) - require.NoError(t, err) - - for _, eb := range tc.expectedBalances { - checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper) - } - } -} - -func TestMsgSetSendEnabled(t *testing.T) { - acc1 := authtypes.NewBaseAccountWithAddress(addr1) - - genAccs := []authtypes.GenesisAccount{acc1} - s := createTestSuite(t, genAccs) - - ctx := s.App.BaseApp.NewContext(false, tmproto.Header{}) - require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 101)))) - addr1Str := addr1.String() - govAddr := s.BankKeeper.GetAuthority() - goodGovProp, err := govv1.NewMsgSubmitProposal( - []sdk.Msg{ - types.NewMsgSetSendEnabled(govAddr, nil, nil), - }, - sdk.Coins{{"foocoin", sdk.NewInt(5)}}, - addr1Str, - "set default send enabled to true", - "Change send enabled", - "Modify send enabled and set to true", - ) - require.NoError(t, err, "making goodGovProp") - badGovProp, err := govv1.NewMsgSubmitProposal( - []sdk.Msg{ - types.NewMsgSetSendEnabled(govAddr, []*types.SendEnabled{{"bad coin name!", true}}, nil), - }, - sdk.Coins{{"foocoin", sdk.NewInt(5)}}, - addr1Str, - "set default send enabled to true", - "Change send enabled", - "Modify send enabled and set to true", - ) - require.NoError(t, err, "making badGovProp") - - testCases := []appTestCase{ - { - desc: "wrong authority", - expSimPass: false, - expPass: false, - msgs: []sdk.Msg{ - types.NewMsgSetSendEnabled(addr1Str, nil, nil), - }, - accSeqs: []uint64{0}, - expInError: []string{ - "invalid authority", - "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", - addr1Str, - "expected gov account as only signer for proposal message", - }, - }, - { - desc: "right authority wrong signer", - expSimPass: false, - expPass: false, - msgs: []sdk.Msg{ - types.NewMsgSetSendEnabled(govAddr, nil, nil), - }, - accSeqs: []uint64{1}, // wrong signer, so this sequence doesn't actually get used. - expInError: []string{ - "pubKey does not match signer address", - govAddr, - "with signer index: 0", - "invalid pubkey", - }, - }, - { - desc: "submitted good as gov prop", - expSimPass: true, - expPass: true, - msgs: []sdk.Msg{ - goodGovProp, - }, - accSeqs: []uint64{1}, - expInError: nil, - }, - { - desc: "submitted bad as gov prop", - expSimPass: false, - expPass: false, - msgs: []sdk.Msg{ - badGovProp, - }, - accSeqs: []uint64{2}, - expInError: []string{ - "invalid denom: bad coin name!", - "invalid proposal message", - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.desc, func(tt *testing.T) { - header := tmproto.Header{Height: s.App.LastBlockHeight() + 1} - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig - _, _, err = simtestutil.SignCheckDeliver(tt, txGen, s.App.BaseApp, header, tc.msgs, "", []uint64{0}, tc.accSeqs, tc.expSimPass, tc.expPass, priv1) - if len(tc.expInError) > 0 { - require.Error(tt, err) - for _, exp := range tc.expInError { - assert.ErrorContains(tt, err, exp) - } - } else { - require.NoError(tt, err) - } - }) - } -} diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go deleted file mode 100644 index 8c75129b6..000000000 --- a/x/bank/bench_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package bank_test - -import ( - "math/rand" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -var moduleAccAddr = authtypes.NewModuleAddress(stakingtypes.BondedPoolName) - -// GenSequenceOfTxs generates a set of signed transactions of messages, such -// that they differ only by having the sequence numbers incremented between -// every transaction. -func genSequenceOfTxs(txGen client.TxConfig, - msgs []sdk.Msg, - accNums []uint64, - initSeqNums []uint64, - numToGenerate int, - priv ...cryptotypes.PrivKey, -) ([]sdk.Tx, error) { - txs := make([]sdk.Tx, numToGenerate) - var err error - for i := 0; i < numToGenerate; i++ { - txs[i], err = simtestutil.GenSignedMockTx( - rand.New(rand.NewSource(time.Now().UnixNano())), - txGen, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - simtestutil.DefaultGenTxGas, - "", - accNums, - initSeqNums, - priv..., - ) - if err != nil { - break - } - - for i := 0; i < len(initSeqNums); i++ { - initSeqNums[i]++ - } - } - - return txs, err -} - -func BenchmarkOneBankSendTxPerBlock(b *testing.B) { - // b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023") - - b.ReportAllocs() - // Add an account at genesis - acc := authtypes.BaseAccount{ - Address: addr1.String(), - } - - // construct genesis state - genAccs := []types.GenesisAccount{&acc} - s := createTestSuite(&testing.T{}, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - // some value conceivably higher than the benchmarks would ever go - require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000)))) - - baseApp.Commit() - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig - - // Precompute all txs - txs, err := genSequenceOfTxs(txGen, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) - require.NoError(b, err) - b.ResetTimer() - - height := int64(3) - - // Run this with a profiler, so its easy to distinguish what time comes from - // Committing, and what time comes from Check/Deliver Tx. - for i := 0; i < b.N; i++ { - baseApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}}) - _, _, err := baseApp.SimCheck(txGen.TxEncoder(), txs[i]) - if err != nil { - panic("something is broken in checking transaction") - } - - _, _, err = baseApp.SimDeliver(txGen.TxEncoder(), txs[i]) - require.NoError(b, err) - baseApp.EndBlock(abci.RequestEndBlock{Height: height}) - baseApp.Commit() - height++ - } -} - -func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) { - // b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023") - - b.ReportAllocs() - // Add an account at genesis - acc := authtypes.BaseAccount{ - Address: addr1.String(), - } - - // Construct genesis state - genAccs := []authtypes.GenesisAccount{&acc} - s := createTestSuite(&testing.T{}, genAccs) - baseApp := s.App.BaseApp - ctx := baseApp.NewContext(false, tmproto.Header{}) - - // some value conceivably higher than the benchmarks would ever go - require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000)))) - - baseApp.Commit() - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig - - // Precompute all txs - txs, err := genSequenceOfTxs(txGen, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) - require.NoError(b, err) - b.ResetTimer() - - height := int64(3) - - // Run this with a profiler, so its easy to distinguish what time comes from - // Committing, and what time comes from Check/Deliver Tx. - for i := 0; i < b.N; i++ { - baseApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}}) - _, _, err := baseApp.SimCheck(txGen.TxEncoder(), txs[i]) - if err != nil { - panic("something is broken in checking transaction") - } - - _, _, err = baseApp.SimDeliver(txGen.TxEncoder(), txs[i]) - require.NoError(b, err) - baseApp.EndBlock(abci.RequestEndBlock{Height: height}) - baseApp.Commit() - height++ - } -} diff --git a/x/bank/client/cli/query.go b/x/bank/client/cli/query.go deleted file mode 100644 index 6726ae2f5..000000000 --- a/x/bank/client/cli/query.go +++ /dev/null @@ -1,341 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -const ( - FlagDenom = "denom" -) - -// GetQueryCmd returns the parent command for all x/bank CLi query commands. The -// provided clientCtx should have, at a minimum, a verifier, Tendermint RPC client, -// and marshaler set. -func GetQueryCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the bank module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - GetBalancesCmd(), - GetSpendableBalancesCmd(), - GetCmdQueryTotalSupply(), - GetCmdDenomsMetadata(), - GetCmdQuerySendEnabled(), - ) - - return cmd -} - -func GetBalancesCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "balances [address]", - Short: "Query for account balances by address", - Long: strings.TrimSpace( - fmt.Sprintf(`Query the total balance of an account or of a specific denomination. - -Example: - $ %s query %s balances [address] - $ %s query %s balances [address] --denom=[denom] -`, - version.AppName, types.ModuleName, version.AppName, types.ModuleName, - ), - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(FlagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - ctx := cmd.Context() - - if denom == "" { - params := types.NewQueryAllBalancesRequest(addr, pageReq) - - res, err := queryClient.AllBalances(ctx, params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - params := types.NewQueryBalanceRequest(addr, denom) - - res, err := queryClient.Balance(ctx, params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res.Balance) - }, - } - - cmd.Flags().String(FlagDenom, "", "The specific balance denomination to query for") - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "all balances") - - return cmd -} - -func GetSpendableBalancesCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "spendable-balances [address]", - Short: "Query for account spendable balances by address", - Example: fmt.Sprintf("$ %s query %s spendable-balances [address]", version.AppName, types.ModuleName), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(FlagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - ctx := cmd.Context() - - if denom == "" { - params := types.NewQuerySpendableBalancesRequest(addr, pageReq) - - res, err := queryClient.SpendableBalances(ctx, params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - params := types.NewQuerySpendableBalanceByDenomRequest(addr, denom) - - res, err := queryClient.SpendableBalanceByDenom(ctx, params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(FlagDenom, "", "The specific balance denomination to query for") - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "spendable balances") - - return cmd -} - -// GetCmdDenomsMetadata defines the cobra command to query client denomination metadata. -func GetCmdDenomsMetadata() *cobra.Command { - cmd := &cobra.Command{ - Use: "denom-metadata", - Short: "Query the client metadata for coin denominations", - Long: strings.TrimSpace( - fmt.Sprintf(`Query the client metadata for all the registered coin denominations - -Example: - To query for the client metadata of all coin denominations use: - $ %s query %s denom-metadata - -To query for the client metadata of a specific coin denomination use: - $ %s query %s denom-metadata --denom=[denom] -`, - version.AppName, types.ModuleName, version.AppName, types.ModuleName, - ), - ), - RunE: func(cmd *cobra.Command, _ []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(FlagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - if denom == "" { - res, err := queryClient.DenomsMetadata(cmd.Context(), &types.QueryDenomsMetadataRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - res, err := queryClient.DenomMetadata(cmd.Context(), &types.QueryDenomMetadataRequest{Denom: denom}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(FlagDenom, "", "The specific denomination to query client metadata for") - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func GetCmdQueryTotalSupply() *cobra.Command { - cmd := &cobra.Command{ - Use: "total", - Short: "Query the total supply of coins of the chain", - Args: cobra.NoArgs, - Long: strings.TrimSpace( - fmt.Sprintf(`Query total supply of coins that are held by accounts in the chain. - -Example: - $ %s query %s total - -To query for the total supply of a specific coin denomination use: - $ %s query %s total --denom=[denom] -`, - version.AppName, types.ModuleName, version.AppName, types.ModuleName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(FlagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - ctx := cmd.Context() - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - if denom == "" { - res, err := queryClient.TotalSupply(ctx, &types.QueryTotalSupplyRequest{Pagination: pageReq}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - res, err := queryClient.SupplyOf(ctx, &types.QuerySupplyOfRequest{Denom: denom}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Amount) - }, - } - - cmd.Flags().String(FlagDenom, "", "The specific balance denomination to query for") - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "all supply totals") - - return cmd -} - -func GetCmdQuerySendEnabled() *cobra.Command { - cmd := &cobra.Command{ - Use: "send-enabled [denom1 ...]", - Short: "Query for send enabled entries", - Long: strings.TrimSpace(`Query for send enabled entries that have been specifically set. - -To look up one or more specific denoms, supply them as arguments to this command. -To look up all denoms, do not provide any arguments. -`, - ), - Example: strings.TrimSpace( - fmt.Sprintf(`Getting one specific entry: - $ %[1]s query %[2]s send-enabled foocoin - -Getting two specific entries: - $ %[1]s query %[2]s send-enabled foocoin barcoin - -Getting all entries: - $ %[1]s query %[2]s send-enabled -`, - version.AppName, types.ModuleName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - reqPag, err := client.ReadPageRequest(client.MustFlagSetWithPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - req := &types.QuerySendEnabledRequest{ - Denoms: args, - Pagination: reqPag, - } - - res, err := queryClient.SendEnabled(cmd.Context(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "send enabled entries") - - return cmd -} diff --git a/x/bank/client/cli/query_test.go b/x/bank/client/cli/query_test.go deleted file mode 100644 index e8a0daa28..000000000 --- a/x/bank/client/cli/query_test.go +++ /dev/null @@ -1,448 +0,0 @@ -package cli_test - -import ( - "bytes" - "context" - "fmt" - "io" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/gogoproto/proto" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/cosmos/cosmos-sdk/testutil" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func (s *CLITestSuite) TestGetBalancesCmd() { - accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - cmd := cli.GetBalancesCmd() - cmd.SetOutput(io.Discard) - - testCases := []struct { - name string - ctxGen func() client.Context - args []string - expectResult proto.Message - expectErr bool - }{ - { - "valid query", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QueryAllBalancesResponse{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - accounts[0].Address.String(), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QueryAllBalancesResponse{}, - false, - }, - { - "valid query with denom", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QueryBalanceResponse{ - Balance: &sdk.Coin{}, - }) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - accounts[0].Address.String(), - fmt.Sprintf("--%s=photon", cli.FlagDenom), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &sdk.Coin{}, - false, - }, - { - "invalid Address", - func() client.Context { - return s.baseCtx - }, - []string{ - "foo", - }, - nil, - true, - }, - { - "invalid denom", - func() client.Context { - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Code: 1, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - accounts[0].Address.String(), - fmt.Sprintf("--%s=foo", cli.FlagDenom), - }, - nil, - true, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) - s.Require().NoError(err) - } - }) - } -} - -func (s *CLITestSuite) TestGetSpendableBalancesCmd() { - accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - - cmd := cli.GetSpendableBalancesCmd() - cmd.SetOutput(io.Discard) - - testCases := []struct { - name string - ctxGen func() client.Context - args []string - expectResult proto.Message - expectErr bool - }{ - { - "valid query", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QuerySpendableBalancesResponse{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - accounts[0].Address.String(), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QuerySpendableBalancesResponse{}, - false, - }, - { - "valid query with denom flag", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QuerySpendableBalanceByDenomRequest{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - accounts[0].Address.String(), - fmt.Sprintf("--%s=json", flags.FlagOutput), - fmt.Sprintf("--%s=photon", cli.FlagDenom), - }, - &types.QuerySpendableBalanceByDenomResponse{}, - false, - }, - { - "invalid Address", - func() client.Context { - return s.baseCtx - }, - []string{ - "foo", - }, - nil, - true, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) - s.Require().NoError(err) - } - }) - } -} - -func (s *CLITestSuite) TestGetCmdDenomsMetadata() { - cmd := cli.GetCmdDenomsMetadata() - cmd.SetOutput(io.Discard) - - testCases := []struct { - name string - ctxGen func() client.Context - args []string - expectResult proto.Message - expectErr bool - }{ - { - "valid query", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QueryDenomsMetadataResponse{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QueryDenomsMetadataResponse{}, - false, - }, - { - "valid query with denom", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QueryDenomMetadataResponse{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=photon", cli.FlagDenom), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QueryDenomMetadataResponse{}, - false, - }, - { - "invalid query with denom", - func() client.Context { - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Code: 1, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=foo", cli.FlagDenom), - }, - nil, - true, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) - s.Require().NoError(err) - } - }) - } -} - -func (s *CLITestSuite) TestGetCmdQueryTotalSupply() { - cmd := cli.GetCmdQueryTotalSupply() - cmd.SetOutput(io.Discard) - - testCases := []struct { - name string - ctxGen func() client.Context - args []string - expectResult proto.Message - expectErr bool - }{ - { - "valid query", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QueryTotalSupplyResponse{}) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QueryTotalSupplyResponse{}, - false, - }, - { - "valid query with denom", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QuerySupplyOfResponse{ - Amount: sdk.Coin{}, - }) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=photon", cli.FlagDenom), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &sdk.Coin{}, - false, - }, - { - "invalid query with denom", - func() client.Context { - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Code: 1, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=foo", cli.FlagDenom), - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - nil, - true, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) - s.Require().NoError(err) - } - }) - } -} - -func (s *CLITestSuite) TestGetCmdQuerySendEnabled() { - cmd := cli.GetCmdQuerySendEnabled() - cmd.SetOutput(io.Discard) - - testCases := []struct { - name string - ctxGen func() client.Context - args []string - expectResult proto.Message - expectErr bool - }{ - { - "valid query", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{}, - }) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QuerySendEnabledResponse{}, - false, - }, - { - "valid query with denoms", - func() client.Context { - bz, _ := s.encCfg.Codec.Marshal(&types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{}, - }) - c := clitestutil.NewMockTendermintRPC(abci.ResponseQuery{ - Value: bz, - }) - return s.baseCtx.WithClient(c) - }, - []string{ - "photon", - "stake", - fmt.Sprintf("--%s=json", flags.FlagOutput), - }, - &types.QuerySendEnabledResponse{}, - false, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - var outBuf bytes.Buffer - - clientCtx := tc.ctxGen().WithOutput(&outBuf) - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(tc.args) - - s.Require().NoError(client.SetCmdClientContextHandler(clientCtx, cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(s.encCfg.Codec.UnmarshalJSON(outBuf.Bytes(), tc.expectResult)) - s.Require().NoError(err) - } - }) - } -} diff --git a/x/bank/client/cli/suite_test.go b/x/bank/client/cli/suite_test.go deleted file mode 100644 index 648a701ce..000000000 --- a/x/bank/client/cli/suite_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package cli_test - -import ( - "io" - "testing" - - rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - testutilmod "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -type CLITestSuite struct { - suite.Suite - - kr keyring.Keyring - encCfg testutilmod.TestEncodingConfig - baseCtx client.Context -} - -func TestMigrateTestSuite(t *testing.T) { - suite.Run(t, new(CLITestSuite)) -} - -func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(bank.AppModuleBasic{}) - s.kr = keyring.NewInMemory(s.encCfg.Codec) - s.baseCtx = client.Context{}. - WithKeyring(s.kr). - WithTxConfig(s.encCfg.TxConfig). - WithCodec(s.encCfg.Codec). - WithClient(clitestutil.MockTendermintRPC{Client: rpcclientmock.Client{}}). - WithAccountRetriever(client.MockAccountRetriever{}). - WithOutput(io.Discard) -} diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go deleted file mode 100644 index c6d87b759..000000000 --- a/x/bank/client/cli/tx.go +++ /dev/null @@ -1,146 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var FlagSplit = "split" - -// NewTxCmd returns a root CLI command handler for all x/bank transaction commands. -func NewTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Bank transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - txCmd.AddCommand( - NewSendTxCmd(), - NewMultiSendTxCmd(), - ) - - return txCmd -} - -// NewSendTxCmd returns a CLI command handler for creating a MsgSend transaction. -func NewSendTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "send [from_key_or_address] [to_address] [amount]", - Short: "Send funds from one account to another.", - Long: `Send funds from one account to another. -Note, the '--from' flag is ignored as it is implied from [from_key_or_address]. -When using '--dry-run' a key name cannot be used, only a bech32 address. -`, - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - toAddr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[2]) - if err != nil { - return err - } - - msg := types.NewMsgSend(clientCtx.GetFromAddress(), toAddr, coins) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -// NewMultiSendTxCmd returns a CLI command handler for creating a MsgMultiSend transaction. -// For a better UX this command is limited to send funds from one account to two or more accounts. -func NewMultiSendTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "multi-send [from_key_or_address] [to_address_1 to_address_2 ...] [amount]", - Short: "Send funds from one account to two or more accounts.", - Long: `Send funds from one account to two or more accounts. -By default, sends the [amount] to each address of the list. -Using the '--split' flag, the [amount] is split equally between the addresses. -Note, the '--from' flag is ignored as it is implied from [from_key_or_address] and -separate addresses with space. -When using '--dry-run' a key name cannot be used, only a bech32 address.`, - Example: fmt.Sprintf("%s tx bank multi-send cosmos1... cosmos1... cosmos1... cosmos1... 10stake", version.AppName), - Args: cobra.MinimumNArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[len(args)-1]) - if err != nil { - return err - } - - if coins.IsZero() { - return fmt.Errorf("must send positive amount") - } - - split, err := cmd.Flags().GetBool(FlagSplit) - if err != nil { - return err - } - - totalAddrs := sdk.NewInt(int64(len(args) - 2)) - // coins to be received by the addresses - sendCoins := coins - if split { - sendCoins = coins.QuoInt(totalAddrs) - } - - var output []types.Output - for _, arg := range args[1 : len(args)-1] { - toAddr, err := sdk.AccAddressFromBech32(arg) - if err != nil { - return err - } - - output = append(output, types.NewOutput(toAddr, sendCoins)) - } - - // amount to be send from the from address - var amount sdk.Coins - if split { - // user input: 1000stake to send to 3 addresses - // actual: 333stake to each address (=> 999stake actually sent) - amount = sendCoins.MulInt(totalAddrs) - } else { - amount = coins.MulInt(totalAddrs) - } - - msg := types.NewMsgMultiSend([]types.Input{types.NewInput(clientCtx.FromAddress, amount)}, output) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().Bool(FlagSplit, false, "Send the equally split token amount to each address") - flags.AddTxFlagsToCmd(cmd) - - return cmd -} diff --git a/x/bank/client/cli/tx_test.go b/x/bank/client/cli/tx_test.go deleted file mode 100644 index 7f3fe4b56..000000000 --- a/x/bank/client/cli/tx_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package cli_test - -import ( - "context" - "fmt" - "io" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/client/cli" -) - -func (s *CLITestSuite) TestSendTxCmd() { - accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) - cmd := cli.NewSendTxCmd() - cmd.SetOutput(io.Discard) - - extraArgs := []string{ - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=test-chain", flags.FlagChainID), - } - - testCases := []struct { - name string - ctxGen func() client.Context - from, to sdk.AccAddress - amount sdk.Coins - extraArgs []string - expectErr bool - }{ - { - "valid transaction", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address, - accounts[0].Address, - sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), - ), - extraArgs, - false, - }, - { - "invalid to Address", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address, - sdk.AccAddress{}, - sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), - ), - extraArgs, - true, - }, - { - "invalid coins", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address, - accounts[0].Address, - nil, - extraArgs, - true, - }, - } - - for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - ctx := svrcmd.CreateExecuteContext(context.Background()) - - cmd.SetContext(ctx) - cmd.SetArgs(append([]string{tc.from.String(), tc.to.String(), tc.amount.String()}, tc.extraArgs...)) - - s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - } - }) - } -} - -func (s *CLITestSuite) TestMultiSendTxCmd() { - accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 3) - - cmd := cli.NewMultiSendTxCmd() - cmd.SetOutput(io.Discard) - - extraArgs := []string{ - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("photon", sdk.NewInt(10))).String()), - fmt.Sprintf("--%s=test-chain", flags.FlagChainID), - } - - testCases := []struct { - name string - ctxGen func() client.Context - from string - to []string - amount sdk.Coins - extraArgs []string - expectErr bool - }{ - { - "valid transaction", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address.String(), - []string{ - accounts[1].Address.String(), - accounts[2].Address.String(), - }, - sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), - ), - extraArgs, - false, - }, - { - "invalid from Address", - func() client.Context { - return s.baseCtx - }, - "foo", - []string{ - accounts[1].Address.String(), - accounts[2].Address.String(), - }, - sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), - ), - extraArgs, - true, - }, - { - "invalid recipients", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address.String(), - []string{ - accounts[1].Address.String(), - "bar", - }, - sdk.NewCoins( - sdk.NewCoin("stake", sdk.NewInt(10)), - sdk.NewCoin("photon", sdk.NewInt(40)), - ), - extraArgs, - true, - }, - { - "invalid amount", - func() client.Context { - return s.baseCtx - }, - accounts[0].Address.String(), - []string{ - accounts[1].Address.String(), - accounts[2].Address.String(), - }, - nil, - extraArgs, - true, - }, - } - - for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { - ctx := svrcmd.CreateExecuteContext(context.Background()) - - var args []string - args = append(args, tc.from) - args = append(args, tc.to...) - args = append(args, tc.amount.String()) - args = append(args, tc.extraArgs...) - - cmd.SetContext(ctx) - cmd.SetArgs(args) - - s.Require().NoError(client.SetCmdClientContextHandler(tc.ctxGen(), cmd)) - - err := cmd.Execute() - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err) - } - }) - } -} diff --git a/x/bank/exported/exported.go b/x/bank/exported/exported.go deleted file mode 100644 index 7ab9136e8..000000000 --- a/x/bank/exported/exported.go +++ /dev/null @@ -1,25 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// GenesisBalance defines a genesis balance interface that allows for account -// address and balance retrieval. -type GenesisBalance interface { - GetAddress() sdk.AccAddress - GetCoins() sdk.Coins -} - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go deleted file mode 100644 index b934430c4..000000000 --- a/x/bank/keeper/genesis.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// InitGenesis initializes the bank module's state from a given genesis state. -func (k BaseKeeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { - if err := k.SetParams(ctx, genState.Params); err != nil { - panic(err) - } - - for _, se := range genState.GetAllSendEnabled() { - k.SetSendEnabled(ctx, se.Denom, se.Enabled) - } - - totalSupply := sdk.Coins{} - genState.Balances = types.SanitizeGenesisBalances(genState.Balances) - - for _, balance := range genState.Balances { - addr := balance.GetAddress() - - if err := k.initBalances(ctx, addr, balance.Coins); err != nil { - panic(fmt.Errorf("error on setting balances %w", err)) - } - - totalSupply = totalSupply.Add(balance.Coins...) - } - - if !genState.Supply.Empty() && !genState.Supply.IsEqual(totalSupply) { - panic(fmt.Errorf("genesis supply is incorrect, expected %v, got %v", genState.Supply, totalSupply)) - } - - for _, supply := range totalSupply { - k.setSupply(ctx, supply) - } - - for _, meta := range genState.DenomMetadata { - k.SetDenomMetaData(ctx, meta) - } -} - -// ExportGenesis returns the bank module's genesis state. -func (k BaseKeeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - totalSupply, _, err := k.GetPaginatedTotalSupply(ctx, &query.PageRequest{Limit: query.MaxLimit}) - if err != nil { - panic(fmt.Errorf("unable to fetch total supply %v", err)) - } - - rv := types.NewGenesisState( - k.GetParams(ctx), - k.GetAccountsBalances(ctx), - totalSupply, - k.GetAllDenomMetaData(ctx), - k.GetAllSendEnabledEntries(ctx), - ) - return rv -} diff --git a/x/bank/keeper/genesis_test.go b/x/bank/keeper/genesis_test.go deleted file mode 100644 index 1fe468520..000000000 --- a/x/bank/keeper/genesis_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package keeper_test - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/bank/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -func (suite *KeeperTestSuite) TestExportGenesis() { - ctx := suite.ctx - - expectedMetadata := suite.getTestMetadata() - expectedBalances, expTotalSupply := suite.getTestBalancesAndSupply() - - // Adding genesis supply to the expTotalSupply - genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit}) - suite.Require().NoError(err) - expTotalSupply = expTotalSupply.Add(genesisSupply...) - - for i := range []int{1, 2} { - suite.bankKeeper.SetDenomMetaData(ctx, expectedMetadata[i]) - accAddr, err1 := sdk.AccAddressFromBech32(expectedBalances[i].Address) - if err1 != nil { - panic(err1) - } - // set balances via mint and send - suite.mockMintCoins(mintAcc) - suite. - Require(). - NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedBalances[i].Coins)) - suite.mockSendCoinsFromModuleToAccount(mintAcc, accAddr) - suite. - Require(). - NoError(suite.bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, accAddr, expectedBalances[i].Coins)) - } - - suite.Require().NoError(suite.bankKeeper.SetParams(ctx, types.DefaultParams())) - - exportGenesis := suite.bankKeeper.ExportGenesis(ctx) - - suite.Require().Len(exportGenesis.Params.SendEnabled, 0) - suite.Require().Equal(types.DefaultParams().DefaultSendEnabled, exportGenesis.Params.DefaultSendEnabled) - suite.Require().Equal(expTotalSupply, exportGenesis.Supply) - suite.Require().Subset(exportGenesis.Balances, expectedBalances) - suite.Require().Equal(expectedMetadata, exportGenesis.DenomMetadata) -} - -func (suite *KeeperTestSuite) getTestBalancesAndSupply() ([]types.Balance, sdk.Coins) { - addr2, _ := sdk.AccAddressFromBech32("cosmos1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0") - addr1, _ := sdk.AccAddressFromBech32("cosmos1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd") - addr1Balance := sdk.Coins{sdk.NewInt64Coin("testcoin3", 10)} - addr2Balance := sdk.Coins{sdk.NewInt64Coin("testcoin1", 32), sdk.NewInt64Coin("testcoin2", 34)} - - totalSupply := addr1Balance - totalSupply = totalSupply.Add(addr2Balance...) - - return []types.Balance{ - {Address: addr2.String(), Coins: addr2Balance}, - {Address: addr1.String(), Coins: addr1Balance}, - }, totalSupply -} - -func (suite *KeeperTestSuite) TestInitGenesis() { - m := types.Metadata{Description: sdk.DefaultBondDenom, Base: sdk.DefaultBondDenom, Display: sdk.DefaultBondDenom} - g := types.DefaultGenesisState() - g.DenomMetadata = []types.Metadata{m} - bk := suite.bankKeeper - bk.InitGenesis(suite.ctx, g) - - m2, found := bk.GetDenomMetaData(suite.ctx, m.Base) - suite.Require().True(found) - suite.Require().Equal(m, m2) -} - -func (suite *KeeperTestSuite) TestTotalSupply() { - // Prepare some test data. - defaultGenesis := types.DefaultGenesisState() - balances := []types.Balance{ - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(1))), Address: "cosmos1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0"}, - {Coins: sdk.NewCoins(sdk.NewCoin("barcoin", sdk.NewInt(1))), Address: "cosmos1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd"}, - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(10)), sdk.NewCoin("barcoin", sdk.NewInt(20))), Address: "cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q"}, - } - totalSupply := sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(11)), sdk.NewCoin("barcoin", sdk.NewInt(21))) - - genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit}) - suite.Require().NoError(err) - - testcases := []struct { - name string - genesis *types.GenesisState - expSupply sdk.Coins - expPanic bool - expPanicMsg string - }{ - { - "calculation NOT matching genesis Supply field", - types.NewGenesisState(defaultGenesis.Params, balances, sdk.NewCoins(sdk.NewCoin("wrongcoin", sdk.NewInt(1))), defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - nil, true, "genesis supply is incorrect, expected 1wrongcoin, got 21barcoin,11foocoin", - }, - { - "calculation matches genesis Supply field", - types.NewGenesisState(defaultGenesis.Params, balances, totalSupply, defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - totalSupply, false, "", - }, - { - "calculation is correct, empty genesis Supply field", - types.NewGenesisState(defaultGenesis.Params, balances, nil, defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - totalSupply, false, "", - }, - } - - for _, tc := range testcases { - tc := tc - suite.Run(tc.name, func() { - if tc.expPanic { - suite.PanicsWithError(tc.expPanicMsg, func() { suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis) }) - } else { - suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis) - totalSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit}) - suite.Require().NoError(err) - - // adding genesis supply to expected supply - expected := tc.expSupply.Add(genesisSupply...) - suite.Require().Equal(expected, totalSupply) - } - }) - } -} diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go deleted file mode 100644 index 6d7cbe9f6..000000000 --- a/x/bank/keeper/grpc_query.go +++ /dev/null @@ -1,300 +0,0 @@ -package keeper - -import ( - "context" - - "cosmossdk.io/math" - gogotypes "github.com/cosmos/gogoproto/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "cosmossdk.io/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var _ types.QueryServer = BaseKeeper{} - -// Balance implements the Query/Balance gRPC method -func (k BaseKeeper) Balance(ctx context.Context, req *types.QueryBalanceRequest) (*types.QueryBalanceResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - if err := sdk.ValidateDenom(req.Denom); err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - address, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - - balance := k.GetBalance(sdkCtx, address, req.Denom) - - return &types.QueryBalanceResponse{Balance: &balance}, nil -} - -// AllBalances implements the Query/AllBalances gRPC method -func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalancesRequest) (*types.QueryAllBalancesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - addr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - balances := sdk.NewCoins() - accountStore := k.getAccountStore(sdkCtx, addr) - - pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, value []byte) error { - denom := string(key) - balance, err := UnmarshalBalanceCompat(k.cdc, value, denom) - if err != nil { - return err - } - balances = append(balances, balance) - return nil - }) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) - } - - return &types.QueryAllBalancesResponse{Balances: balances, Pagination: pageRes}, nil -} - -// SpendableBalances implements a gRPC query handler for retrieving an account's -// spendable balances. -func (k BaseKeeper) SpendableBalances(ctx context.Context, req *types.QuerySpendableBalancesRequest) (*types.QuerySpendableBalancesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - addr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - balances := sdk.NewCoins() - accountStore := k.getAccountStore(sdkCtx, addr) - zeroAmt := math.ZeroInt() - - pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, _ []byte) error { - balances = append(balances, sdk.NewCoin(string(key), zeroAmt)) - return nil - }) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) - } - - result := sdk.NewCoins() - spendable := k.SpendableCoins(sdkCtx, addr) - - for _, c := range balances { - result = append(result, sdk.NewCoin(c.Denom, spendable.AmountOf(c.Denom))) - } - - return &types.QuerySpendableBalancesResponse{Balances: result, Pagination: pageRes}, nil -} - -// SpendableBalanceByDenom implements a gRPC query handler for retrieving an account's -// spendable balance for a specific denom. -func (k BaseKeeper) SpendableBalanceByDenom(ctx context.Context, req *types.QuerySpendableBalanceByDenomRequest) (*types.QuerySpendableBalanceByDenomResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - addr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - - if err := sdk.ValidateDenom(req.Denom); err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - spendable := k.SpendableCoin(sdkCtx, addr, req.Denom) - - return &types.QuerySpendableBalanceByDenomResponse{Balance: &spendable}, nil -} - -// TotalSupply implements the Query/TotalSupply gRPC method -func (k BaseKeeper) TotalSupply(ctx context.Context, req *types.QueryTotalSupplyRequest) (*types.QueryTotalSupplyResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalSupply, pageRes, err := k.GetPaginatedTotalSupply(sdkCtx, req.Pagination) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryTotalSupplyResponse{Supply: totalSupply, Pagination: pageRes}, nil -} - -// SupplyOf implements the Query/SupplyOf gRPC method -func (k BaseKeeper) SupplyOf(c context.Context, req *types.QuerySupplyOfRequest) (*types.QuerySupplyOfResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - if err := sdk.ValidateDenom(req.Denom); err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - ctx := sdk.UnwrapSDKContext(c) - supply := k.GetSupply(ctx, req.Denom) - - return &types.QuerySupplyOfResponse{Amount: sdk.NewCoin(req.Denom, supply.Amount)}, nil -} - -// Params implements the gRPC service handler for querying x/bank parameters. -func (k BaseKeeper) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := k.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// DenomsMetadata implements Query/DenomsMetadata gRPC method. -func (k BaseKeeper) DenomsMetadata(c context.Context, req *types.QueryDenomsMetadataRequest) (*types.QueryDenomsMetadataResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.DenomMetadataPrefix) - - metadatas := []types.Metadata{} - pageRes, err := query.Paginate(store, req.Pagination, func(_, value []byte) error { - var metadata types.Metadata - k.cdc.MustUnmarshal(value, &metadata) - - metadatas = append(metadatas, metadata) - return nil - }) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryDenomsMetadataResponse{ - Metadatas: metadatas, - Pagination: pageRes, - }, nil -} - -// DenomMetadata implements Query/DenomMetadata gRPC method. -func (k BaseKeeper) DenomMetadata(c context.Context, req *types.QueryDenomMetadataRequest) (*types.QueryDenomMetadataResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - if err := sdk.ValidateDenom(req.Denom); err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - ctx := sdk.UnwrapSDKContext(c) - - metadata, found := k.GetDenomMetaData(ctx, req.Denom) - if !found { - return nil, status.Errorf(codes.NotFound, "client metadata for denom %s", req.Denom) - } - - return &types.QueryDenomMetadataResponse{ - Metadata: metadata, - }, nil -} - -func (k BaseKeeper) DenomOwners( - goCtx context.Context, - req *types.QueryDenomOwnersRequest, -) (*types.QueryDenomOwnersResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - if err := sdk.ValidateDenom(req.Denom); err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - denomPrefixStore := k.getDenomAddressPrefixStore(ctx, req.Denom) - - var denomOwners []*types.DenomOwner - pageRes, err := query.FilteredPaginate( - denomPrefixStore, - req.Pagination, - func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - address, _, err := types.AddressAndDenomFromBalancesStore(key) - if err != nil { - return false, err - } - - denomOwners = append( - denomOwners, - &types.DenomOwner{ - Address: address.String(), - Balance: k.GetBalance(ctx, address, req.Denom), - }, - ) - } - - return true, nil - }, - ) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryDenomOwnersResponse{DenomOwners: denomOwners, Pagination: pageRes}, nil -} - -func (k BaseKeeper) SendEnabled(goCtx context.Context, req *types.QuerySendEnabledRequest) (*types.QuerySendEnabledResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(goCtx) - resp := &types.QuerySendEnabledResponse{} - if len(req.Denoms) > 0 { - store := ctx.KVStore(k.storeKey) - for _, denom := range req.Denoms { - if se, ok := k.getSendEnabled(store, denom); ok { - resp.SendEnabled = append(resp.SendEnabled, types.NewSendEnabled(denom, se)) - } - } - } else { - store := k.getSendEnabledPrefixStore(ctx) - var err error - - resp.Pagination, err = query.FilteredPaginate( - store, - req.Pagination, - func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var enabled gogotypes.BoolValue - k.cdc.MustUnmarshal(value, &enabled) - - resp.SendEnabled = append(resp.SendEnabled, types.NewSendEnabled(string(key), enabled.Value)) - } - return true, nil - }, - ) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - } - - return resp, nil -} diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go deleted file mode 100644 index 4b2b34464..000000000 --- a/x/bank/keeper/grpc_query_test.go +++ /dev/null @@ -1,644 +0,0 @@ -package keeper_test - -import ( - gocontext "context" - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/bank/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -func (suite *KeeperTestSuite) TestQueryBalance() { - ctx, queryClient := suite.ctx, suite.queryClient - _, _, addr := testdata.KeyTestPubAddr() - - _, err := queryClient.Balance(gocontext.Background(), &types.QueryBalanceRequest{}) - suite.Require().Error(err) - - _, err = queryClient.Balance(gocontext.Background(), &types.QueryBalanceRequest{Address: addr.String()}) - suite.Require().Error(err) - - req := types.NewQueryBalanceRequest(addr, "0000") - _, err = queryClient.Balance(gocontext.Background(), req) - suite.Require().Error(err) - - req = types.NewQueryBalanceRequest(addr, fooDenom) - res, err := queryClient.Balance(gocontext.Background(), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.True(res.Balance.IsZero()) - - origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30)) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins)) - - res, err = queryClient.Balance(gocontext.Background(), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.True(res.Balance.IsEqual(newFooCoin(50))) -} - -func (suite *KeeperTestSuite) TestQueryAllBalances() { - ctx, queryClient := suite.ctx, suite.queryClient - _, _, addr := testdata.KeyTestPubAddr() - _, err := queryClient.AllBalances(gocontext.Background(), &types.QueryAllBalancesRequest{}) - suite.Require().Error(err) - - pageReq := &query.PageRequest{ - Key: nil, - Limit: 1, - CountTotal: false, - } - req := types.NewQueryAllBalancesRequest(addr, pageReq) - res, err := queryClient.AllBalances(gocontext.Background(), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.True(res.Balances.IsZero()) - - fooCoins := newFooCoin(50) - barCoins := newBarCoin(30) - - origCoins := sdk.NewCoins(fooCoins, barCoins) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins)) - - res, err = queryClient.AllBalances(gocontext.Background(), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Equal(res.Balances.Len(), 1) - suite.NotNil(res.Pagination.NextKey) - - suite.T().Log("query second page with nextkey") - pageReq = &query.PageRequest{ - Key: res.Pagination.NextKey, - Limit: 1, - CountTotal: true, - } - req = types.NewQueryAllBalancesRequest(addr, pageReq) - res, err = queryClient.AllBalances(gocontext.Background(), req) - suite.Require().NoError(err) - suite.Equal(res.Balances.Len(), 1) - suite.Nil(res.Pagination.NextKey) -} - -func (suite *KeeperTestSuite) TestSpendableBalances() { - ctx := suite.ctx - _, _, addr := testdata.KeyTestPubAddr() - ctx = ctx.WithBlockTime(time.Now()) - queryClient := suite.mockQueryClient(ctx) - - _, err := queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), &types.QuerySpendableBalancesRequest{}) - suite.Require().Error(err) - - pageReq := &query.PageRequest{ - Key: nil, - Limit: 2, - CountTotal: false, - } - req := types.NewQuerySpendableBalancesRequest(addr, pageReq) - acc := authtypes.NewBaseAccountWithAddress(addr) - - suite.mockSpendableCoins(ctx, acc) - res, err := queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.True(res.Balances.IsZero()) - - fooCoins := newFooCoin(50) - barCoins := newBarCoin(30) - - origCoins := sdk.NewCoins(fooCoins, barCoins) - vacc := vestingtypes.NewContinuousVestingAccount( - acc, - sdk.NewCoins(fooCoins), - ctx.BlockTime().Unix(), - ctx.BlockTime().Add(time.Hour).Unix(), - ) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, suite.ctx, addr, origCoins)) - - // move time forward for some tokens to vest - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(30 * time.Minute)) - queryClient = suite.mockQueryClient(ctx) - - suite.mockSpendableCoins(ctx, vacc) - res, err = queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Equal(2, res.Balances.Len()) - suite.Nil(res.Pagination.NextKey) - suite.EqualValues(30, res.Balances[0].Amount.Int64()) - suite.EqualValues(25, res.Balances[1].Amount.Int64()) -} - -func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { - ctx := suite.ctx - _, _, addr := testdata.KeyTestPubAddr() - ctx = ctx.WithBlockTime(time.Now()) - queryClient := suite.mockQueryClient(ctx) - - _, err := queryClient.SpendableBalanceByDenom(ctx, &types.QuerySpendableBalanceByDenomRequest{}) - suite.Require().Error(err) - - req := types.NewQuerySpendableBalanceByDenomRequest(addr, fooDenom) - acc := authtypes.NewBaseAccountWithAddress(addr) - - suite.mockSpendableCoins(ctx, acc) - res, err := queryClient.SpendableBalanceByDenom(ctx, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.True(res.Balance.IsZero()) - - fooCoins := newFooCoin(100) - barCoins := newBarCoin(30) - - origCoins := sdk.NewCoins(fooCoins, barCoins) - vacc := vestingtypes.NewContinuousVestingAccount( - acc, - sdk.NewCoins(fooCoins), - ctx.BlockTime().Unix(), - ctx.BlockTime().Add(time.Hour).Unix(), - ) - - suite.mockFundAccount(addr) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, suite.ctx, addr, origCoins)) - - // move time forward for half of the tokens to vest - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(30 * time.Minute)) - queryClient = suite.mockQueryClient(ctx) - - // check fooCoins first, it has some vested and some vesting - suite.mockSpendableCoins(ctx, vacc) - res, err = queryClient.SpendableBalanceByDenom(ctx, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.EqualValues(50, res.Balance.Amount.Int64()) - - // check barCoins, all of it is spendable - req.Denom = barDenom - suite.mockSpendableCoins(ctx, vacc) - res, err = queryClient.SpendableBalanceByDenom(ctx, req) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.EqualValues(30, res.Balance.Amount.Int64()) -} - -func (suite *KeeperTestSuite) TestQueryTotalSupply() { - ctx, queryClient := suite.ctx, suite.queryClient - res, err := queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{}) - suite.Require().NoError(err) - genesisSupply := res.Supply - testCoins := sdk.NewCoins(sdk.NewInt64Coin("test", 400000000)) - - suite.mockMintCoins(mintAcc) - suite. - Require(). - NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins)) - - res, err = queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{}) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - expectedTotalSupply := genesisSupply.Add(testCoins...) - suite.Require().Equal(1, len(res.Supply)) - suite.Require().Equal(res.Supply, expectedTotalSupply) -} - -func (suite *KeeperTestSuite) TestQueryTotalSupplyOf() { - ctx, queryClient := suite.ctx, suite.queryClient - - test1Supply := sdk.NewInt64Coin("test1", 4000000) - test2Supply := sdk.NewInt64Coin("test2", 700000000) - expectedTotalSupply := sdk.NewCoins(test1Supply, test2Supply) - - suite.mockMintCoins(mintAcc) - suite. - Require(). - NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply)) - - _, err := queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{}) - suite.Require().Error(err) - - res, err := queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{Denom: test1Supply.Denom}) - suite.Require().NoError(err) - suite.Require().NotNil(res) - - suite.Require().Equal(test1Supply, res.Amount) -} - -func (suite *KeeperTestSuite) TestQueryParams() { - res, err := suite.queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().Equal(suite.bankKeeper.GetParams(suite.ctx), res.GetParams()) -} - -func (suite *KeeperTestSuite) QueryDenomsMetadataRequest() { - var ( - req *types.QueryDenomsMetadataRequest - expMetadata = []types.Metadata{} - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty pagination", - func() { - req = &types.QueryDenomsMetadataRequest{} - }, - true, - }, - { - "success, no results", - func() { - req = &types.QueryDenomsMetadataRequest{ - Pagination: &query.PageRequest{ - Limit: 3, - CountTotal: true, - }, - } - }, - true, - }, - { - "success", - func() { - metadataAtom := types.Metadata{ - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - { - Denom: "uatom", - Exponent: 0, - Aliases: []string{"microatom"}, - }, - { - Denom: "atom", - Exponent: 6, - Aliases: []string{"ATOM"}, - }, - }, - Base: "uatom", - Display: "atom", - } - - metadataEth := types.Metadata{ - Description: "Ethereum native token", - DenomUnits: []*types.DenomUnit{ - { - Denom: "wei", - Exponent: 0, - }, - { - Denom: "eth", - Exponent: 18, - Aliases: []string{"ETH", "ether"}, - }, - }, - Base: "wei", - Display: "eth", - } - - suite.bankKeeper.SetDenomMetaData(suite.ctx, metadataAtom) - suite.bankKeeper.SetDenomMetaData(suite.ctx, metadataEth) - expMetadata = []types.Metadata{metadataAtom, metadataEth} - req = &types.QueryDenomsMetadataRequest{ - Pagination: &query.PageRequest{ - Limit: 7, - CountTotal: true, - }, - } - }, - true, - }, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { - suite.SetupTest() // reset - - tc.malleate() - ctx := sdk.WrapSDKContext(suite.ctx) - - res, err := suite.queryClient.DenomsMetadata(ctx, req) - - if tc.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().Equal(expMetadata, res.Metadatas) - } else { - suite.Require().Error(err) - } - }) - } -} - -func (suite *KeeperTestSuite) QueryDenomMetadataRequest() { - var ( - req *types.QueryDenomMetadataRequest - expMetadata = types.Metadata{} - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "empty denom", - func() { - req = &types.QueryDenomMetadataRequest{} - }, - false, - }, - { - "not found denom", - func() { - req = &types.QueryDenomMetadataRequest{ - Denom: "foo", - } - }, - false, - }, - { - "success", - func() { - expMetadata := types.Metadata{ - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - { - Denom: "uatom", - Exponent: 0, - Aliases: []string{"microatom"}, - }, - { - Denom: "atom", - Exponent: 6, - Aliases: []string{"ATOM"}, - }, - }, - Base: "uatom", - Display: "atom", - } - - suite.bankKeeper.SetDenomMetaData(suite.ctx, expMetadata) - req = &types.QueryDenomMetadataRequest{ - Denom: expMetadata.Base, - } - }, - true, - }, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { - suite.SetupTest() // reset - - tc.malleate() - ctx := sdk.WrapSDKContext(suite.ctx) - - res, err := suite.queryClient.DenomMetadata(ctx, req) - - if tc.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(res) - suite.Require().Equal(expMetadata, res.Metadata) - } else { - suite.Require().Error(err) - } - }) - } -} - -func (suite *KeeperTestSuite) TestGRPCDenomOwners() { - ctx := suite.ctx - - keeper := suite.bankKeeper - - suite.mockMintCoins(mintAcc) - suite.Require().NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins)) - - for i := 0; i < 10; i++ { - addr := sdk.AccAddress([]byte(fmt.Sprintf("account-%d", i))) - - bal := sdk.NewCoins(sdk.NewCoin( - sdk.DefaultBondDenom, - sdk.TokensFromConsensusPower(initialPower/10, sdk.DefaultPowerReduction), - )) - suite.mockSendCoinsFromModuleToAccount(mintAcc, addr) - suite.Require().NoError(keeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, bal)) - } - - testCases := map[string]struct { - req *types.QueryDenomOwnersRequest - expPass bool - numAddrs int - hasNext bool - total uint64 - }{ - "empty request": { - req: &types.QueryDenomOwnersRequest{}, - expPass: false, - }, - "invalid denom": { - req: &types.QueryDenomOwnersRequest{ - Denom: "foo", - }, - expPass: true, - numAddrs: 0, - hasNext: false, - total: 0, - }, - "valid request - page 1": { - req: &types.QueryDenomOwnersRequest{ - Denom: sdk.DefaultBondDenom, - Pagination: &query.PageRequest{ - Limit: 6, - CountTotal: true, - }, - }, - expPass: true, - numAddrs: 6, - hasNext: true, - total: 10, - }, - "valid request - page 2": { - req: &types.QueryDenomOwnersRequest{ - Denom: sdk.DefaultBondDenom, - Pagination: &query.PageRequest{ - Offset: 6, - Limit: 10, - CountTotal: true, - }, - }, - expPass: true, - numAddrs: 4, - hasNext: false, - total: 10, - }, - } - - for name, tc := range testCases { - suite.Run(name, func() { - resp, err := suite.queryClient.DenomOwners(gocontext.Background(), tc.req) - if tc.expPass { - suite.NoError(err) - suite.NotNil(resp) - suite.Len(resp.DenomOwners, tc.numAddrs) - suite.Equal(tc.total, resp.Pagination.Total) - - if tc.hasNext { - suite.NotNil(resp.Pagination.NextKey) - } else { - suite.Nil(resp.Pagination.NextKey) - } - } else { - suite.Require().Error(err) - } - }) - } - - suite.Require().True(true) -} - -func (suite *KeeperTestSuite) TestQuerySendEnabled() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - - bankKeeper.SetSendEnabled(ctx, "falsestcoin", false) - bankKeeper.SetSendEnabled(ctx, "truestcoin", true) - - tests := []struct { - name string - req *types.QuerySendEnabledRequest - exp *types.QuerySendEnabledResponse - }{ - { - name: "nil denoms list", - req: &types.QuerySendEnabledRequest{Denoms: []string{}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "falsestcoin", Enabled: false}, - {Denom: "truestcoin", Enabled: true}, - }, - Pagination: &query.PageResponse{ - NextKey: nil, - Total: 2, - }, - }, - }, - { - name: "empty denoms list", - req: &types.QuerySendEnabledRequest{Denoms: []string{}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "falsestcoin", Enabled: false}, - {Denom: "truestcoin", Enabled: true}, - }, - Pagination: &query.PageResponse{ - NextKey: nil, - Total: 2, - }, - }, - }, - { - name: "limit 1", - req: &types.QuerySendEnabledRequest{ - Pagination: &query.PageRequest{ - Limit: 1, - CountTotal: true, - }, - }, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "falsestcoin", Enabled: false}, - }, - Pagination: &query.PageResponse{ - NextKey: []byte("truestcoin"), - Total: 2, - }, - }, - }, - { - name: "just truestcoin", - req: &types.QuerySendEnabledRequest{Denoms: []string{"truestcoin"}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "truestcoin", Enabled: true}, - }, - Pagination: nil, - }, - }, - { - name: "just falsestcoin", - req: &types.QuerySendEnabledRequest{Denoms: []string{"falsestcoin"}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "falsestcoin", Enabled: false}, - }, - Pagination: nil, - }, - }, - { - name: "just an unknown coin", - req: &types.QuerySendEnabledRequest{Denoms: []string{"unknowniercoin"}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: nil, - Pagination: nil, - }, - }, - { - name: "both truestcoin falsestcoin", - req: &types.QuerySendEnabledRequest{Denoms: []string{"truestcoin", "falsestcoin"}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "truestcoin", Enabled: true}, - {Denom: "falsestcoin", Enabled: false}, - }, - Pagination: nil, - }, - }, - { - name: "both truestcoin falsestcoin and an unknown", - req: &types.QuerySendEnabledRequest{Denoms: []string{"truestcoin", "falsestcoin", "unknownestcoin"}}, - exp: &types.QuerySendEnabledResponse{ - SendEnabled: []*types.SendEnabled{ - {Denom: "truestcoin", Enabled: true}, - {Denom: "falsestcoin", Enabled: false}, - }, - Pagination: nil, - }, - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - resp, err := suite.queryClient.SendEnabled(gocontext.Background(), tc.req) - suite.Require().NoError(err) - if !suite.Assert().Equal(tc.exp, resp) { - if !suite.Assert().Len(resp.SendEnabled, len(tc.exp.SendEnabled)) { - for i := range tc.exp.SendEnabled { - suite.Assert().Equal(tc.exp.SendEnabled[i].Denom, resp.SendEnabled[i].Denom, fmt.Sprintf("SendEnabled[%d].Denom", i)) - suite.Assert().Equal(tc.exp.SendEnabled[i].Enabled, resp.SendEnabled[i].Enabled, fmt.Sprintf("SendEnabled[%d].Enabled", i)) - } - } - if !suite.Assert().Equal(tc.exp.Pagination, resp.Pagination, "Pagination") && tc.exp.Pagination != nil && resp.Pagination != nil { - suite.Assert().Equal(tc.exp.Pagination.NextKey, resp.Pagination.NextKey, "Pagination.NextKey") - suite.Assert().Equal(tc.exp.Pagination.Total, resp.Pagination.Total, "Pagination.Total") - } - } - suite.Require().Equal(tc.exp, resp) - }) - } -} diff --git a/x/bank/keeper/invariants.go b/x/bank/keeper/invariants.go deleted file mode 100644 index dead9dca0..000000000 --- a/x/bank/keeper/invariants.go +++ /dev/null @@ -1,73 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// RegisterInvariants registers the bank module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "nonnegative-outstanding", NonnegativeBalanceInvariant(k)) - ir.RegisterRoute(types.ModuleName, "total-supply", TotalSupply(k)) -} - -// AllInvariants runs all invariants of the X/bank module. -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - return TotalSupply(k)(ctx) - } -} - -// NonnegativeBalanceInvariant checks that all accounts in the application have non-negative balances -func NonnegativeBalanceInvariant(k ViewKeeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - var ( - msg string - count int - ) - - k.IterateAllBalances(ctx, func(addr sdk.AccAddress, balance sdk.Coin) bool { - if balance.IsNegative() { - count++ - msg += fmt.Sprintf("\t%s has a negative balance of %s\n", addr, balance) - } - - return false - }) - - broken := count != 0 - - return sdk.FormatInvariant( - types.ModuleName, "nonnegative-outstanding", - fmt.Sprintf("amount of negative balances found %d\n%s", count, msg), - ), broken - } -} - -// TotalSupply checks that the total supply reflects all the coins held in accounts -func TotalSupply(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - expectedTotal := sdk.Coins{} - supply, _, err := k.GetPaginatedTotalSupply(ctx, &query.PageRequest{Limit: query.MaxLimit}) - if err != nil { - return sdk.FormatInvariant(types.ModuleName, "query supply", - fmt.Sprintf("error querying total supply %v", err)), false - } - - k.IterateAllBalances(ctx, func(_ sdk.AccAddress, balance sdk.Coin) bool { - expectedTotal = expectedTotal.Add(balance) - return false - }) - - broken := !expectedTotal.IsEqual(supply) - - return sdk.FormatInvariant(types.ModuleName, "total supply", - fmt.Sprintf( - "\tsum of accounts coins: %v\n"+ - "\tsupply.Total: %v\n", - expectedTotal, supply)), broken - } -} diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 109add01a..f5174c2db 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -3,408 +3,103 @@ package keeper import ( "fmt" - "github.com/ODIN-PROTOCOL/odin-core/app/helpers/conv" + "github.com/cometbft/cometbft/libs/log" - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var _ Keeper = (*BaseKeeper)(nil) - -// Keeper defines a module interface that facilitates the transfer of coins -// between accounts. -type Keeper interface { - SendKeeper - WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper - - InitGenesis(sdk.Context, *types.GenesisState) - ExportGenesis(sdk.Context) *types.GenesisState - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - HasSupply(ctx sdk.Context, denom string) bool - GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) - IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) - GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool) - HasDenomMetaData(ctx sdk.Context, denom string) bool - SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metadata) - GetAllDenomMetaData(ctx sdk.Context) []types.Metadata - IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool) - - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - DelegateCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - - DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error - UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error - - types.QueryServer -} - -// BaseKeeper manages transfers between accounts. It implements the Keeper interface. -type BaseKeeper struct { - BaseSendKeeper - - ak types.AccountKeeper - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - mintCoinsRestrictionFn MintingRestrictionFn -} - -type MintingRestrictionFn func(ctx sdk.Context, coins sdk.Coins) error - -// GetPaginatedTotalSupply queries for the supply, ignoring 0 coins, with a given pagination -func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) { - store := ctx.KVStore(k.storeKey) - supplyStore := prefix.NewStore(store, types.SupplyKey) - - supply := sdk.NewCoins() - - pageRes, err := query.Paginate(supplyStore, pagination, func(key, value []byte) error { - var amount math.Int - err := amount.Unmarshal(value) - if err != nil { - return fmt.Errorf("unable to convert amount string to Int %v", err) - } - - // `Add` omits the 0 coins addition to the `supply`. - supply = supply.Add(sdk.NewCoin(string(key), amount)) - return nil - }) - if err != nil { - return nil, nil, err - } - - return supply, pageRes, nil -} - -// NewBaseKeeper returns a new BaseKeeper object with a given codec, dedicated -// store key, an AccountKeeper implementation, and a parameter Subspace used to -// store and fetch module parameters. The BaseKeeper also accepts a -// blocklist map. This blocklist describes the set of addresses that are not allowed -// to receive funds through direct and explicit actions, for example, by using a MsgSend or -// by using a SendCoinsFromModuleToAccount execution. -func NewBaseKeeper( - cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, - ak types.AccountKeeper, - blockedAddrs map[string]bool, - authority string, -) BaseKeeper { - if _, err := sdk.AccAddressFromBech32(authority); err != nil { - panic(fmt.Errorf("invalid bank authority address: %w", err)) - } + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - return BaseKeeper{ - BaseSendKeeper: NewBaseSendKeeper(cdc, storeKey, ak, blockedAddrs, authority), - ak: ak, - cdc: cdc, - storeKey: storeKey, - mintCoinsRestrictionFn: func(ctx sdk.Context, coins sdk.Coins) error { return nil }, - } -} + "github.com/ODIN-PROTOCOL/odin-core/x/bank/types" +) -// WithMintCoinsRestriction restricts the bank Keeper used within a specific module to -// have restricted permissions on minting via function passed in parameter. -// Previous restriction functions can be nested as such: +// WrappedBankKeeper encapsulates the underlying bank keeper and overrides +// its BurnCoins function to send the coins to the community pool instead of +// just destroying them. // -// bankKeeper.WithMintCoinsRestriction(restriction1).WithMintCoinsRestriction(restriction2) -func (k BaseKeeper) WithMintCoinsRestriction(check MintingRestrictionFn) BaseKeeper { - oldRestrictionFn := k.mintCoinsRestrictionFn - k.mintCoinsRestrictionFn = func(ctx sdk.Context, coins sdk.Coins) error { - err := check(ctx, coins) - if err != nil { - return err - } - err = oldRestrictionFn(ctx, coins) - if err != nil { - return err - } - return nil - } - return k -} - -// DelegateCoins performs delegation by deducting amt coins from an account with -// address addr. For vesting accounts, delegations amounts are tracked for both -// vesting and vested coins. The coins are then transferred from the delegator -// address to a ModuleAccount address. If any of the delegation amounts are negative, -// an error is returned. -func (k BaseKeeper) DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error { - moduleAcc := k.ak.GetAccount(ctx, moduleAccAddr) - if moduleAcc == nil { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr) - } - - if !amt.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String()) - } - - balances := sdk.NewCoins() - - for _, coin := range amt { - balance := k.GetBalance(ctx, delegatorAddr, coin.GetDenom()) - if balance.IsLT(coin) { - return sdkerrors.Wrapf( - sdkerrors.ErrInsufficientFunds, "failed to delegate; %s is smaller than %s", balance, amt, - ) - } - - balances = balances.Add(balance) - err := k.setBalance(ctx, delegatorAddr, balance.Sub(coin)) - if err != nil { - return err - } - } - - if err := k.trackDelegation(ctx, delegatorAddr, balances, amt); err != nil { - return sdkerrors.Wrap(err, "failed to track delegation") - } - // emit coin spent event - ctx.EventManager().EmitEvent( - types.NewCoinSpentEvent(delegatorAddr, amt), - ) - - err := k.addCoins(ctx, moduleAccAddr, amt) - if err != nil { - return err - } - - return nil -} - -// UndelegateCoins performs undelegation by crediting amt coins to an account with -// address addr. For vesting accounts, undelegation amounts are tracked for both -// vesting and vested coins. The coins are then transferred from a ModuleAccount -// address to the delegator address. If any of the undelegation amounts are -// negative, an error is returned. -func (k BaseKeeper) UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error { - moduleAcc := k.ak.GetAccount(ctx, moduleAccAddr) - if moduleAcc == nil { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr) - } - - if !amt.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String()) - } - - err := k.subUnlockedCoins(ctx, moduleAccAddr, amt) - if err != nil { - return err - } - - if err := k.trackUndelegation(ctx, delegatorAddr, amt); err != nil { - return sdkerrors.Wrap(err, "failed to track undelegation") - } - - err = k.addCoins(ctx, delegatorAddr, amt) - if err != nil { - return err - } - - return nil -} - -// GetSupply retrieves the Supply from store -func (k BaseKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { - store := ctx.KVStore(k.storeKey) - supplyStore := prefix.NewStore(store, types.SupplyKey) - - bz := supplyStore.Get(conv.UnsafeStrToBytes(denom)) - if bz == nil { - return sdk.Coin{ - Denom: denom, - Amount: sdk.NewInt(0), - } - } - - var amount math.Int - err := amount.Unmarshal(bz) - if err != nil { - panic(fmt.Errorf("unable to unmarshal supply value %v", err)) - } - - return sdk.Coin{ - Denom: denom, - Amount: amount, - } -} - -// HasSupply checks if the supply coin exists in store. -func (k BaseKeeper) HasSupply(ctx sdk.Context, denom string) bool { - store := ctx.KVStore(k.storeKey) - supplyStore := prefix.NewStore(store, types.SupplyKey) - return supplyStore.Has(conv.UnsafeStrToBytes(denom)) -} - -// GetDenomMetaData retrieves the denomination metadata. returns the metadata and true if the denom exists, -// false otherwise. -func (k BaseKeeper) GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool) { - store := ctx.KVStore(k.storeKey) - store = prefix.NewStore(store, types.DenomMetadataPrefix) - - bz := store.Get(conv.UnsafeStrToBytes(denom)) - if bz == nil { - return types.Metadata{}, false - } - - var metadata types.Metadata - k.cdc.MustUnmarshal(bz, &metadata) +// Note that distrKeeper keeps the reference to the distr module keeper. +// Due to the circular dependency between bank-distr, distrKeeper +// cannot be initialized when the struct is created. Rather, SetDistrKeeper and SetAccountKeeper +// are expected to be called to set `distrKeeper` and `accountKeeper` respectively. +type WrappedBankKeeper struct { + bankkeeper.Keeper - return metadata, true + distrKeeper types.DistributionKeeper + mintKeeper types.MintKeeper + accountKeeper types.AccountKeeper } -// HasDenomMetaData checks if the denomination metadata exists in store. -func (k BaseKeeper) HasDenomMetaData(ctx sdk.Context, denom string) bool { - store := ctx.KVStore(k.storeKey) - store = prefix.NewStore(store, types.DenomMetadataPrefix) - return store.Has(conv.UnsafeStrToBytes(denom)) -} - -// GetAllDenomMetaData retrieves all denominations metadata -func (k BaseKeeper) GetAllDenomMetaData(ctx sdk.Context) []types.Metadata { - denomMetaData := make([]types.Metadata, 0) - k.IterateAllDenomMetaData(ctx, func(metadata types.Metadata) bool { - denomMetaData = append(denomMetaData, metadata) - return false - }) - - return denomMetaData +// NewWrappedBankKeeperBurnToCommunityPool creates a new instance of WrappedBankKeeper +// with its distrKeeper and accountKeeper members set to nil. +func NewWrappedBankKeeperBurnToCommunityPool(bk bankkeeper.Keeper, acc types.AccountKeeper) WrappedBankKeeper { + return WrappedBankKeeper{bk, nil, nil, acc} } -// IterateAllDenomMetaData iterates over all the denominations metadata and -// provides the metadata to a callback. If true is returned from the -// callback, iteration is halted. -func (k BaseKeeper) IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool) { - store := ctx.KVStore(k.storeKey) - denomMetaDataStore := prefix.NewStore(store, types.DenomMetadataPrefix) - - iterator := denomMetaDataStore.Iterator(nil, nil) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) - - for ; iterator.Valid(); iterator.Next() { - var metadata types.Metadata - k.cdc.MustUnmarshal(iterator.Value(), &metadata) - - if cb(metadata) { - break - } - } +// SetDistrKeeper sets distr module keeper for this WrappedBankKeeper instance. +func (k *WrappedBankKeeper) SetDistrKeeper(dk types.DistributionKeeper) { + k.distrKeeper = dk } -// SetDenomMetaData sets the denominations metadata -func (k BaseKeeper) SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metadata) { - store := ctx.KVStore(k.storeKey) - denomMetaDataStore := prefix.NewStore(store, types.DenomMetadataPrefix) - - m := k.cdc.MustMarshal(&denomMetaData) - denomMetaDataStore.Set([]byte(denomMetaData.Base), m) +func (k *WrappedBankKeeper) SetMintKeeper(mintKeeper types.MintKeeper) { + k.mintKeeper = mintKeeper } -// SendCoinsFromModuleToAccount transfers coins from a ModuleAccount to an AccAddress. -// It will panic if the module account does not exist. An error is returned if -// the recipient address is black-listed or if sending the tokens fails. -func (k BaseKeeper) SendCoinsFromModuleToAccount( - ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, -) error { - senderAddr := k.ak.GetModuleAddress(senderModule) - if senderAddr == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) - } - - if k.BlockedAddr(recipientAddr) { - return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", recipientAddr) - } - - return k.SendCoins(ctx, senderAddr, recipientAddr, amt) +// Logger returns a module-specific logger. +func (k WrappedBankKeeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprint("x/wrappedbank")) } -// SendCoinsFromModuleToModule transfers coins from a ModuleAccount to another. -// It will panic if either module account does not exist. -func (k BaseKeeper) SendCoinsFromModuleToModule( - ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins, -) error { - senderAddr := k.ak.GetModuleAddress(senderModule) - if senderAddr == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) - } - - recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule) - if recipientAcc == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) +// BurnCoins moves the specified amount of coins from the given module name to +// the community pool. The total bank of the coins will not change. +func (k WrappedBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { + // If distrKeeper is not set OR we want to burn coins in distr itself, we will + // just use the original BurnCoins function. + if k.distrKeeper == nil || moduleName == distrtypes.ModuleName { + return k.Keeper.BurnCoins(ctx, moduleName, amt) } - return k.SendCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt) -} - -// SendCoinsFromAccountToModule transfers coins from an AccAddress to a ModuleAccount. -// It will panic if the module account does not exist. -func (k BaseKeeper) SendCoinsFromAccountToModule( - ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins, -) error { - recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule) - if recipientAcc == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) + // Create the account if it doesn't yet exist. + acc := k.accountKeeper.GetModuleAccount(ctx, moduleName) + if acc == nil { + panic(sdkerrors.Wrapf( + sdkerrors.ErrUnknownAddress, + "module account %s does not exist", moduleName, + )) } - return k.SendCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt) -} - -// DelegateCoinsFromAccountToModule delegates coins and transfers them from a -// delegator account to a module account. It will panic if the module account -// does not exist or is unauthorized. -func (k BaseKeeper) DelegateCoinsFromAccountToModule( - ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins, -) error { - recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule) - if recipientAcc == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) + if !acc.HasPermission(authtypes.Burner) { + panic(sdkerrors.Wrapf( + sdkerrors.ErrUnauthorized, + "module account %s does not have permissions to burn tokens", + moduleName, + )) } - if !recipientAcc.HasPermission(authtypes.Staking) { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to receive delegated coins", recipientModule)) - } + // Instead of burning coins, we send them to the community pool. + k.SendCoinsFromModuleToModule(ctx, moduleName, distrtypes.ModuleName, amt) + feePool := k.distrKeeper.GetFeePool(ctx) + feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) + k.distrKeeper.SetFeePool(ctx, feePool) - return k.DelegateCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt) + logger := k.Logger(ctx) + logger.Info(fmt.Sprintf( + "sent %s from %s module account to community pool", amt.String(), moduleName, + )) + return nil } -// UndelegateCoinsFromModuleToAccount undelegates the unbonding coins and transfers -// them from a module account to the delegator account. It will panic if the -// module account does not exist or is unauthorized. -func (k BaseKeeper) UndelegateCoinsFromModuleToAccount( - ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, -) error { - acc := k.ak.GetModuleAccount(ctx, senderModule) - if acc == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) - } - - if !acc.HasPermission(authtypes.Staking) { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to undelegate coins", senderModule)) +// MintCoins does not create any new coins, just gets them from the community pull +func (k WrappedBankKeeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error { + if k.distrKeeper == nil || moduleName == distrtypes.ModuleName { + return k.Keeper.MintCoins(ctx, moduleName, amt) } - return k.UndelegateCoins(ctx, acc.GetAddress(), recipientAddr, amt) -} - -// MintCoins creates new coins from thin air and adds it to the module account. -// It will panic if the module account does not exist or is unauthorized. -func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { - err := k.mintCoinsRestrictionFn(ctx, amounts) - if err != nil { - ctx.Logger().Error(fmt.Sprintf("Module %q attempted to mint coins %s it doesn't have permission for, error %v", moduleName, amounts, err)) - return err + vanillaMinting := k.mintKeeper.GetParams(ctx).MintAir + if vanillaMinting { + return k.Keeper.MintCoins(ctx, moduleName, amt) } - acc := k.ak.GetModuleAccount(ctx, moduleName) + acc := k.accountKeeper.GetModuleAccount(ctx, moduleName) if acc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleName)) } @@ -413,138 +108,14 @@ func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Co panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to mint tokens", moduleName)) } - err = k.addCoins(ctx, acc.GetAddress(), amounts) - if err != nil { - return err - } - - for _, amount := range amounts { - supply := k.GetSupply(ctx, amount.GetDenom()) - supply = supply.Add(amount) - k.setSupply(ctx, supply) - } - logger := k.Logger(ctx) - logger.Info("minted coins from module account", "amount", amounts.String(), "from", moduleName) - - // emit mint event - ctx.EventManager().EmitEvent( - types.NewCoinMintEvent(acc.GetAddress(), amounts), - ) - - return nil -} - -// BurnCoins burns coins deletes coins from the balance of the module account. -// It will panic if the module account does not exist or is unauthorized. -func (k BaseKeeper) BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { - acc := k.ak.GetModuleAccount(ctx, moduleName) - if acc == nil { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleName)) - } - - if !acc.HasPermission(authtypes.Burner) { - panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to burn tokens", moduleName)) - } - - err := k.subUnlockedCoins(ctx, acc.GetAddress(), amounts) + err := k.SendCoinsFromModuleToModule(ctx, distrtypes.ModuleName, moduleName, amt) if err != nil { + err = sdkerrors.Wrap(err, fmt.Sprintf("failed to mint %s from %s module account", amt.String(), moduleName)) + logger.Error(err.Error()) return err } - - for _, amount := range amounts { - supply := k.GetSupply(ctx, amount.GetDenom()) - supply = supply.Sub(amount) - k.setSupply(ctx, supply) - } - - logger := k.Logger(ctx) - logger.Info("burned tokens from module account", "amount", amounts.String(), "from", moduleName) - - // emit burn event - ctx.EventManager().EmitEvent( - types.NewCoinBurnEvent(acc.GetAddress(), amounts), - ) - - return nil -} - -// setSupply sets the supply for the given coin -func (k BaseKeeper) setSupply(ctx sdk.Context, coin sdk.Coin) { - intBytes, err := coin.Amount.Marshal() - if err != nil { - panic(fmt.Errorf("unable to marshal amount value %v", err)) - } - - store := ctx.KVStore(k.storeKey) - supplyStore := prefix.NewStore(store, types.SupplyKey) - - // Bank invariants and IBC requires to remove zero coins. - if coin.IsZero() { - supplyStore.Delete(conv.UnsafeStrToBytes(coin.GetDenom())) - } else { - supplyStore.Set([]byte(coin.GetDenom()), intBytes) - } -} - -// trackDelegation tracks the delegation of the given account if it is a vesting account -func (k BaseKeeper) trackDelegation(ctx sdk.Context, addr sdk.AccAddress, balance, amt sdk.Coins) error { - acc := k.ak.GetAccount(ctx, addr) - if acc == nil { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) - } - - vacc, ok := acc.(types.VestingAccount) - if ok { - // TODO: return error on account.TrackDelegation - vacc.TrackDelegation(ctx.BlockHeader().Time, balance, amt) - k.ak.SetAccount(ctx, acc) - } - - return nil -} - -// trackUndelegation trakcs undelegation of the given account if it is a vesting account -func (k BaseKeeper) trackUndelegation(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error { - acc := k.ak.GetAccount(ctx, addr) - if acc == nil { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) - } - - vacc, ok := acc.(types.VestingAccount) - if ok { - // TODO: return error on account.TrackUndelegation - vacc.TrackUndelegation(amt) - k.ak.SetAccount(ctx, acc) - } + logger.Info(fmt.Sprintf("minted %s from %s module account", amt.String(), moduleName)) return nil } - -// IterateTotalSupply iterates over the total supply calling the given cb (callback) function -// with the balance of each coin. -// The iteration stops if the callback returns true. -func (k BaseViewKeeper) IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) { - store := ctx.KVStore(k.storeKey) - supplyStore := prefix.NewStore(store, types.SupplyKey) - - iterator := supplyStore.Iterator(nil, nil) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) - - for ; iterator.Valid(); iterator.Next() { - var amount math.Int - err := amount.Unmarshal(iterator.Value()) - if err != nil { - panic(fmt.Errorf("unable to unmarshal supply value %v", err)) - } - - balance := sdk.Coin{ - Denom: string(iterator.Key()), - Amount: amount, - } - - if cb(balance) { - break - } - } -} diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go deleted file mode 100644 index 9cb428322..000000000 --- a/x/bank/keeper/keeper_test.go +++ /dev/null @@ -1,1777 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - "testing" - "time" - - "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -const ( - fooDenom = "foo" - barDenom = "bar" - initialPower = int64(100) - holder = "holder" - multiPerm = "multiple permissions account" - randomPerm = "random permission" -) - -var ( - holderAcc = authtypes.NewEmptyModuleAccount(holder) - burnerAcc = authtypes.NewEmptyModuleAccount(authtypes.Burner, authtypes.Burner) - minterAcc = authtypes.NewEmptyModuleAccount(authtypes.Minter, authtypes.Minter) - mintAcc = authtypes.NewEmptyModuleAccount(minttypes.ModuleName, authtypes.Minter) - multiPermAcc = authtypes.NewEmptyModuleAccount(multiPerm, authtypes.Burner, authtypes.Minter, authtypes.Staking) - - baseAcc = authtypes.NewBaseAccountWithAddress(sdk.AccAddress([]byte("baseAcc"))) - - accAddrs = []sdk.AccAddress{ - sdk.AccAddress([]byte("addr1_______________")), - sdk.AccAddress([]byte("addr2_______________")), - sdk.AccAddress([]byte("addr3_______________")), - sdk.AccAddress([]byte("addr4_______________")), - sdk.AccAddress([]byte("addr5_______________")), - } - - // The default power validators are initialized to have within tests - initTokens = sdk.TokensFromConsensusPower(initialPower, sdk.DefaultPowerReduction) - initCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)) -) - -func newFooCoin(amt int64) sdk.Coin { - return sdk.NewInt64Coin(fooDenom, amt) -} - -func newBarCoin(amt int64) sdk.Coin { - return sdk.NewInt64Coin(barDenom, amt) -} - -type KeeperTestSuite struct { - suite.Suite - - ctx sdk.Context - bankKeeper keeper.BaseKeeper - authKeeper *banktestutil.MockAccountKeeper - - queryClient banktypes.QueryClient - msgServer banktypes.MsgServer - - encCfg moduletestutil.TestEncodingConfig -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -func (suite *KeeperTestSuite) SetupTest() { - key := sdk.NewKVStoreKey(banktypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()}) - encCfg := moduletestutil.MakeTestEncodingConfig() - - // gomock initializations - ctrl := gomock.NewController(suite.T()) - authKeeper := banktestutil.NewMockAccountKeeper(ctrl) - - suite.ctx = ctx - suite.authKeeper = authKeeper - suite.bankKeeper = keeper.NewBaseKeeper( - encCfg.Codec, - key, - suite.authKeeper, - map[string]bool{accAddrs[4].String(): true}, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - banktypes.RegisterInterfaces(encCfg.InterfaceRegistry) - - queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) - banktypes.RegisterQueryServer(queryHelper, suite.bankKeeper) - queryClient := banktypes.NewQueryClient(queryHelper) - - suite.queryClient = queryClient - suite.msgServer = keeper.NewMsgServerImpl(suite.bankKeeper) - suite.encCfg = encCfg -} - -func (suite *KeeperTestSuite) mockQueryClient(ctx sdk.Context) banktypes.QueryClient { - queryHelper := baseapp.NewQueryServerTestHelper(ctx, suite.encCfg.InterfaceRegistry) - banktypes.RegisterQueryServer(queryHelper, suite.bankKeeper) - return banktypes.NewQueryClient(queryHelper) -} - -func (suite *KeeperTestSuite) mockMintCoins(moduleAcc *authtypes.ModuleAccount) { - suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, moduleAcc.Name).Return(moduleAcc) -} - -func (suite *KeeperTestSuite) mockSendCoinsFromModuleToAccount(moduleAcc *authtypes.ModuleAccount, accAddr sdk.AccAddress) { - suite.authKeeper.EXPECT().GetModuleAddress(moduleAcc.Name).Return(moduleAcc.GetAddress()) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, moduleAcc.GetAddress()).Return(moduleAcc) - suite.authKeeper.EXPECT().HasAccount(suite.ctx, accAddr).Return(true) -} - -func (suite *KeeperTestSuite) mockBurnCoins(moduleAcc *authtypes.ModuleAccount) { - suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, moduleAcc.Name).Return(moduleAcc) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, moduleAcc.GetAddress()).Return(moduleAcc) -} - -func (suite *KeeperTestSuite) mockSendCoinsFromModuleToModule(sender *authtypes.ModuleAccount, receiver *authtypes.ModuleAccount) { - suite.authKeeper.EXPECT().GetModuleAddress(sender.Name).Return(sender.GetAddress()) - suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, receiver.Name).Return(receiver) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, sender.GetAddress()).Return(sender) - suite.authKeeper.EXPECT().HasAccount(suite.ctx, receiver.GetAddress()).Return(true) -} - -func (suite *KeeperTestSuite) mockSendCoinsFromAccountToModule(acc *authtypes.BaseAccount, moduleAcc *authtypes.ModuleAccount) { - suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, moduleAcc.Name).Return(moduleAcc) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, acc.GetAddress()).Return(acc) - suite.authKeeper.EXPECT().HasAccount(suite.ctx, moduleAcc.GetAddress()).Return(true) -} - -func (suite *KeeperTestSuite) mockSendCoins(ctx sdk.Context, sender authtypes.AccountI, receiver sdk.AccAddress) { - suite.authKeeper.EXPECT().GetAccount(ctx, sender.GetAddress()).Return(sender) - suite.authKeeper.EXPECT().HasAccount(ctx, receiver).Return(true) -} - -func (suite *KeeperTestSuite) mockFundAccount(receiver sdk.AccAddress) { - suite.mockMintCoins(mintAcc) - suite.mockSendCoinsFromModuleToAccount(mintAcc, receiver) -} - -func (suite *KeeperTestSuite) mockInputOutputCoins(inputs []authtypes.AccountI, outputs []sdk.AccAddress) { - for _, input := range inputs { - suite.authKeeper.EXPECT().GetAccount(suite.ctx, input.GetAddress()).Return(input) - } - for _, output := range outputs { - suite.authKeeper.EXPECT().HasAccount(suite.ctx, output).Return(true) - } -} - -func (suite *KeeperTestSuite) mockValidateBalance(acc authtypes.AccountI) { - suite.authKeeper.EXPECT().GetAccount(suite.ctx, acc.GetAddress()).Return(acc) -} - -func (suite *KeeperTestSuite) mockSpendableCoins(ctx sdk.Context, acc authtypes.AccountI) { - suite.authKeeper.EXPECT().GetAccount(ctx, acc.GetAddress()).Return(acc) -} - -func (suite *KeeperTestSuite) mockDelegateCoins(ctx sdk.Context, acc authtypes.AccountI, mAcc authtypes.AccountI) { - vacc, ok := acc.(banktypes.VestingAccount) - if ok { - suite.authKeeper.EXPECT().SetAccount(ctx, vacc) - } - suite.authKeeper.EXPECT().GetAccount(ctx, acc.GetAddress()).Return(acc) - suite.authKeeper.EXPECT().GetAccount(ctx, mAcc.GetAddress()).Return(mAcc) -} - -func (suite *KeeperTestSuite) mockUnDelegateCoins(ctx sdk.Context, acc authtypes.AccountI, mAcc authtypes.AccountI) { - vacc, ok := acc.(banktypes.VestingAccount) - if ok { - suite.authKeeper.EXPECT().SetAccount(ctx, vacc) - } - suite.authKeeper.EXPECT().GetAccount(ctx, acc.GetAddress()).Return(acc) - suite.authKeeper.EXPECT().GetAccount(ctx, mAcc.GetAddress()).Return(mAcc) - suite.authKeeper.EXPECT().GetAccount(ctx, mAcc.GetAddress()).Return(mAcc) -} - -func (suite *KeeperTestSuite) TestGetAuthority() { - NewKeeperWithAuthority := func(authority string) keeper.BaseKeeper { - return keeper.NewBaseKeeper( - moduletestutil.MakeTestEncodingConfig().Codec, - sdk.NewKVStoreKey(banktypes.StoreKey), - nil, - nil, - authority, - ) - } - - tests := map[string]string{ - "some random account": "cosmos139f7kncmglres2nf3h4hc4tade85ekfr8sulz5", - "gov module account": authtypes.NewModuleAddress(govtypes.ModuleName).String(), - "another module account": authtypes.NewModuleAddress(minttypes.ModuleName).String(), - } - - for name, expected := range tests { - suite.T().Run(name, func(t *testing.T) { - kpr := NewKeeperWithAuthority(expected) - actual := kpr.GetAuthority() - suite.Require().Equal(expected, actual) - }) - } -} - -func (suite *KeeperTestSuite) TestSupply() { - ctx := suite.ctx - require := suite.Require() - keeper := suite.bankKeeper - - // add module accounts to supply keeper - genesisSupply, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - initialPower := int64(100) - initTokens := sdk.TokensFromConsensusPower(initialPower, sdk.DefaultPowerReduction) - initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)) - - // set burnerAcc balance - suite.mockMintCoins(minterAcc) - require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) - - suite.mockSendCoinsFromModuleToAccount(minterAcc, burnerAcc.GetAddress()) - require.NoError(keeper.SendCoinsFromModuleToAccount(ctx, authtypes.Minter, burnerAcc.GetAddress(), initCoins)) - - total, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - expTotalSupply := initCoins.Add(genesisSupply...) - require.Equal(expTotalSupply, total) - - // burning all supplied tokens - suite.mockBurnCoins(burnerAcc) - require.NoError(keeper.BurnCoins(ctx, authtypes.Burner, initCoins)) - - total, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - require.Equal(total, genesisSupply) -} - -func (suite *KeeperTestSuite) TestSendCoinsFromModuleToAccount_Blocklist() { - ctx := suite.ctx - require := suite.Require() - keeper := suite.bankKeeper - - suite.mockMintCoins(mintAcc) - require.NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins)) - - suite.authKeeper.EXPECT().GetModuleAddress(mintAcc.Name).Return(mintAcc.GetAddress()) - require.Error(keeper.SendCoinsFromModuleToAccount( - ctx, minttypes.ModuleName, accAddrs[4], initCoins, - )) -} - -func (suite *KeeperTestSuite) TestSupply_SendCoins() { - ctx := suite.ctx - require := suite.Require() - authKeeper, keeper := suite.authKeeper, suite.bankKeeper - - // set initial balances - suite.mockMintCoins(mintAcc) - require.NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins)) - - suite.mockSendCoinsFromModuleToAccount(mintAcc, holderAcc.GetAddress()) - require.NoError(keeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, holderAcc.GetAddress(), initCoins)) - - authKeeper.EXPECT().GetModuleAddress("").Return(nil) - require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) // nolint:errcheck - }) - - authKeeper.EXPECT().GetModuleAddress(burnerAcc.Name).Return(burnerAcc.GetAddress()) - authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) // nolint:errcheck - }) - - authKeeper.EXPECT().GetModuleAddress("").Return(nil) - require.Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) // nolint:errcheck - }) - - authKeeper.EXPECT().GetModuleAddress(holderAcc.Name).Return(holderAcc.GetAddress()) - authKeeper.EXPECT().GetAccount(suite.ctx, holderAcc.GetAddress()).Return(holderAcc) - require.Error( - keeper.SendCoinsFromModuleToAccount(ctx, holderAcc.GetName(), baseAcc.GetAddress(), initCoins.Add(initCoins...)), - ) - - suite.mockSendCoinsFromModuleToModule(holderAcc, burnerAcc) - require.NoError( - keeper.SendCoinsFromModuleToModule(ctx, holderAcc.GetName(), authtypes.Burner, initCoins), - ) - - require.Equal(sdk.NewCoins(), keeper.GetAllBalances(ctx, holderAcc.GetAddress())) - require.Equal(initCoins, keeper.GetAllBalances(ctx, burnerAcc.GetAddress())) - - suite.mockSendCoinsFromModuleToAccount(burnerAcc, baseAcc.GetAddress()) - require.NoError( - keeper.SendCoinsFromModuleToAccount(ctx, authtypes.Burner, baseAcc.GetAddress(), initCoins), - ) - require.Equal(sdk.NewCoins(), keeper.GetAllBalances(ctx, burnerAcc.GetAddress())) - require.Equal(initCoins, keeper.GetAllBalances(ctx, baseAcc.GetAddress())) - - suite.mockSendCoinsFromAccountToModule(baseAcc, burnerAcc) - require.NoError(keeper.SendCoinsFromAccountToModule(ctx, baseAcc.GetAddress(), authtypes.Burner, initCoins)) - require.Equal(sdk.NewCoins(), keeper.GetAllBalances(ctx, baseAcc.GetAddress())) - require.Equal(initCoins, keeper.GetAllBalances(ctx, burnerAcc.GetAddress())) -} - -func (suite *KeeperTestSuite) TestSupply_MintCoins() { - ctx := suite.ctx - require := suite.Require() - authKeeper, keeper := suite.authKeeper, suite.bankKeeper - - initialSupply, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, "", initCoins) }, "no module account") // nolint:errcheck - - suite.mockMintCoins(burnerAcc) - require.Panics(func() { _ = keeper.MintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") // nolint:errcheck - - suite.mockMintCoins(minterAcc) - require.Error(keeper.MintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: sdk.NewInt(-10)}}), "insufficient coins") - - authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, randomPerm, initCoins) }) // nolint:errcheck - - suite.mockMintCoins(minterAcc) - require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) - - require.Equal(initCoins, keeper.GetAllBalances(ctx, minterAcc.GetAddress())) - totalSupply, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - require.Equal(initialSupply.Add(initCoins...), totalSupply) - - // test same functionality on module account with multiple permissions - initialSupply, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - suite.mockMintCoins(multiPermAcc) - require.NoError(keeper.MintCoins(ctx, multiPermAcc.GetName(), initCoins)) - - totalSupply, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - require.Equal(initCoins, keeper.GetAllBalances(ctx, multiPermAcc.GetAddress())) - require.Equal(initialSupply.Add(initCoins...), totalSupply) -} - -func (suite *KeeperTestSuite) TestSupply_BurnCoins() { - ctx := suite.ctx - require := suite.Require() - authKeeper, keeper := suite.authKeeper, suite.bankKeeper - - // set burnerAcc balance - suite.mockMintCoins(minterAcc) - require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) - - suite.mockSendCoinsFromModuleToAccount(minterAcc, burnerAcc.GetAddress()) - require.NoError(keeper.SendCoinsFromModuleToAccount(ctx, authtypes.Minter, burnerAcc.GetAddress(), initCoins)) - - // inflate supply - suite.mockMintCoins(minterAcc) - require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) - - supplyAfterInflation, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, "", initCoins) }, "no module account") // nolint:errcheck - - authKeeper.EXPECT().GetModuleAccount(ctx, minterAcc.Name).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") // nolint:errcheck - - authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") // nolint:errcheck - - suite.mockBurnCoins(burnerAcc) - require.Error(keeper.BurnCoins(ctx, authtypes.Burner, supplyAfterInflation), "insufficient coins") - - suite.mockBurnCoins(burnerAcc) - require.NoError(keeper.BurnCoins(ctx, authtypes.Burner, initCoins)) - - supplyAfterBurn, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - require.Equal(sdk.NewCoins(), keeper.GetAllBalances(ctx, burnerAcc.GetAddress())) - require.Equal(supplyAfterInflation.Sub(initCoins...), supplyAfterBurn) - - // test same functionality on module account with multiple permissions - suite.mockMintCoins(minterAcc) - require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) - - supplyAfterInflation, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - - suite.mockSendCoins(ctx, minterAcc, multiPermAcc.GetAddress()) - require.NoError(keeper.SendCoins(ctx, minterAcc.GetAddress(), multiPermAcc.GetAddress(), initCoins)) - - suite.mockBurnCoins(multiPermAcc) - require.NoError(keeper.BurnCoins(ctx, multiPermAcc.GetName(), initCoins)) - - supplyAfterBurn, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) - require.NoError(err) - require.Equal(sdk.NewCoins(), keeper.GetAllBalances(ctx, multiPermAcc.GetAddress())) - require.Equal(supplyAfterInflation.Sub(initCoins...), supplyAfterBurn) -} - -func (suite *KeeperTestSuite) TestSendCoinsNewAccount() { - ctx := suite.ctx - require := suite.Require() - balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - require.Equal(balances, acc1Balances) - - suite.bankKeeper.GetAllBalances(ctx, accAddrs[1]) - require.Empty(suite.bankKeeper.GetAllBalances(ctx, accAddrs[1])) - - sendAmt := sdk.NewCoins(newFooCoin(50), newBarCoin(50)) - suite.mockSendCoins(ctx, acc0, accAddrs[1]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendAmt)) - - acc2Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[1]) - acc1Balances = suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - require.Equal(sendAmt, acc2Balances) - updatedAcc1Bal := balances.Sub(sendAmt...) - require.Len(acc1Balances, len(updatedAcc1Bal)) - require.Equal(acc1Balances, updatedAcc1Bal) -} - -func (suite *KeeperTestSuite) TestInputOutputNewAccount() { - ctx := suite.ctx - require := suite.Require() - - balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - - acc1Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - require.Equal(balances, acc1Balances) - - require.Empty(suite.bankKeeper.GetAllBalances(ctx, accAddrs[1])) - - suite.mockInputOutputCoins([]authtypes.AccountI{authtypes.NewBaseAccountWithAddress(accAddrs[0])}, []sdk.AccAddress{accAddrs[1]}) - inputs := []banktypes.Input{ - {Address: accAddrs[0].String(), Coins: sdk.NewCoins(newFooCoin(30), newBarCoin(10))}, - } - outputs := []banktypes.Output{ - {Address: accAddrs[1].String(), Coins: sdk.NewCoins(newFooCoin(30), newBarCoin(10))}, - } - - require.NoError(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - expected := sdk.NewCoins(newFooCoin(30), newBarCoin(10)) - acc2Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[1]) - require.Equal(expected, acc2Balances) -} - -func (suite *KeeperTestSuite) TestInputOutputCoins() { - ctx := suite.ctx - require := suite.Require() - balances := sdk.NewCoins(newFooCoin(90), newBarCoin(30)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - inputs := []banktypes.Input{ - {Address: accAddrs[0].String(), Coins: sdk.NewCoins(newFooCoin(60), newBarCoin(20))}, - } - outputs := []banktypes.Output{ - {Address: accAddrs[1].String(), Coins: sdk.NewCoins(newFooCoin(30), newBarCoin(10))}, - {Address: accAddrs[2].String(), Coins: sdk.NewCoins(newFooCoin(30), newBarCoin(10))}, - } - - require.Error(suite.bankKeeper.InputOutputCoins(ctx, inputs, []banktypes.Output{})) - - suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(acc0) - require.Error(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - - insufficientInputs := []banktypes.Input{ - { - Address: accAddrs[0].String(), - Coins: sdk.NewCoins(newFooCoin(300), newBarCoin(100)), - }, - } - insufficientOutputs := []banktypes.Output{ - {Address: accAddrs[1].String(), Coins: sdk.NewCoins(newFooCoin(300), newBarCoin(100))}, - {Address: accAddrs[2].String(), Coins: sdk.NewCoins(newFooCoin(300), newBarCoin(100))}, - } - - require.Error(suite.bankKeeper.InputOutputCoins(ctx, insufficientInputs, insufficientOutputs)) - - suite.mockInputOutputCoins([]authtypes.AccountI{acc0}, accAddrs[1:3]) - require.NoError(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - acc1Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - expected := sdk.NewCoins(newFooCoin(30), newBarCoin(10)) - require.Equal(expected, acc1Balances) - - acc2Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[1]) - require.Equal(expected, acc2Balances) - - acc3Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[2]) - require.Equal(expected, acc3Balances) -} - -func (suite *KeeperTestSuite) TestSendCoins() { - ctx := suite.ctx - require := suite.Require() - balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], balances)) - - sendAmt := sdk.NewCoins(newFooCoin(50), newBarCoin(25)) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(acc0) - require.Error(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendAmt)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - suite.mockSendCoins(ctx, acc0, accAddrs[1]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendAmt)) - - acc1Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - expected := sdk.NewCoins(newFooCoin(50), newBarCoin(25)) - require.Equal(expected, acc1Balances) - - acc2Balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[1]) - expected = sdk.NewCoins(newFooCoin(150), newBarCoin(75)) - require.Equal(expected, acc2Balances) - - // we sent all foo coins to acc2, so foo balance should be deleted for acc1 and bar should be still there - var coins []sdk.Coin - suite.bankKeeper.IterateAccountBalances(ctx, accAddrs[0], func(c sdk.Coin) (stop bool) { - coins = append(coins, c) - return true - }) - require.Len(coins, 1) - require.Equal(newBarCoin(25), coins[0], "expected only bar coins in the account balance, got: %v", coins) -} - -func (suite *KeeperTestSuite) TestSendCoins_Invalid_SendLockedCoins() { - balances := sdk.NewCoins(newFooCoin(50)) - - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, now.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[1]) - suite.Require().NoError(banktestutil.FundAccount(suite.bankKeeper, suite.ctx, accAddrs[1], balances)) - - suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(vacc) - suite.Require().Error(suite.bankKeeper.SendCoins(suite.ctx, accAddrs[0], accAddrs[1], sendCoins)) -} - -func (suite *KeeperTestSuite) TestValidateBalance() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(nil) - require.Error(suite.bankKeeper.ValidateBalance(ctx, accAddrs[0])) - - balances := sdk.NewCoins(newFooCoin(100)) - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - - suite.mockValidateBalance(acc0) - require.NoError(suite.bankKeeper.ValidateBalance(ctx, accAddrs[0])) - - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc := vesting.NewContinuousVestingAccount(acc1, balances.Add(balances...), now.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], balances)) - - suite.mockValidateBalance(vacc) - require.Error(suite.bankKeeper.ValidateBalance(ctx, accAddrs[1])) -} - -func (suite *KeeperTestSuite) TestSendEnabled() { - ctx := suite.ctx - require := suite.Require() - enabled := true - params := banktypes.DefaultParams() - require.Equal(enabled, params.DefaultSendEnabled) - - require.NoError(suite.bankKeeper.SetParams(ctx, params)) - - bondCoin := sdk.NewCoin(sdk.DefaultBondDenom, math.OneInt()) - fooCoin := sdk.NewCoin("foocoin", math.OneInt()) - barCoin := sdk.NewCoin("barcoin", math.OneInt()) - - // assert with default (all denom) send enabled both Bar and Bond Denom are enabled - require.Equal(enabled, suite.bankKeeper.IsSendEnabledCoin(ctx, barCoin)) - require.Equal(enabled, suite.bankKeeper.IsSendEnabledCoin(ctx, bondCoin)) - - // Both coins should be send enabled. - err := suite.bankKeeper.IsSendEnabledCoins(ctx, fooCoin, bondCoin) - require.NoError(err) - - // Set default send_enabled to !enabled, add a foodenom that overrides default as enabled - params.DefaultSendEnabled = !enabled - require.NoError(suite.bankKeeper.SetParams(ctx, params)) - suite.bankKeeper.SetSendEnabled(ctx, fooCoin.Denom, enabled) - - // Expect our specific override to be enabled, others to be !enabled. - require.Equal(enabled, suite.bankKeeper.IsSendEnabledCoin(ctx, fooCoin)) - require.Equal(!enabled, suite.bankKeeper.IsSendEnabledCoin(ctx, barCoin)) - require.Equal(!enabled, suite.bankKeeper.IsSendEnabledCoin(ctx, bondCoin)) - - // Foo coin should be send enabled. - err = suite.bankKeeper.IsSendEnabledCoins(ctx, fooCoin) - require.NoError(err) - - // Expect an error when one coin is not send enabled. - err = suite.bankKeeper.IsSendEnabledCoins(ctx, fooCoin, bondCoin) - require.Error(err) - - // Expect an error when all coins are not send enabled. - err = suite.bankKeeper.IsSendEnabledCoins(ctx, bondCoin, barCoin) - require.Error(err) -} - -func (suite *KeeperTestSuite) TestHasBalance() { - ctx := suite.ctx - require := suite.Require() - - balances := sdk.NewCoins(newFooCoin(100)) - require.False(suite.bankKeeper.HasBalance(ctx, accAddrs[0], newFooCoin(99))) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], balances)) - require.False(suite.bankKeeper.HasBalance(ctx, accAddrs[0], newFooCoin(101))) - require.True(suite.bankKeeper.HasBalance(ctx, accAddrs[0], newFooCoin(100))) - require.True(suite.bankKeeper.HasBalance(ctx, accAddrs[0], newFooCoin(1))) -} - -func (suite *KeeperTestSuite) TestMsgSendEvents() { - ctx := suite.ctx - require := suite.Require() - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - newCoins := sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50)) - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], newCoins)) - - suite.mockSendCoins(ctx, acc0, accAddrs[1]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], newCoins)) - event1 := sdk.Event{ - Type: banktypes.EventTypeTransfer, - Attributes: []abci.EventAttribute{}, - } - event1.Attributes = append( - event1.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeyRecipient, Value: accAddrs[1].String()}, - ) - event1.Attributes = append( - event1.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeySender, Value: accAddrs[0].String()}, - ) - event1.Attributes = append( - event1.Attributes, - abci.EventAttribute{Key: sdk.AttributeKeyAmount, Value: newCoins.String()}, - ) - - event2 := sdk.Event{ - Type: sdk.EventTypeMessage, - Attributes: []abci.EventAttribute{}, - } - event2.Attributes = append( - event2.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeySender, Value: accAddrs[0].String()}, - ) - - // events are shifted due to the funding account events - events := ctx.EventManager().ABCIEvents() - require.Equal(10, len(events)) - require.Equal(abci.Event(event1), events[8]) - require.Equal(abci.Event(event2), events[9]) -} - -func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { - ctx := suite.ctx - require := suite.Require() - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - - require.NoError(suite.bankKeeper.SetParams(ctx, banktypes.DefaultParams())) - - coins := sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50), sdk.NewInt64Coin(barDenom, 100)) - newCoins := sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50)) - newCoins2 := sdk.NewCoins(sdk.NewInt64Coin(barDenom, 100)) - inputs := []banktypes.Input{ - { - Address: accAddrs[0].String(), - Coins: coins, - }, - } - outputs := []banktypes.Output{ - {Address: accAddrs[2].String(), Coins: newCoins}, - {Address: accAddrs[3].String(), Coins: newCoins2}, - } - - suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(acc0) - require.Error(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - events := ctx.EventManager().ABCIEvents() - require.Equal(0, len(events)) - - // Set addr's coins but not accAddrs[1]'s coins - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50), sdk.NewInt64Coin(barDenom, 100)))) - - suite.mockInputOutputCoins([]authtypes.AccountI{acc0}, accAddrs[2:4]) - require.NoError(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - events = ctx.EventManager().ABCIEvents() - require.Equal(12, len(events)) // 12 events because account funding causes extra minting + coin_spent + coin_recv events - - event1 := sdk.Event{ - Type: sdk.EventTypeMessage, - Attributes: []abci.EventAttribute{}, - } - event1.Attributes = append( - event1.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeySender, Value: accAddrs[0].String()}, - ) - require.Equal(abci.Event(event1), events[7]) - - // Set addr's coins and accAddrs[1]'s coins - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50)))) - newCoins = sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(barDenom, 100)))) - newCoins2 = sdk.NewCoins(sdk.NewInt64Coin(barDenom, 100)) - - suite.mockInputOutputCoins([]authtypes.AccountI{acc0}, accAddrs[2:4]) - require.NoError(suite.bankKeeper.InputOutputCoins(ctx, inputs, outputs)) - - events = ctx.EventManager().ABCIEvents() - require.Equal(30, len(events)) // 27 due to account funding + coin_spent + coin_recv events - - event2 := sdk.Event{ - Type: banktypes.EventTypeTransfer, - Attributes: []abci.EventAttribute{}, - } - event2.Attributes = append( - event2.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeyRecipient, Value: accAddrs[2].String()}, - ) - event2.Attributes = append( - event2.Attributes, - abci.EventAttribute{Key: sdk.AttributeKeyAmount, Value: newCoins.String()}) - event3 := sdk.Event{ - Type: banktypes.EventTypeTransfer, - Attributes: []abci.EventAttribute{}, - } - event3.Attributes = append( - event3.Attributes, - abci.EventAttribute{Key: banktypes.AttributeKeyRecipient, Value: accAddrs[3].String()}, - ) - event3.Attributes = append( - event3.Attributes, - abci.EventAttribute{Key: sdk.AttributeKeyAmount, Value: newCoins2.String()}, - ) - // events are shifted due to the funding account events - require.Equal(abci.Event(event1), events[25]) - require.Equal(abci.Event(event2), events[27]) - require.Equal(abci.Event(event3), events[29]) -} - -func (suite *KeeperTestSuite) TestSpendableCoins() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - lockedCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], origCoins)) - - suite.mockSpendableCoins(ctx, acc1) - require.Equal(origCoins, suite.bankKeeper.SpendableCoins(ctx, accAddrs[1])) - - suite.mockSpendableCoins(ctx, acc1) - require.Equal(origCoins[0], suite.bankKeeper.SpendableCoin(ctx, accAddrs[1], "stake")) - - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) - suite.mockSpendableCoins(ctx, vacc) - require.Equal(origCoins.Sub(lockedCoins...), suite.bankKeeper.SpendableCoins(ctx, accAddrs[0])) - - suite.mockSpendableCoins(ctx, vacc) - require.Equal(origCoins.Sub(lockedCoins...)[0], suite.bankKeeper.SpendableCoin(ctx, accAddrs[0], "stake")) -} - -func (suite *KeeperTestSuite) TestVestingAccountSend() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, now.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - // require that no coins be sendable at the beginning of the vesting schedule - suite.authKeeper.EXPECT().GetAccount(ctx, accAddrs[0]).Return(vacc) - require.Error(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) - - // receive some coins - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], sendCoins)) - // require that all vested coins are spendable plus any received - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) - suite.mockSendCoins(ctx, vacc, accAddrs[1]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) - require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) -} - -func (suite *KeeperTestSuite) TestPeriodicVestingAccountSend() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - periods := vesting.Periods{ - vesting.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 50)}}, - vesting.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 25)}}, - vesting.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 25)}}, - } - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - vacc := vesting.NewPeriodicVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), periods) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - // require that no coins be sendable at the beginning of the vesting schedule - suite.authKeeper.EXPECT().GetAccount(ctx, accAddrs[0]).Return(vacc) - require.Error(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) - - // receive some coins - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], sendCoins)) - - // require that all vested coins are spendable plus any received - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) - suite.mockSendCoins(ctx, vacc, accAddrs[1]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) - require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) -} - -func (suite *KeeperTestSuite) TestVestingAccountReceive() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], origCoins)) - - // send some coins to the vesting account - suite.mockSendCoins(ctx, acc1, accAddrs[0]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[1], accAddrs[0], sendCoins)) - - // require the coins are spendable - balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - require.Equal(origCoins.Add(sendCoins...), balances) - require.Equal(balances.Sub(vacc.LockedCoins(now)...), sendCoins) - - // require coins are spendable plus any that have vested - require.Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))...), origCoins) -} - -func (suite *KeeperTestSuite) TestPeriodicVestingAccountReceive() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - periods := vesting.Periods{ - vesting.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 50)}}, - vesting.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 25)}}, - vesting.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 25)}}, - } - - vacc := vesting.NewPeriodicVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), periods) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], origCoins)) - - // send some coins to the vesting account - suite.mockSendCoins(ctx, acc1, accAddrs[0]) - require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[1], accAddrs[0], sendCoins)) - - // require the coins are spendable - balances := suite.bankKeeper.GetAllBalances(ctx, accAddrs[0]) - require.Equal(origCoins.Add(sendCoins...), balances) - require.Equal(balances.Sub(vacc.LockedCoins(now)...), sendCoins) - - // require coins are spendable plus any that have vested - require.Equal(balances.Sub(vacc.LockedCoins(now.Add(12*time.Hour))...), origCoins) -} - -func (suite *KeeperTestSuite) TestDelegateCoins() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - delCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], origCoins)) - - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) - - // require the ability for a non-vesting account to delegate - suite.mockDelegateCoins(ctx, acc1, holderAcc) - require.NoError(suite.bankKeeper.DelegateCoins(ctx, accAddrs[1], holderAcc.GetAddress(), delCoins)) - require.Equal(origCoins.Sub(delCoins...), suite.bankKeeper.GetAllBalances(ctx, accAddrs[1])) - require.Equal(delCoins, suite.bankKeeper.GetAllBalances(ctx, holderAcc.GetAddress())) - - // require the ability for a vesting account to delegate - suite.mockDelegateCoins(ctx, vacc, holderAcc) - require.NoError(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) - require.Equal(delCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) - - // require that delegated vesting amount is equal to what was delegated with DelegateCoins - require.Equal(delCoins, vacc.GetDelegatedVesting()) -} - -func (suite *KeeperTestSuite) TestDelegateCoins_Invalid() { - ctx := suite.ctx - require := suite.Require() - - origCoins := sdk.NewCoins(newFooCoin(100)) - delCoins := sdk.NewCoins(newFooCoin(50)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(nil) - require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - invalidCoins := sdk.Coins{sdk.Coin{Denom: "fooDenom", Amount: sdk.NewInt(-50)}} - require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), invalidCoins)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - require.Error(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), origCoins.Add(origCoins...))) -} - -func (suite *KeeperTestSuite) TestUndelegateCoins() { - ctx := suite.ctx - require := suite.Require() - now := tmtime.Now() - endTime := now.Add(24 * time.Hour) - - origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - delCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix()) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockFundAccount(accAddrs[1]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[1], origCoins)) - - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) - - // require the ability for a non-vesting account to delegate - suite.mockDelegateCoins(ctx, acc1, holderAcc) - require.NoError(suite.bankKeeper.DelegateCoins(ctx, accAddrs[1], holderAcc.GetAddress(), delCoins)) - - require.Equal(origCoins.Sub(delCoins...), suite.bankKeeper.GetAllBalances(ctx, accAddrs[1])) - require.Equal(delCoins, suite.bankKeeper.GetAllBalances(ctx, holderAcc.GetAddress())) - - // require the ability for a non-vesting account to undelegate - suite.mockUnDelegateCoins(ctx, acc1, holderAcc) - require.NoError(suite.bankKeeper.UndelegateCoins(ctx, holderAcc.GetAddress(), accAddrs[1], delCoins)) - - require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[1])) - require.True(suite.bankKeeper.GetAllBalances(ctx, holderAcc.GetAddress()).Empty()) - - // require the ability for a vesting account to delegate - suite.mockDelegateCoins(ctx, acc0, holderAcc) - require.NoError(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) - - require.Equal(origCoins.Sub(delCoins...), suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) - require.Equal(delCoins, suite.bankKeeper.GetAllBalances(ctx, holderAcc.GetAddress())) - - // require the ability for a vesting account to undelegate - suite.mockUnDelegateCoins(ctx, vacc, holderAcc) - require.NoError(suite.bankKeeper.UndelegateCoins(ctx, holderAcc.GetAddress(), accAddrs[0], delCoins)) - - require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) - require.True(suite.bankKeeper.GetAllBalances(ctx, holderAcc.GetAddress()).Empty()) - - // require that delegated vesting amount is completely empty, since they were completely undelegated - require.Empty(vacc.GetDelegatedVesting()) -} - -func (suite *KeeperTestSuite) TestUndelegateCoins_Invalid() { - ctx := suite.ctx - require := suite.Require() - - origCoins := sdk.NewCoins(newFooCoin(100)) - delCoins := sdk.NewCoins(newFooCoin(50)) - - acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(nil) - require.Error(suite.bankKeeper.UndelegateCoins(ctx, holderAcc.GetAddress(), accAddrs[0], delCoins)) - - suite.mockFundAccount(accAddrs[0]) - require.NoError(banktestutil.FundAccount(suite.bankKeeper, ctx, accAddrs[0], origCoins)) - - suite.mockDelegateCoins(ctx, acc0, holderAcc) - require.NoError(suite.bankKeeper.DelegateCoins(ctx, accAddrs[0], holderAcc.GetAddress(), delCoins)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - suite.authKeeper.EXPECT().GetAccount(ctx, acc0.GetAddress()).Return(nil) - require.Error(suite.bankKeeper.UndelegateCoins(ctx, holderAcc.GetAddress(), accAddrs[0], delCoins)) - - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - suite.authKeeper.EXPECT().GetAccount(ctx, holderAcc.GetAddress()).Return(holderAcc) - require.Error(suite.bankKeeper.UndelegateCoins(ctx, holderAcc.GetAddress(), accAddrs[0], origCoins)) -} - -func (suite *KeeperTestSuite) TestSetDenomMetaData() { - ctx := suite.ctx - require := suite.Require() - - metadata := suite.getTestMetadata() - - for i := range []int{1, 2} { - suite.bankKeeper.SetDenomMetaData(ctx, metadata[i]) - } - - actualMetadata, found := suite.bankKeeper.GetDenomMetaData(ctx, metadata[1].Base) - require.True(found) - found = suite.bankKeeper.HasDenomMetaData(ctx, metadata[1].Base) - require.True(found) - require.Equal(metadata[1].GetBase(), actualMetadata.GetBase()) - require.Equal(metadata[1].GetDisplay(), actualMetadata.GetDisplay()) - require.Equal(metadata[1].GetDescription(), actualMetadata.GetDescription()) - require.Equal(metadata[1].GetDenomUnits()[1].GetDenom(), actualMetadata.GetDenomUnits()[1].GetDenom()) - require.Equal(metadata[1].GetDenomUnits()[1].GetExponent(), actualMetadata.GetDenomUnits()[1].GetExponent()) - require.Equal(metadata[1].GetDenomUnits()[1].GetAliases(), actualMetadata.GetDenomUnits()[1].GetAliases()) -} - -func (suite *KeeperTestSuite) TestIterateAllDenomMetaData() { - ctx := suite.ctx - require := suite.Require() - - expectedMetadata := suite.getTestMetadata() - // set metadata - for i := range []int{1, 2} { - suite.bankKeeper.SetDenomMetaData(ctx, expectedMetadata[i]) - } - // retrieve metadata - actualMetadata := make([]banktypes.Metadata, 0) - suite.bankKeeper.IterateAllDenomMetaData(ctx, func(metadata banktypes.Metadata) bool { - actualMetadata = append(actualMetadata, metadata) - return false - }) - // execute checks - for i := range []int{1, 2} { - require.Equal(expectedMetadata[i].GetBase(), actualMetadata[i].GetBase()) - require.Equal(expectedMetadata[i].GetDisplay(), actualMetadata[i].GetDisplay()) - require.Equal(expectedMetadata[i].GetDescription(), actualMetadata[i].GetDescription()) - require.Equal(expectedMetadata[i].GetDenomUnits()[1].GetDenom(), actualMetadata[i].GetDenomUnits()[1].GetDenom()) - require.Equal(expectedMetadata[i].GetDenomUnits()[1].GetExponent(), actualMetadata[i].GetDenomUnits()[1].GetExponent()) - require.Equal(expectedMetadata[i].GetDenomUnits()[1].GetAliases(), actualMetadata[i].GetDenomUnits()[1].GetAliases()) - } -} - -func (suite *KeeperTestSuite) TestBalanceTrackingEvents() { - require := suite.Require() - - // mint coins - suite.mockMintCoins(multiPermAcc) - require.NoError( - suite.bankKeeper.MintCoins( - suite.ctx, - multiPermAcc.Name, - sdk.NewCoins(sdk.NewCoin("utxo", sdk.NewInt(100000)))), - ) - // send coins to address - suite.mockSendCoinsFromModuleToAccount(multiPermAcc, accAddrs[0]) - require.NoError( - suite.bankKeeper.SendCoinsFromModuleToAccount( - suite.ctx, - multiPermAcc.Name, - accAddrs[0], - sdk.NewCoins(sdk.NewCoin("utxo", sdk.NewInt(50000))), - ), - ) - - // burn coins from module account - suite.mockBurnCoins(multiPermAcc) - require.NoError( - suite.bankKeeper.BurnCoins( - suite.ctx, - multiPermAcc.Name, - sdk.NewCoins(sdk.NewInt64Coin("utxo", 1000)), - ), - ) - - // process balances and supply from events - supply := sdk.NewCoins() - - balances := make(map[string]sdk.Coins) - - for _, e := range suite.ctx.EventManager().ABCIEvents() { - switch e.Type { - case banktypes.EventTypeCoinBurn: - burnedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) - require.NoError(err) - supply = supply.Sub(burnedCoins...) - - case banktypes.EventTypeCoinMint: - mintedCoins, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) - require.NoError(err) - supply = supply.Add(mintedCoins...) - - case banktypes.EventTypeCoinSpent: - coinsSpent, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) - require.NoError(err) - spender, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) - require.NoError(err) - balances[spender.String()] = balances[spender.String()].Sub(coinsSpent...) - - case banktypes.EventTypeCoinReceived: - coinsRecv, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) - require.NoError(err) - receiver, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) - require.NoError(err) - balances[receiver.String()] = balances[receiver.String()].Add(coinsRecv...) - } - } - - // check balance and supply tracking - require.True(suite.bankKeeper.HasSupply(suite.ctx, "utxo")) - savedSupply := suite.bankKeeper.GetSupply(suite.ctx, "utxo") - utxoSupply := savedSupply - require.Equal(utxoSupply.Amount, supply.AmountOf("utxo")) - // iterate accounts and check balances - suite.bankKeeper.IterateAllBalances(suite.ctx, func(address sdk.AccAddress, coin sdk.Coin) (stop bool) { - // if it's not utxo coin then skip - if coin.Denom != "utxo" { - return false - } - - balance, exists := balances[address.String()] - require.True(exists) - - expectedUtxo := sdk.NewCoin("utxo", balance.AmountOf(coin.Denom)) - require.Equal(expectedUtxo.String(), coin.String()) - return false - }) -} - -func (suite *KeeperTestSuite) getTestMetadata() []banktypes.Metadata { - return []banktypes.Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*banktypes.DenomUnit{ - {Denom: "uatom", Exponent: uint32(0), Aliases: []string{"microatom"}}, - {Denom: "matom", Exponent: uint32(3), Aliases: []string{"milliatom"}}, - {Denom: "atom", Exponent: uint32(6), Aliases: nil}, - }, - Base: "uatom", - Display: "atom", - }, - { - Name: "Token", - Symbol: "TOKEN", - Description: "The native staking token of the Token Hub.", - DenomUnits: []*banktypes.DenomUnit{ - {Denom: "1token", Exponent: uint32(5), Aliases: []string{"decitoken"}}, - {Denom: "2token", Exponent: uint32(4), Aliases: []string{"centitoken"}}, - {Denom: "3token", Exponent: uint32(7), Aliases: []string{"dekatoken"}}, - }, - Base: "utoken", - Display: "token", - }, - } -} - -func (suite *KeeperTestSuite) TestMintCoinRestrictions() { - type BankMintingRestrictionFn func(ctx sdk.Context, coins sdk.Coins) error - require := suite.Require() - - type testCase struct { - coinsToTry sdk.Coin - expectPass bool - } - - tests := []struct { - name string - restrictionFn BankMintingRestrictionFn - testCases []testCase - }{ - { - "restriction", - func(_ sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - if coin.Denom != fooDenom { - return fmt.Errorf("Module %s only has perms for minting %s coins, tried minting %s coins", banktypes.ModuleName, fooDenom, coin.Denom) - } - } - return nil - }, - []testCase{ - { - coinsToTry: newFooCoin(100), - expectPass: true, - }, - { - coinsToTry: newBarCoin(100), - expectPass: false, - }, - }, - }, - } - - for _, test := range tests { - keeper := suite.bankKeeper.WithMintCoinsRestriction(keeper.MintingRestrictionFn(test.restrictionFn)) - for _, testCase := range test.testCases { - if testCase.expectPass { - suite.mockMintCoins(multiPermAcc) - require.NoError( - keeper.MintCoins( - suite.ctx, - multiPermAcc.Name, - sdk.NewCoins(testCase.coinsToTry), - ), - ) - } else { - require.Error( - keeper.MintCoins( - suite.ctx, - multiPermAcc.Name, - sdk.NewCoins(testCase.coinsToTry), - ), - ) - } - } - } -} - -func (suite *KeeperTestSuite) TestIsSendEnabledDenom() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - defaultCoin := "defaultCoin" - enabledCoin := "enabledCoin" - disabledCoin := "disabledCoin" - bankKeeper.DeleteSendEnabled(ctx, defaultCoin) - bankKeeper.SetSendEnabled(ctx, enabledCoin, true) - bankKeeper.SetSendEnabled(ctx, disabledCoin, false) - - tests := []struct { - denom string - exp bool - expDef bool - }{ - { - denom: "defaultCoin", - expDef: true, - }, - { - denom: enabledCoin, - exp: true, - }, - { - denom: disabledCoin, - exp: false, - }, - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - for _, tc := range tests { - suite.T().Run(fmt.Sprintf("%s default %t", tc.denom, def), func(t *testing.T) { - actual := suite.bankKeeper.IsSendEnabledDenom(suite.ctx, tc.denom) - exp := tc.exp - if tc.expDef { - exp = def - } - - require.Equal(exp, actual) - }) - } - } -} - -func (suite *KeeperTestSuite) TestGetSendEnabledEntry() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - bankKeeper.SetAllSendEnabled(ctx, []*banktypes.SendEnabled{ - {Denom: "gettruecoin", Enabled: true}, - {Denom: "getfalsecoin", Enabled: false}, - }) - - tests := []struct { - denom string - expSE banktypes.SendEnabled - expF bool - }{ - { - denom: "missing", - expSE: banktypes.SendEnabled{}, - expF: false, - }, - { - denom: "gettruecoin", - expSE: banktypes.SendEnabled{Denom: "gettruecoin", Enabled: true}, - expF: true, - }, - { - denom: "getfalsecoin", - expSE: banktypes.SendEnabled{Denom: "getfalsecoin", Enabled: false}, - expF: true, - }, - } - - for _, tc := range tests { - suite.T().Run(tc.denom, func(t *testing.T) { - actualSE, actualF := bankKeeper.GetSendEnabledEntry(ctx, tc.denom) - require.Equal(tc.expF, actualF, "found") - require.Equal(tc.expSE, actualSE, "SendEnabled") - }) - } -} - -func (suite *KeeperTestSuite) TestSetSendEnabled() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - tests := []struct { - name string - denom string - value bool - }{ - { - name: "very short denom true", - denom: "f", - value: true, - }, - { - name: "very short denom false", - denom: "f", - value: true, - }, - { - name: "falseFirstCoin false", - denom: "falseFirstCoin", - value: false, - }, - { - name: "falseFirstCoin true", - denom: "falseFirstCoin", - value: true, - }, - { - name: "falseFirstCoin true again", - denom: "falseFirstCoin", - value: true, - }, - { - name: "trueFirstCoin true", - denom: "falseFirstCoin", - value: false, - }, - { - name: "trueFirstCoin false", - denom: "falseFirstCoin", - value: false, - }, - { - name: "trueFirstCoin false again", - denom: "falseFirstCoin", - value: false, - }, - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - for _, tc := range tests { - suite.T().Run(fmt.Sprintf("%s default %t", tc.name, def), func(t *testing.T) { - bankKeeper.SetSendEnabled(ctx, tc.denom, tc.value) - actual := bankKeeper.IsSendEnabledDenom(ctx, tc.denom) - require.Equal(tc.value, actual) - }) - } - } -} - -func (suite *KeeperTestSuite) TestSetAllSendEnabled() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - tests := []struct { - name string - sendEnableds []*banktypes.SendEnabled - }{ - { - name: "nil", - sendEnableds: nil, - }, - { - name: "empty", - sendEnableds: []*banktypes.SendEnabled{}, - }, - { - name: "one true", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "aonecoin", Enabled: true}, - }, - }, - { - name: "one false", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "bonecoin", Enabled: false}, - }, - }, - { - name: "two true", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "conecoin", Enabled: true}, - {Denom: "ctwocoin", Enabled: true}, - }, - }, - { - name: "two true false", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "donecoin", Enabled: true}, - {Denom: "dtwocoin", Enabled: false}, - }, - }, - { - name: "two false true", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "eonecoin", Enabled: false}, - {Denom: "etwocoin", Enabled: true}, - }, - }, - { - name: "two false", - sendEnableds: []*banktypes.SendEnabled{ - {Denom: "fonecoin", Enabled: false}, - {Denom: "ftwocoin", Enabled: false}, - }, - }, - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - for _, tc := range tests { - suite.T().Run(fmt.Sprintf("%s default %t", tc.name, def), func(t *testing.T) { - bankKeeper.SetAllSendEnabled(ctx, tc.sendEnableds) - - for _, se := range tc.sendEnableds { - actual := bankKeeper.IsSendEnabledDenom(ctx, se.Denom) - require.Equal(se.Enabled, actual, se.Denom) - } - }) - } - } -} - -func (suite *KeeperTestSuite) TestDeleteSendEnabled() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - suite.T().Run(fmt.Sprintf("default %t", def), func(t *testing.T) { - denom := fmt.Sprintf("somerand%tcoin", !def) - bankKeeper.SetSendEnabled(ctx, denom, !def) - require.Equal(!def, bankKeeper.IsSendEnabledDenom(ctx, denom)) - bankKeeper.DeleteSendEnabled(ctx, denom) - require.Equal(def, bankKeeper.IsSendEnabledDenom(ctx, denom)) - }) - } -} - -func (suite *KeeperTestSuite) TestIterateSendEnabledEntries() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - suite.T().Run("no entries to iterate", func(t *testing.T) { - count := 0 - bankKeeper.IterateSendEnabledEntries(ctx, func(_ string, _ bool) (stop bool) { - count++ - return false - }) - - require.Equal(0, count) - }) - - alpha := strings.Split("abcdefghijklmnopqrstuvwxyz", "") - denoms := make([]string, len(alpha)*2) - for i, l := range alpha { - denoms[i*2] = fmt.Sprintf("%sitercointrue", l) - denoms[i*2+1] = fmt.Sprintf("%sitercoinfalse", l) - bankKeeper.SetSendEnabled(ctx, denoms[i*2], true) - bankKeeper.SetSendEnabled(ctx, denoms[i*2+1], false) - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - var seen []string - suite.T().Run(fmt.Sprintf("all denoms have expected values default %t", def), func(t *testing.T) { - bankKeeper.IterateSendEnabledEntries(ctx, func(denom string, sendEnabled bool) (stop bool) { - seen = append(seen, denom) - exp := true - if strings.HasSuffix(denom, "false") { - exp = false - } - - require.Equal(exp, sendEnabled, denom) - return false - }) - }) - - suite.T().Run(fmt.Sprintf("all denoms were seen default %t", def), func(t *testing.T) { - require.ElementsMatch(denoms, seen) - }) - } - - bankKeeper.DeleteSendEnabled(ctx, denoms...) - - suite.T().Run("no entries to iterate again after deleting all of them", func(t *testing.T) { - count := 0 - bankKeeper.IterateSendEnabledEntries(ctx, func(_ string, _ bool) (stop bool) { - count++ - return false - }) - - require.Equal(0, count) - }) -} - -func (suite *KeeperTestSuite) TestGetAllSendEnabledEntries() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - suite.T().Run("no entries", func(t *testing.T) { - actual := bankKeeper.GetAllSendEnabledEntries(ctx) - require.Len(actual, 0) - }) - - alpha := strings.Split("abcdefghijklmnopqrstuvwxyz", "") - denoms := make([]string, len(alpha)*2) - for i, l := range alpha { - denoms[i*2] = fmt.Sprintf("%sitercointrue", l) - denoms[i*2+1] = fmt.Sprintf("%sitercoinfalse", l) - bankKeeper.SetSendEnabled(ctx, denoms[i*2], true) - bankKeeper.SetSendEnabled(ctx, denoms[i*2+1], false) - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - var seen []string - suite.T().Run(fmt.Sprintf("all denoms have expected values default %t", def), func(t *testing.T) { - actual := bankKeeper.GetAllSendEnabledEntries(ctx) - for _, se := range actual { - seen = append(seen, se.Denom) - exp := true - if strings.HasSuffix(se.Denom, "false") { - exp = false - } - - require.Equal(exp, se.Enabled, se.Denom) - } - }) - - suite.T().Run(fmt.Sprintf("all denoms were seen default %t", def), func(t *testing.T) { - require.ElementsMatch(denoms, seen) - }) - } - - for _, denom := range denoms { - bankKeeper.DeleteSendEnabled(ctx, denom) - } - - suite.T().Run("no entries again after deleting all of them", func(t *testing.T) { - actual := bankKeeper.GetAllSendEnabledEntries(ctx) - require.Len(actual, 0) - }) -} - -type mockSubspace struct { - ps banktypes.Params -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*banktypes.Params) = ms.ps -} - -func (suite *KeeperTestSuite) TestMigrator_Migrate3to4() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - for _, def := range []bool{true, false} { - params := banktypes.Params{DefaultSendEnabled: def} - require.NoError(bankKeeper.SetParams(ctx, params)) - - suite.T().Run(fmt.Sprintf("default %t does not change", def), func(t *testing.T) { - legacySubspace := func(ps banktypes.Params) mockSubspace { - return mockSubspace{ps: ps} - }(banktypes.NewParams(def)) - - migrator := keeper.NewMigrator(bankKeeper, legacySubspace) - require.NoError(migrator.Migrate3to4(ctx)) - - actual := bankKeeper.GetParams(ctx) - require.Equal(params.DefaultSendEnabled, actual.DefaultSendEnabled) - }) - } - - for _, def := range []bool{true, false} { - params := banktypes.Params{ - SendEnabled: []*banktypes.SendEnabled{ - {Denom: fmt.Sprintf("truecoin%t", def), Enabled: true}, - {Denom: fmt.Sprintf("falsecoin%t", def), Enabled: false}, - }, - } - - require.NoError(bankKeeper.SetParams(ctx, params)) - - suite.T().Run(fmt.Sprintf("default %t send enabled info moved to store", def), func(t *testing.T) { - legacySubspace := func(ps banktypes.Params) mockSubspace { - return mockSubspace{ps: ps} - }(banktypes.NewParams(def)) - - migrator := keeper.NewMigrator(bankKeeper, legacySubspace) - require.NoError(migrator.Migrate3to4(ctx)) - - newParams := bankKeeper.GetParams(ctx) - require.Len(newParams.SendEnabled, 0) - require.Equal(def, newParams.DefaultSendEnabled) - - for _, se := range params.SendEnabled { - actual := bankKeeper.IsSendEnabledDenom(ctx, se.Denom) - require.Equal(se.Enabled, actual, se.Denom) - } - }) - } -} - -func (suite *KeeperTestSuite) TestSetParams() { - ctx, bankKeeper := suite.ctx, suite.bankKeeper - require := suite.Require() - - params := banktypes.NewParams(true) - params.SendEnabled = []*banktypes.SendEnabled{ - {Denom: "paramscointrue", Enabled: true}, - {Denom: "paramscoinfalse", Enabled: false}, - } - require.NoError(bankKeeper.SetParams(ctx, params)) - - suite.Run("stored params are as expected", func() { - actual := bankKeeper.GetParams(ctx) - require.True(actual.DefaultSendEnabled, "DefaultSendEnabled") - require.Len(actual.SendEnabled, 0, "SendEnabled") - }) - - suite.Run("send enabled params converted to store", func() { - actual := bankKeeper.GetAllSendEnabledEntries(ctx) - if suite.Assert().Len(actual, 2) { - require.Equal("paramscoinfalse", actual[0].Denom, "actual[0].Denom") - require.False(actual[0].Enabled, "actual[0].Enabled") - require.Equal("paramscointrue", actual[1].Denom, "actual[1].Denom") - require.True(actual[1].Enabled, "actual[1].Enabled") - } - }) -} diff --git a/x/bank/keeper/migrations.go b/x/bank/keeper/migrations.go deleted file mode 100644 index 2e2d0ee7a..000000000 --- a/x/bank/keeper/migrations.go +++ /dev/null @@ -1,35 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v3" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper BaseKeeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper BaseKeeper, legacySubspace exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: legacySubspace} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc) -} - -// Migrate2to3 migrates x/bank storage from version 2 to 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v3.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc) -} - -// Migrate3to4 migrates x/bank storage from version 3 to 4. -func (m Migrator) Migrate3to4(ctx sdk.Context) error { - return v4.MigrateStore(ctx, m.keeper.storeKey, m.legacySubspace, m.keeper.cdc) -} diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go deleted file mode 100644 index 3f2d5bac1..000000000 --- a/x/bank/keeper/msg_server.go +++ /dev/null @@ -1,120 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/armon/go-metrics" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" -) - -type msgServer struct { - Keeper -} - -var _ types.MsgServer = msgServer{} - -// NewMsgServerImpl returns an implementation of the bank MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSendResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := k.IsSendEnabledCoins(ctx, msg.Amount...); err != nil { - return nil, err - } - - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return nil, err - } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { - return nil, err - } - - if k.BlockedAddr(to) { - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) - } - - err = k.SendCoins(ctx, from, to, msg.Amount) - if err != nil { - return nil, err - } - - defer func() { - for _, a := range msg.Amount { - if a.Amount.IsInt64() { - telemetry.SetGaugeWithLabels( - []string{"tx", "msg", "send"}, - float32(a.Amount.Int64()), - []metrics.Label{telemetry.NewLabel("denom", a.Denom)}, - ) - } - } - }() - - return &types.MsgSendResponse{}, nil -} - -func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*types.MsgMultiSendResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - // NOTE: totalIn == totalOut should already have been checked - for _, in := range msg.Inputs { - if err := k.IsSendEnabledCoins(ctx, in.Coins...); err != nil { - return nil, err - } - } - - for _, out := range msg.Outputs { - accAddr := sdk.MustAccAddressFromBech32(out.Address) - - if k.BlockedAddr(accAddr) { - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", out.Address) - } - } - - err := k.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) - if err != nil { - return nil, err - } - - return &types.MsgMultiSendResponse{}, nil -} - -func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.GetAuthority() != req.Authority { - return nil, sdkerrors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.SetParams(ctx, req.Params); err != nil { - return nil, err - } - - return &types.MsgUpdateParamsResponse{}, nil -} - -func (k msgServer) SetSendEnabled(goCtx context.Context, msg *types.MsgSetSendEnabled) (*types.MsgSetSendEnabledResponse, error) { - if k.GetAuthority() != msg.Authority { - return nil, sdkerrors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), msg.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - if len(msg.SendEnabled) > 0 { - k.SetAllSendEnabled(ctx, msg.SendEnabled) - } - if len(msg.UseDefaultFor) > 0 { - k.DeleteSendEnabled(ctx, msg.UseDefaultFor...) - } - - return &types.MsgSetSendEnabledResponse{}, nil -} diff --git a/x/bank/keeper/msg_service_test.go b/x/bank/keeper/msg_service_test.go deleted file mode 100644 index 87b5c4b6f..000000000 --- a/x/bank/keeper/msg_service_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package keeper_test - -import ( - 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" -) - -func (suite *KeeperTestSuite) TestMsgUpdateParams() { - // default params - params := banktypes.DefaultParams() - - testCases := []struct { - name string - input *banktypes.MsgUpdateParams - expErr bool - expErrMsg string - }{ - { - name: "invalid authority", - input: &banktypes.MsgUpdateParams{ - Authority: "invalid", - Params: params, - }, - expErr: true, - expErrMsg: "invalid authority", - }, - { - name: "send enabled param", - input: &banktypes.MsgUpdateParams{ - Authority: suite.bankKeeper.GetAuthority(), - Params: banktypes.Params{ - SendEnabled: []*banktypes.SendEnabled{ - {Denom: "foo", Enabled: true}, - }, - }, - }, - expErr: false, - }, - { - name: "all good", - input: &banktypes.MsgUpdateParams{ - Authority: suite.bankKeeper.GetAuthority(), - Params: params, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - _, err := suite.msgServer.UpdateParams(suite.ctx, tc.input) - - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMsgSend() { - origCoins := sdk.NewCoins(sdk.NewInt64Coin("sendableCoin", 100)) - suite.bankKeeper.SetSendEnabled(suite.ctx, origCoins.Denoms()[0], true) - - testCases := []struct { - name string - input *banktypes.MsgSend - expErr bool - expErrMsg string - }{ - { - name: "invalid send to blocked address", - input: &banktypes.MsgSend{ - FromAddress: minterAcc.GetAddress().String(), - ToAddress: accAddrs[4].String(), - Amount: origCoins, - }, - expErr: true, - expErrMsg: "is not allowed to receive funds", - }, - { - name: "all good", - input: &banktypes.MsgSend{ - FromAddress: minterAcc.GetAddress().String(), - ToAddress: baseAcc.Address, - Amount: origCoins, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) - if !tc.expErr { - suite.mockSendCoins(suite.ctx, minterAcc, baseAcc.GetAddress()) - } - _, err := suite.msgServer.Send(suite.ctx, tc.input) - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMsgMultiSend() { - origDenom := "sendableCoin" - origCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 100)) - sendCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 50)) - suite.bankKeeper.SetSendEnabled(suite.ctx, origDenom, true) - - testCases := []struct { - name string - input *banktypes.MsgMultiSend - expErr bool - expErrMsg string - }{ - { - name: "invalid send to blocked address", - input: &banktypes.MsgMultiSend{ - Inputs: []banktypes.Input{ - {Address: minterAcc.GetAddress().String(), Coins: origCoins}, - }, - Outputs: []banktypes.Output{ - {Address: accAddrs[0].String(), Coins: sendCoins}, - {Address: accAddrs[4].String(), Coins: sendCoins}, - }, - }, - expErr: true, - expErrMsg: "is not allowed to receive funds", - }, - { - name: "invalid send to blocked address", - input: &banktypes.MsgMultiSend{ - Inputs: []banktypes.Input{ - {Address: minterAcc.GetAddress().String(), Coins: origCoins}, - }, - Outputs: []banktypes.Output{ - {Address: accAddrs[0].String(), Coins: sendCoins}, - {Address: accAddrs[1].String(), Coins: sendCoins}, - }, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) - if !tc.expErr { - suite.mockInputOutputCoins([]authtypes.AccountI{minterAcc}, accAddrs[:2]) - } - _, err := suite.msgServer.MultiSend(suite.ctx, tc.input) - if tc.expErr { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.expErrMsg) - } else { - suite.Require().NoError(err) - } - }) - } -} diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go deleted file mode 100644 index 644ea1980..000000000 --- a/x/bank/keeper/send.go +++ /dev/null @@ -1,523 +0,0 @@ -package keeper - -import ( - "fmt" - - gogotypes "github.com/cosmos/gogoproto/types" - - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// SendKeeper defines a module interface that facilitates the transfer of coins -// between accounts without the possibility of creating coins. -type SendKeeper interface { - ViewKeeper - - InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error - - GetParams(ctx sdk.Context) types.Params - SetParams(ctx sdk.Context, params types.Params) error - - IsSendEnabledDenom(ctx sdk.Context, denom string) bool - GetSendEnabledEntry(ctx sdk.Context, denom string) (types.SendEnabled, bool) - SetSendEnabled(ctx sdk.Context, denom string, value bool) - SetAllSendEnabled(ctx sdk.Context, sendEnableds []*types.SendEnabled) - DeleteSendEnabled(ctx sdk.Context, denoms ...string) - IterateSendEnabledEntries(ctx sdk.Context, cb func(denom string, sendEnabled bool) (stop bool)) - GetAllSendEnabledEntries(ctx sdk.Context) []types.SendEnabled - - IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool - IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - - BlockedAddr(addr sdk.AccAddress) bool - GetBlockedAddresses() map[string]bool - - GetAuthority() string -} - -var _ SendKeeper = (*BaseSendKeeper)(nil) - -// BaseSendKeeper only allows transfers between accounts without the possibility of -// creating coins. It implements the SendKeeper interface. -type BaseSendKeeper struct { - BaseViewKeeper - - cdc codec.BinaryCodec - ak types.AccountKeeper - storeKey storetypes.StoreKey - - // list of addresses that are restricted from receiving transactions - blockedAddrs map[string]bool - - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority string -} - -func NewBaseSendKeeper( - cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, - ak types.AccountKeeper, - blockedAddrs map[string]bool, - authority string, -) BaseSendKeeper { - if _, err := sdk.AccAddressFromBech32(authority); err != nil { - panic(fmt.Errorf("invalid bank authority address: %w", err)) - } - - return BaseSendKeeper{ - BaseViewKeeper: NewBaseViewKeeper(cdc, storeKey, ak), - cdc: cdc, - ak: ak, - storeKey: storeKey, - blockedAddrs: blockedAddrs, - authority: authority, - } -} - -// GetAuthority returns the x/bank module's authority. -func (k BaseSendKeeper) GetAuthority() string { - return k.authority -} - -// GetParams returns the total set of bank parameters. -func (k BaseSendKeeper) GetParams(ctx sdk.Context) (params types.Params) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - - k.cdc.MustUnmarshal(bz, ¶ms) - return params -} - -// SetParams sets the total set of bank parameters. -// -// Note: params.SendEnabled is deprecated but it should be here regardless. -// -//nolint:staticcheck -func (k BaseSendKeeper) SetParams(ctx sdk.Context, params types.Params) error { - // Normally SendEnabled is deprecated but we still support it for backwards - // compatibility. Using params.Validate() would fail due to the SendEnabled - // deprecation. - if len(params.SendEnabled) > 0 { - k.SetAllSendEnabled(ctx, params.SendEnabled) - - // override params without SendEnabled - params = types.NewParams(params.DefaultSendEnabled) - } - - store := ctx.KVStore(k.storeKey) - bz, err := k.cdc.Marshal(¶ms) - if err != nil { - return err - } - - store.Set(types.ParamsKey, bz) - return nil -} - -// InputOutputCoins performs multi-send functionality. It accepts a series of -// inputs that correspond to a series of outputs. It returns an error if the -// inputs and outputs don't line up or if any single transfer of tokens fails. -func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error { - // Safety check ensuring that when sending coins the keeper must maintain the - // Check supply invariant and validity of Coins. - if err := types.ValidateInputsOutputs(inputs, outputs); err != nil { - return err - } - - for _, in := range inputs { - inAddress, err := sdk.AccAddressFromBech32(in.Address) - if err != nil { - return err - } - - err = k.subUnlockedCoins(ctx, inAddress, in.Coins) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(types.AttributeKeySender, in.Address), - ), - ) - } - - for _, out := range outputs { - outAddress, err := sdk.AccAddressFromBech32(out.Address) - if err != nil { - return err - } - - if err := k.addCoins(ctx, outAddress, out.Coins); err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeyRecipient, out.Address), - sdk.NewAttribute(sdk.AttributeKeyAmount, out.Coins.String()), - ), - ) - - // Create account if recipient does not exist. - // - // NOTE: This should ultimately be removed in favor a more flexible approach - // such as delegated fee messages. - accExists := k.ak.HasAccount(ctx, outAddress) - if !accExists { - defer telemetry.IncrCounter(1, "new", "account") - k.ak.SetAccount(ctx, k.ak.NewAccountWithAddress(ctx, outAddress)) - } - } - - return nil -} - -// SendCoins transfers amt coins from a sending account to a receiving account. -// An error is returned upon failure. -func (k BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { - err := k.subUnlockedCoins(ctx, fromAddr, amt) - if err != nil { - return err - } - - err = k.addCoins(ctx, toAddr, amt) - if err != nil { - return err - } - - // Create account if recipient does not exist. - // - // NOTE: This should ultimately be removed in favor a more flexible approach - // such as delegated fee messages. - accExists := k.ak.HasAccount(ctx, toAddr) - if !accExists { - defer telemetry.IncrCounter(1, "new", "account") - k.ak.SetAccount(ctx, k.ak.NewAccountWithAddress(ctx, toAddr)) - } - - // bech32 encoding is expensive! Only do it once for fromAddr - fromAddrString := fromAddr.String() - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeTransfer, - sdk.NewAttribute(types.AttributeKeyRecipient, toAddr.String()), - sdk.NewAttribute(types.AttributeKeySender, fromAddrString), - sdk.NewAttribute(sdk.AttributeKeyAmount, amt.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(types.AttributeKeySender, fromAddr.String()), - ), - }) - - return nil -} - -// subUnlockedCoins removes the unlocked amt coins of the given account. An error is -// returned if the resulting balance is negative or the initial amount is invalid. -// A coin_spent event is emitted after. -func (k BaseSendKeeper) subUnlockedCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error { - if !amt.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String()) - } - - lockedCoins := k.LockedCoins(ctx, addr) - - for _, coin := range amt { - balance := k.GetBalance(ctx, addr, coin.Denom) - locked := sdk.NewCoin(coin.Denom, lockedCoins.AmountOf(coin.Denom)) - - spendable, hasNeg := sdk.Coins{balance}.SafeSub(locked) - if hasNeg { - return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, - "locked amount exceeds account balance funds: %s > %s", locked, balance) - } - - if _, hasNeg := spendable.SafeSub(coin); hasNeg { - return sdkerrors.Wrapf( - sdkerrors.ErrInsufficientFunds, - "spendable balance %s is smaller than %s", - spendable, coin, - ) - } - - newBalance := balance.Sub(coin) - - if err := k.setBalance(ctx, addr, newBalance); err != nil { - return err - } - } - - ctx.EventManager().EmitEvent( - types.NewCoinSpentEvent(addr, amt), - ) - - return nil -} - -// addCoins increase the addr balance by the given amt. Fails if the provided -// amt is invalid. It emits a coin received event. -func (k BaseSendKeeper) addCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error { - if !amt.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String()) - } - - for _, coin := range amt { - balance := k.GetBalance(ctx, addr, coin.Denom) - newBalance := balance.Add(coin) - - err := k.setBalance(ctx, addr, newBalance) - if err != nil { - return err - } - } - - // emit coin received event - ctx.EventManager().EmitEvent( - types.NewCoinReceivedEvent(addr, amt), - ) - - return nil -} - -// initBalances sets the balance (multiple coins) for an account by address. -// An error is returned upon failure. -func (k BaseSendKeeper) initBalances(ctx sdk.Context, addr sdk.AccAddress, balances sdk.Coins) error { - accountStore := k.getAccountStore(ctx, addr) - denomPrefixStores := make(map[string]prefix.Store) // memoize prefix stores - - for i := range balances { - balance := balances[i] - if !balance.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, balance.String()) - } - - // x/bank invariants prohibit persistence of zero balances - if !balance.IsZero() { - amount, err := balance.Amount.Marshal() - if err != nil { - return err - } - accountStore.Set([]byte(balance.Denom), amount) - - denomPrefixStore, ok := denomPrefixStores[balance.Denom] - if !ok { - denomPrefixStore = k.getDenomAddressPrefixStore(ctx, balance.Denom) - denomPrefixStores[balance.Denom] = denomPrefixStore - } - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomAddrKey := address.MustLengthPrefix(addr) - if !denomPrefixStore.Has(denomAddrKey) { - denomPrefixStore.Set(denomAddrKey, []byte{0}) - } - } - } - - return nil -} - -// setBalance sets the coin balance for an account by address. -func (k BaseSendKeeper) setBalance(ctx sdk.Context, addr sdk.AccAddress, balance sdk.Coin) error { - if !balance.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, balance.String()) - } - - accountStore := k.getAccountStore(ctx, addr) - denomPrefixStore := k.getDenomAddressPrefixStore(ctx, balance.Denom) - - // x/bank invariants prohibit persistence of zero balances - if balance.IsZero() { - accountStore.Delete([]byte(balance.Denom)) - denomPrefixStore.Delete(address.MustLengthPrefix(addr)) - } else { - amount, err := balance.Amount.Marshal() - if err != nil { - return err - } - - accountStore.Set([]byte(balance.Denom), amount) - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomAddrKey := address.MustLengthPrefix(addr) - if !denomPrefixStore.Has(denomAddrKey) { - denomPrefixStore.Set(denomAddrKey, []byte{0}) - } - } - - return nil -} - -// IsSendEnabledCoins checks the coins provided and returns an ErrSendDisabled -// if any of the coins are not configured for sending. Returns nil if sending is -// enabled for all provided coins. -func (k BaseSendKeeper) IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error { - if len(coins) == 0 { - return nil - } - - store := ctx.KVStore(k.storeKey) - defaultVal := k.GetParams(ctx).DefaultSendEnabled - - for _, coin := range coins { - if !k.getSendEnabledOrDefault(store, coin.Denom, defaultVal) { - return types.ErrSendDisabled.Wrapf("%s transfers are currently disabled", coin.Denom) - } - } - - return nil -} - -// IsSendEnabledCoin returns the current SendEnabled status of the provided coin's denom -func (k BaseSendKeeper) IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool { - return k.IsSendEnabledDenom(ctx, coin.Denom) -} - -// BlockedAddr checks if a given address is restricted from -// receiving funds. -func (k BaseSendKeeper) BlockedAddr(addr sdk.AccAddress) bool { - return k.blockedAddrs[addr.String()] -} - -// GetBlockedAddresses returns the full list of addresses restricted from receiving funds. -func (k BaseSendKeeper) GetBlockedAddresses() map[string]bool { - return k.blockedAddrs -} - -// IsSendEnabledDenom returns the current SendEnabled status of the provided denom. -func (k BaseSendKeeper) IsSendEnabledDenom(ctx sdk.Context, denom string) bool { - return k.getSendEnabledOrDefault(ctx.KVStore(k.storeKey), denom, k.GetParams(ctx).DefaultSendEnabled) -} - -// GetSendEnabledEntry gets a SendEnabled entry for the given denom. -// The second return argument is true iff a specific entry exists for the given denom. -func (k BaseSendKeeper) GetSendEnabledEntry(ctx sdk.Context, denom string) (types.SendEnabled, bool) { - sendEnabled, found := k.getSendEnabled(ctx.KVStore(k.storeKey), denom) - if !found { - return types.SendEnabled{}, false - } - - return types.SendEnabled{Denom: denom, Enabled: sendEnabled}, true -} - -// SetSendEnabled sets the SendEnabled flag for a denom to the provided value. -func (k BaseSendKeeper) SetSendEnabled(ctx sdk.Context, denom string, value bool) { - store := ctx.KVStore(k.storeKey) - k.setSendEnabledEntry(store, denom, value) -} - -// SetAllSendEnabled sets all the provided SendEnabled entries in the bank store. -func (k BaseSendKeeper) SetAllSendEnabled(ctx sdk.Context, entries []*types.SendEnabled) { - store := ctx.KVStore(k.storeKey) - for _, entry := range entries { - k.setSendEnabledEntry(store, entry.Denom, entry.Enabled) - } -} - -// setSendEnabledEntry sets SendEnabled for the given denom to the give value in the provided store. -func (k BaseSendKeeper) setSendEnabledEntry(store sdk.KVStore, denom string, value bool) { - key := types.CreateSendEnabledKey(denom) - - bz := k.cdc.MustMarshal(&gogotypes.BoolValue{Value: value}) - store.Set(key, bz) -} - -// DeleteSendEnabled deletes the SendEnabled flags for one or more denoms. -// If a denom is provided that doesn't have a SendEnabled entry, it is ignored. -func (k BaseSendKeeper) DeleteSendEnabled(ctx sdk.Context, denoms ...string) { - store := ctx.KVStore(k.storeKey) - for _, denom := range denoms { - store.Delete(types.CreateSendEnabledKey(denom)) - } -} - -// getSendEnabledPrefixStore gets a prefix store for the SendEnabled entries. -func (k BaseSendKeeper) getSendEnabledPrefixStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.SendEnabledPrefix) -} - -// IterateSendEnabledEntries iterates over all the SendEnabled entries. -func (k BaseSendKeeper) IterateSendEnabledEntries(ctx sdk.Context, cb func(denom string, sendEnabled bool) bool) { - seStore := k.getSendEnabledPrefixStore(ctx) - - iterator := seStore.Iterator(nil, nil) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) - - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - - var enabled gogotypes.BoolValue - k.cdc.MustUnmarshal(iterator.Value(), &enabled) - - if cb(denom, enabled.Value) { - break - } - } -} - -// GetAllSendEnabledEntries gets all the SendEnabled entries that are stored. -// Any denominations not returned use the default value (set in Params). -func (k BaseSendKeeper) GetAllSendEnabledEntries(ctx sdk.Context) []types.SendEnabled { - var rv []types.SendEnabled - k.IterateSendEnabledEntries(ctx, func(denom string, sendEnabled bool) bool { - rv = append(rv, types.SendEnabled{Denom: denom, Enabled: sendEnabled}) - return false - }) - - return rv -} - -// getSendEnabled returns whether send is enabled and whether that flag was set -// for a denom. -// -// Example usage: -// -// store := ctx.KVStore(k.storeKey) -// sendEnabled, found := getSendEnabled(store, "atom") -// if !found { -// sendEnabled = DefaultSendEnabled -// } -func (k BaseSendKeeper) getSendEnabled(store sdk.KVStore, denom string) (bool, bool) { - key := types.CreateSendEnabledKey(denom) - if !store.Has(key) { - return false, false - } - - bz := store.Get(key) - if bz == nil { - return false, false - } - - var enabled gogotypes.BoolValue - k.cdc.MustUnmarshal(bz, &enabled) - - return enabled.Value, true -} - -// getSendEnabledOrDefault gets the SendEnabled value for a denom. If it's not -// in the store, this will return defaultVal. -func (k BaseSendKeeper) getSendEnabledOrDefault(store sdk.KVStore, denom string, defaultVal bool) bool { - sendEnabled, found := k.getSendEnabled(store, denom) - if found { - return sendEnabled - } - - return defaultVal -} diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go deleted file mode 100644 index 61b535c3a..000000000 --- a/x/bank/keeper/view.go +++ /dev/null @@ -1,275 +0,0 @@ -package keeper - -import ( - "fmt" - - "cosmossdk.io/math" - "github.com/cometbft/cometbft/libs/log" - - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var _ ViewKeeper = (*BaseViewKeeper)(nil) - -// ViewKeeper defines a module interface that facilitates read only access to -// account balances. -type ViewKeeper interface { - ValidateBalance(ctx sdk.Context, addr sdk.AccAddress) error - HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool - - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetAccountsBalances(ctx sdk.Context) []types.Balance - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - LockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoin(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - - IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddress, cb func(coin sdk.Coin) (stop bool)) - IterateAllBalances(ctx sdk.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) -} - -// BaseViewKeeper implements a read only keeper implementation of ViewKeeper. -type BaseViewKeeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - ak types.AccountKeeper -} - -// NewBaseViewKeeper returns a new BaseViewKeeper. -func NewBaseViewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, ak types.AccountKeeper) BaseViewKeeper { - return BaseViewKeeper{ - cdc: cdc, - storeKey: storeKey, - ak: ak, - } -} - -// Logger returns a module-specific logger. -func (k BaseViewKeeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) -} - -// HasBalance returns whether or not an account has at least amt balance. -func (k BaseViewKeeper) HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool { - return k.GetBalance(ctx, addr, amt.Denom).IsGTE(amt) -} - -// GetAllBalances returns all the account balances for the given account address. -func (k BaseViewKeeper) GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - balances := sdk.NewCoins() - k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool { - balances = balances.Add(balance) - return false - }) - - return balances.Sort() -} - -// GetAccountsBalances returns all the accounts balances from the store. -func (k BaseViewKeeper) GetAccountsBalances(ctx sdk.Context) []types.Balance { - balances := make([]types.Balance, 0) - mapAddressToBalancesIdx := make(map[string]int) - - k.IterateAllBalances(ctx, func(addr sdk.AccAddress, balance sdk.Coin) bool { - idx, ok := mapAddressToBalancesIdx[addr.String()] - if ok { - // address is already on the set of accounts balances - balances[idx].Coins = balances[idx].Coins.Add(balance) - balances[idx].Coins.Sort() - return false - } - - accountBalance := types.Balance{ - Address: addr.String(), - Coins: sdk.NewCoins(balance), - } - balances = append(balances, accountBalance) - mapAddressToBalancesIdx[addr.String()] = len(balances) - 1 - return false - }) - - return balances -} - -// GetBalance returns the balance of a specific denomination for a given account -// by address. -func (k BaseViewKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - accountStore := k.getAccountStore(ctx, addr) - bz := accountStore.Get([]byte(denom)) - balance, err := UnmarshalBalanceCompat(k.cdc, bz, denom) - if err != nil { - panic(err) - } - - return balance -} - -// IterateAccountBalances iterates over the balances of a single account and -// provides the token balance to a callback. If true is returned from the -// callback, iteration is halted. -func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) { - accountStore := k.getAccountStore(ctx, addr) - - iterator := accountStore.Iterator(nil, nil) - defer sdk.LogDeferred(ctx.Logger(), func() error { return iterator.Close() }) - - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - balance, err := UnmarshalBalanceCompat(k.cdc, iterator.Value(), denom) - if err != nil { - panic(err) - } - - if cb(balance) { - break - } - } -} - -// IterateAllBalances iterates over all the balances of all accounts and -// denominations that are provided to a callback. If true is returned from the -// callback, iteration is halted. -func (k BaseViewKeeper) IterateAllBalances(ctx sdk.Context, cb func(sdk.AccAddress, sdk.Coin) bool) { - store := ctx.KVStore(k.storeKey) - balancesStore := prefix.NewStore(store, types.BalancesPrefix) - - iterator := balancesStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - address, denom, err := types.AddressAndDenomFromBalancesStore(iterator.Key()) - if err != nil { - k.Logger(ctx).With("key", iterator.Key(), "err", err).Error("failed to get address from balances store") - // TODO: revisit, for now, panic here to keep same behavior as in 0.42 - // ref: https://github.com/cosmos/cosmos-sdk/issues/7409 - panic(err) - } - - balance, err := UnmarshalBalanceCompat(k.cdc, iterator.Value(), denom) - if err != nil { - panic(err) - } - - if cb(address, balance) { - break - } - } -} - -// LockedCoins returns all the coins that are not spendable (i.e. locked) for an -// account by address. For standard accounts, the result will always be no coins. -// For vesting accounts, LockedCoins is delegated to the concrete vesting account -// type. -func (k BaseViewKeeper) LockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - acc := k.ak.GetAccount(ctx, addr) - if acc != nil { - vacc, ok := acc.(types.VestingAccount) - if ok { - return vacc.LockedCoins(ctx.BlockTime()) - } - } - - return sdk.NewCoins() -} - -// SpendableCoins returns the total balances of spendable coins for an account -// by address. If the account has no spendable coins, an empty Coins slice is -// returned. -func (k BaseViewKeeper) SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - spendable, _ := k.spendableCoins(ctx, addr) - return spendable -} - -// SpendableCoin returns the balance of specific denomination of spendable coins -// for an account by address. If the account has no spendable coin, a zero Coin -// is returned. -func (k BaseViewKeeper) SpendableCoin(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - balance := k.GetBalance(ctx, addr, denom) - locked := k.LockedCoins(ctx, addr) - return balance.SubAmount(locked.AmountOf(denom)) -} - -// spendableCoins returns the coins the given address can spend alongside the total amount of coins it holds. -// It exists for gas efficiency, in order to avoid to have to get balance multiple times. -func (k BaseViewKeeper) spendableCoins(ctx sdk.Context, addr sdk.AccAddress) (spendable, total sdk.Coins) { - total = k.GetAllBalances(ctx, addr) - locked := k.LockedCoins(ctx, addr) - - spendable, hasNeg := total.SafeSub(locked...) - if hasNeg { - spendable = sdk.NewCoins() - return - } - - return -} - -// ValidateBalance validates all balances for a given account address returning -// an error if any balance is invalid. It will check for vesting account types -// and validate the balances against the original vesting balances. -// -// CONTRACT: ValidateBalance should only be called upon genesis state. In the -// case of vesting accounts, balances may change in a valid manner that would -// otherwise yield an error from this call. -func (k BaseViewKeeper) ValidateBalance(ctx sdk.Context, addr sdk.AccAddress) error { - acc := k.ak.GetAccount(ctx, addr) - if acc == nil { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) - } - - balances := k.GetAllBalances(ctx, addr) - if !balances.IsValid() { - return fmt.Errorf("account balance of %s is invalid", balances) - } - - vacc, ok := acc.(types.VestingAccount) - if ok { - ogv := vacc.GetOriginalVesting() - if ogv.IsAnyGT(balances) { - return fmt.Errorf("vesting amount %s cannot be greater than total amount %s", ogv, balances) - } - } - - return nil -} - -// getAccountStore gets the account store of the given address. -func (k BaseViewKeeper) getAccountStore(ctx sdk.Context, addr sdk.AccAddress) prefix.Store { - store := ctx.KVStore(k.storeKey) - return prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) -} - -// getDenomAddressPrefixStore returns a prefix store that acts as a reverse index -// between a denomination and account balance for that denomination. -func (k BaseViewKeeper) getDenomAddressPrefixStore(ctx sdk.Context, denom string) prefix.Store { - return prefix.NewStore(ctx.KVStore(k.storeKey), types.CreateDenomAddressPrefix(denom)) -} - -// UnmarshalBalanceCompat unmarshal balance amount from storage, it's backward-compatible with the legacy format. -func UnmarshalBalanceCompat(cdc codec.BinaryCodec, bz []byte, denom string) (sdk.Coin, error) { - if err := sdk.ValidateDenom(denom); err != nil { - return sdk.Coin{}, err - } - - amount := math.ZeroInt() - if bz == nil { - return sdk.NewCoin(denom, amount), nil - } - - if err := amount.Unmarshal(bz); err != nil { - // try to unmarshal with the legacy format. - var balance sdk.Coin - if cdc.Unmarshal(bz, &balance) != nil { - // return with the original error - return sdk.Coin{}, err - } - return balance, nil - } - - return sdk.NewCoin(denom, amount), nil -} diff --git a/x/bank/migrations/v1/types.go b/x/bank/migrations/v1/types.go deleted file mode 100644 index a584be926..000000000 --- a/x/bank/migrations/v1/types.go +++ /dev/null @@ -1,70 +0,0 @@ -package v1 - -import ( - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/golang/protobuf/proto" -) - -const ( - // ModuleName defines the module name - ModuleName = "bank" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey defines the module's message routing key - RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName -) - -// KVStore keys -var ( - BalancesPrefix = []byte("balances") - SupplyKey = []byte{0x00} - DenomMetadataPrefix = []byte{0x1} -) - -// DenomMetadataKey returns the denomination metadata key. -func DenomMetadataKey(denom string) []byte { - d := []byte(denom) - return append(DenomMetadataPrefix, d...) -} - -// AddressFromBalancesStore returns an account address from a balances prefix -// store. The key must not contain the perfix BalancesPrefix as the prefix store -// iterator discards the actual prefix. -func AddressFromBalancesStore(key []byte) sdk.AccAddress { - kv.AssertKeyAtLeastLength(key, 1+v1auth.AddrLen) - addr := key[:v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.AccAddress(addr) -} - -// SupplyI defines an inflationary supply interface for modules that handle -// token supply. -// It is copy-pasted from: -// https://github.com/cosmos/cosmos-sdk/blob/v0.42.3/x/bank/exported/exported.go -// where we stripped off the unnecessary methods. -// -// It is used in the migration script, because we save this interface as an Any -// in the supply state. -// -// Deprecated. -type SupplyI interface { - proto.Message -} - -// RegisterInterfaces registers interfaces required for the v1 migrations. -func RegisterInterfaces(registry codectypes.InterfaceRegistry) { - registry.RegisterInterface( - "cosmos.bank.v1beta1.SupplyI", - (*SupplyI)(nil), - &types.Supply{}, - ) -} diff --git a/x/bank/migrations/v2/json.go b/x/bank/migrations/v2/json.go deleted file mode 100644 index 0c128db21..000000000 --- a/x/bank/migrations/v2/json.go +++ /dev/null @@ -1,32 +0,0 @@ -package v2 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// pruneZeroBalancesJSON removes the zero balance addresses from exported genesis. -func pruneZeroBalancesJSON(oldBalances []types.Balance) []types.Balance { - var balances []types.Balance - - for _, b := range oldBalances { - if !b.Coins.IsZero() { - b.Coins = sdk.NewCoins(b.Coins...) // prunes zero denom. - balances = append(balances, b) - } - } - - return balances -} - -// MigrateJSON accepts exported v0.40 x/bank genesis state and migrates it to -// v0.43 x/bank genesis state. The migration includes: -// - Prune balances & supply with zero coins (ref: https://github.com/cosmos/cosmos-sdk/pull/9229) -func MigrateJSON(oldState *types.GenesisState) *types.GenesisState { - return &types.GenesisState{ - Params: oldState.Params, - Balances: pruneZeroBalancesJSON(oldState.Balances), - Supply: sdk.NewCoins(oldState.Supply...), // NewCoins used here to remove zero coin denoms from supply. - DenomMetadata: oldState.DenomMetadata, - } -} diff --git a/x/bank/migrations/v2/json_test.go b/x/bank/migrations/v2/json_test.go deleted file mode 100644 index ddf908e01..000000000 --- a/x/bank/migrations/v2/json_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package v2_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v2bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig() - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - voter, err := sdk.AccAddressFromBech32("cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") - require.NoError(t, err) - bankGenState := &types.GenesisState{ - Balances: []types.Balance{ - { - Address: voter.String(), - Coins: sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(10)), - sdk.NewCoin("bar", sdk.NewInt(20)), - sdk.NewCoin("foobar", sdk.NewInt(0)), - }, - }, - }, - Supply: sdk.Coins{ - sdk.NewCoin("foo", sdk.NewInt(10)), - sdk.NewCoin("bar", sdk.NewInt(20)), - sdk.NewCoin("foobar", sdk.NewInt(0)), - sdk.NewCoin("barfoo", sdk.NewInt(0)), - }, - } - - migrated := v2bank.MigrateJSON(bankGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]interface{} - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - // Make sure about: - // - zero coin balances pruned. - // - zero supply denoms pruned. - expected := `{ - "balances": [ - { - "address": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", - "coins": [ - { - "amount": "20", - "denom": "bar" - }, - { - "amount": "10", - "denom": "foo" - } - ] - } - ], - "denom_metadata": [], - "params": { - "default_send_enabled": false, - "send_enabled": [] - }, - "send_enabled": [], - "supply": [ - { - "amount": "20", - "denom": "bar" - }, - { - "amount": "10", - "denom": "foo" - } - ] -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/bank/migrations/v2/keys.go b/x/bank/migrations/v2/keys.go deleted file mode 100644 index eadb02e9d..000000000 --- a/x/bank/migrations/v2/keys.go +++ /dev/null @@ -1,45 +0,0 @@ -package v2 - -import ( - "errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -const ( - ModuleName = "bank" -) - -var ( - SupplyKey = []byte{0x00} - BalancesPrefix = []byte{0x02} - DenomMetadataPrefix = []byte{0x1} - - ErrInvalidKey = errors.New("invalid key") -) - -func CreateAccountBalancesPrefix(addr []byte) []byte { - return append(BalancesPrefix, address.MustLengthPrefix(addr)...) -} - -func AddressFromBalancesStore(key []byte) (sdk.AccAddress, error) { - if len(key) == 0 { - return nil, ErrInvalidKey - } - - addrLen := key[0] - bound := int(addrLen) - - if len(key)-1 < bound { - return nil, ErrInvalidKey - } - - return key[1 : bound+1], nil -} - -// DenomMetadataKey returns the denomination metadata key. -func DenomMetadataKey(denom string) []byte { - d := []byte(denom) - return append(DenomMetadataPrefix, d...) -} diff --git a/x/bank/migrations/v2/store.go b/x/bank/migrations/v2/store.go deleted file mode 100644 index e92132dfc..000000000 --- a/x/bank/migrations/v2/store.go +++ /dev/null @@ -1,134 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/math" - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" - v1 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// migrateSupply migrates the supply to be stored by denom key instead in a -// single blob. -// ref: https://github.com/cosmos/cosmos-sdk/issues/7092 -func migrateSupply(store sdk.KVStore, cdc codec.BinaryCodec) error { - // Old supply was stored as a single blob under the SupplyKey. - var oldSupplyI v1.SupplyI - err := cdc.UnmarshalInterface(store.Get(v1.SupplyKey), &oldSupplyI) - if err != nil { - return err - } - - // We delete the single key holding the whole blob. - store.Delete(v1.SupplyKey) - - if oldSupplyI == nil { - return nil - } - - // We add a new key for each denom - supplyStore := prefix.NewStore(store, SupplyKey) - - // We're sure that SupplyI is a Supply struct, there's no other - // implementation. - oldSupply := oldSupplyI.(*types.Supply) - for i := range oldSupply.Total { - coin := oldSupply.Total[i] - coinBz, err := coin.Amount.Marshal() - if err != nil { - return err - } - - supplyStore.Set([]byte(coin.Denom), coinBz) - } - - return nil -} - -// migrateBalanceKeys migrate the balances keys to cater for variable-length -// addresses. -func migrateBalanceKeys(store sdk.KVStore, logger log.Logger) { - // old key is of format: - // prefix ("balances") || addrBytes (20 bytes) || denomBytes - // new key is of format - // prefix (0x02) || addrLen (1 byte) || addrBytes || denomBytes - oldStore := prefix.NewStore(store, v1.BalancesPrefix) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldStoreIter.Close() }) - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := v1.AddressFromBalancesStore(oldStoreIter.Key()) - denom := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := types.CreatePrefixedAccountStoreKey(addr, denom) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Change addresses to be length-prefixed. -// - Change balances prefix to 1 byte -// - Change supply to be indexed by denom -// - Prune balances & supply with zero coins (ref: https://github.com/cosmos/cosmos-sdk/pull/9229) -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - migrateBalanceKeys(store, ctx.Logger()) - - if err := pruneZeroBalances(store, cdc); err != nil { - return err - } - - if err := migrateSupply(store, cdc); err != nil { - return err - } - - return pruneZeroSupply(store) -} - -// pruneZeroBalances removes the zero balance addresses from balances store. -func pruneZeroBalances(store sdk.KVStore, cdc codec.BinaryCodec) error { - balancesStore := prefix.NewStore(store, BalancesPrefix) - iterator := balancesStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var balance sdk.Coin - if err := cdc.Unmarshal(iterator.Value(), &balance); err != nil { - return err - } - - if balance.IsZero() { - balancesStore.Delete(iterator.Key()) - } - } - return nil -} - -// pruneZeroSupply removes zero balance denom from supply store. -func pruneZeroSupply(store sdk.KVStore) error { - supplyStore := prefix.NewStore(store, SupplyKey) - iterator := supplyStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var amount math.Int - if err := amount.Unmarshal(iterator.Value()); err != nil { - return err - } - - if amount.IsZero() { - supplyStore.Delete(iterator.Key()) - } - } - - return nil -} diff --git a/x/bank/migrations/v2/store_test.go b/x/bank/migrations/v2/store_test.go deleted file mode 100644 index 4c4f237be..000000000 --- a/x/bank/migrations/v2/store_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package v2_test - -import ( - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - "cosmossdk.io/store/prefix" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v1bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - v2bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestSupplyMigration(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := sdk.NewKVStoreKey("bank") - ctx := testutil.DefaultContext(bankKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(bankKey) - - v1bank.RegisterInterfaces(encCfg.InterfaceRegistry) - - oldFooCoin := sdk.NewCoin("foo", sdk.NewInt(100)) - oldBarCoin := sdk.NewCoin("bar", sdk.NewInt(200)) - oldFooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) // to ensure the zero denom coins pruned. - - // Old supply was stored as a single blob under the `SupplyKey`. - var oldSupply v1bank.SupplyI - oldSupply = &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}} - oldSupplyBz, err := encCfg.Codec.MarshalInterface(oldSupply) - require.NoError(t, err) - store.Set(v1bank.SupplyKey, oldSupplyBz) - - // Run migration. - err = v2bank.MigrateStore(ctx, bankKey, encCfg.Codec) - require.NoError(t, err) - - // New supply is indexed by denom. - supplyStore := prefix.NewStore(store, types.SupplyKey) - bz := supplyStore.Get([]byte("foo")) - var amount math.Int - err = amount.Unmarshal(bz) - require.NoError(t, err) - - newFooCoin := sdk.Coin{ - Denom: "foo", - Amount: amount, - } - require.Equal(t, oldFooCoin, newFooCoin) - - bz = supplyStore.Get([]byte("bar")) - err = amount.Unmarshal(bz) - require.NoError(t, err) - - newBarCoin := sdk.Coin{ - Denom: "bar", - Amount: amount, - } - require.Equal(t, oldBarCoin, newBarCoin) - - // foobar shouldn't be existed in the store. - bz = supplyStore.Get([]byte("foobar")) - require.Nil(t, bz) -} - -func TestBalanceKeysMigration(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := sdk.NewKVStoreKey("bank") - ctx := testutil.DefaultContext(bankKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(bankKey) - - _, _, addr := testdata.KeyTestPubAddr() - - // set 10 foo coin - fooCoin := sdk.NewCoin("foo", sdk.NewInt(10)) - oldFooKey := append(append(v1bank.BalancesPrefix, addr...), []byte(fooCoin.Denom)...) - fooBz, err := encCfg.Codec.Marshal(&fooCoin) - require.NoError(t, err) - store.Set(oldFooKey, fooBz) - - // set 0 foobar coin - fooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) - oldKeyFooBar := append(append(v1bank.BalancesPrefix, addr...), []byte(fooBarCoin.Denom)...) - fooBarBz, err := encCfg.Codec.Marshal(&fooBarCoin) - require.NoError(t, err) - store.Set(oldKeyFooBar, fooBarBz) - require.NotNil(t, store.Get(oldKeyFooBar)) // before store migation zero values can also exist in store. - - err = v2bank.MigrateStore(ctx, bankKey, encCfg.Codec) - require.NoError(t, err) - - newKey := types.CreatePrefixedAccountStoreKey(addr, []byte(fooCoin.Denom)) - // -7 because we replaced "balances" with 0x02, - // +1 because we added length-prefix to address. - require.Equal(t, len(oldFooKey)-7+1, len(newKey)) - require.Nil(t, store.Get(oldFooKey)) - require.Equal(t, fooBz, store.Get(newKey)) - - newKeyFooBar := types.CreatePrefixedAccountStoreKey(addr, []byte(fooBarCoin.Denom)) - require.Nil(t, store.Get(newKeyFooBar)) // after migration zero balances pruned from store. -} diff --git a/x/bank/migrations/v3/keys.go b/x/bank/migrations/v3/keys.go deleted file mode 100644 index 1b7afe3f9..000000000 --- a/x/bank/migrations/v3/keys.go +++ /dev/null @@ -1,14 +0,0 @@ -package v3 - -var DenomAddressPrefix = []byte{0x03} - -// CreateDenomAddressPrefix creates a prefix for a reverse index of denomination -// to account balance for that denomination. -func CreateDenomAddressPrefix(denom string) []byte { - // we add a "zero" byte at the end - null byte terminator, to allow prefix denom prefix - // scan. Setting it is not needed (key[last] = 0) - because this is the default. - key := make([]byte, len(DenomAddressPrefix)+len(denom)+1) - copy(key, DenomAddressPrefix) - copy(key[len(DenomAddressPrefix):], denom) - return key -} diff --git a/x/bank/migrations/v3/store.go b/x/bank/migrations/v3/store.go deleted file mode 100644 index 036eeb3c8..000000000 --- a/x/bank/migrations/v3/store.go +++ /dev/null @@ -1,95 +0,0 @@ -package v3 - -import ( - "cosmossdk.io/store/prefix" - storetypes "cosmossdk.io/store/types" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// MigrateStore performs in-place store migrations from v0.43 to v0.45. The -// migration includes: -// -// - Migrate coin storage to save only amount. -// - Add an additional reverse index from denomination to address. -// - Remove duplicate denom from denom metadata store key. -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - err := addDenomReverseIndex(store, cdc, ctx.Logger()) - if err != nil { - return err - } - - return migrateDenomMetadata(store, ctx.Logger()) -} - -func addDenomReverseIndex(store sdk.KVStore, cdc codec.BinaryCodec, logger log.Logger) error { - oldBalancesStore := prefix.NewStore(store, v2.BalancesPrefix) - - oldBalancesIter := oldBalancesStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldBalancesIter.Close() }) - - denomPrefixStores := make(map[string]prefix.Store) // memoize prefix stores - - for ; oldBalancesIter.Valid(); oldBalancesIter.Next() { - var balance sdk.Coin - if err := cdc.Unmarshal(oldBalancesIter.Value(), &balance); err != nil { - return err - } - - addr, err := v2.AddressFromBalancesStore(oldBalancesIter.Key()) - if err != nil { - return err - } - - var coin sdk.DecCoin - if err := cdc.Unmarshal(oldBalancesIter.Value(), &coin); err != nil { - return err - } - - bz, err := coin.Amount.Marshal() - if err != nil { - return err - } - - newStore := prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) - newStore.Set([]byte(coin.Denom), bz) - - denomPrefixStore, ok := denomPrefixStores[balance.Denom] - if !ok { - denomPrefixStore = prefix.NewStore(store, CreateDenomAddressPrefix(balance.Denom)) - denomPrefixStores[balance.Denom] = denomPrefixStore - } - - // Store a reverse index from denomination to account address with a - // sentinel value. - denomPrefixStore.Set(address.MustLengthPrefix(addr), []byte{0}) - } - - return nil -} - -func migrateDenomMetadata(store sdk.KVStore, logger log.Logger) error { - oldDenomMetaDataStore := prefix.NewStore(store, v2.DenomMetadataPrefix) - - oldDenomMetaDataIter := oldDenomMetaDataStore.Iterator(nil, nil) - defer sdk.LogDeferred(logger, func() error { return oldDenomMetaDataIter.Close() }) - - for ; oldDenomMetaDataIter.Valid(); oldDenomMetaDataIter.Next() { - oldKey := oldDenomMetaDataIter.Key() - l := len(oldKey) / 2 - - newKey := make([]byte, len(types.DenomMetadataPrefix)+l) - // old key: prefix_bytes | denom_bytes | denom_bytes - copy(newKey, types.DenomMetadataPrefix) - copy(newKey[len(types.DenomMetadataPrefix):], oldKey[:l]) - store.Set(newKey, oldDenomMetaDataIter.Value()) - oldDenomMetaDataStore.Delete(oldKey) - } - - return nil -} diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go deleted file mode 100644 index c80222f5e..000000000 --- a/x/bank/migrations/v3/store_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package v3_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - - "cosmossdk.io/store/prefix" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - v2 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v2" - v3 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v3" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateStore(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := sdk.NewKVStoreKey("bank") - ctx := testutil.DefaultContext(bankKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(bankKey) - - addr := sdk.AccAddress([]byte("addr________________")) - prefixAccStore := prefix.NewStore(store, v2.CreateAccountBalancesPrefix(addr)) - - balances := sdk.NewCoins( - sdk.NewCoin("foo", sdk.NewInt(10000)), - sdk.NewCoin("bar", sdk.NewInt(20000)), - ) - - for _, b := range balances { - bz, err := encCfg.Codec.Marshal(&b) - require.NoError(t, err) - - prefixAccStore.Set([]byte(b.Denom), bz) - } - - require.NoError(t, v3.MigrateStore(ctx, bankKey, encCfg.Codec)) - - for _, b := range balances { - addrPrefixStore := prefix.NewStore(store, types.CreateAccountBalancesPrefix(addr)) - bz := addrPrefixStore.Get([]byte(b.Denom)) - var expected math.Int - require.NoError(t, expected.Unmarshal(bz)) - require.Equal(t, expected, b.Amount) - } - - for _, b := range balances { - denomPrefixStore := prefix.NewStore(store, v3.CreateDenomAddressPrefix(b.Denom)) - bz := denomPrefixStore.Get(address.MustLengthPrefix(addr)) - require.NotNil(t, bz) - } -} - -func TestMigrateDenomMetaData(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - bankKey := sdk.NewKVStoreKey("bank") - ctx := testutil.DefaultContext(bankKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(bankKey) - metaData := []types.Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {Denom: "uatom", Exponent: uint32(0), Aliases: []string{"microatom"}}, - {Denom: "matom", Exponent: uint32(3), Aliases: []string{"milliatom"}}, - {Denom: "atom", Exponent: uint32(6), Aliases: nil}, - }, - Base: "uatom", - Display: "atom", - }, - { - Name: "Token", - Symbol: "TOKEN", - Description: "The native staking token of the Token Hub.", - DenomUnits: []*types.DenomUnit{ - {Denom: "1token", Exponent: uint32(5), Aliases: []string{"decitoken"}}, - {Denom: "2token", Exponent: uint32(4), Aliases: []string{"centitoken"}}, - {Denom: "3token", Exponent: uint32(7), Aliases: []string{"dekatoken"}}, - }, - Base: "utoken", - Display: "token", - }, - } - denomMetadataStore := prefix.NewStore(store, v2.DenomMetadataPrefix) - - for i := range []int{0, 1} { - // keys before 0.45 had denom two times in the key - key := append([]byte{}, []byte(metaData[i].Base)...) - key = append(key, []byte(metaData[i].Base)...) - bz, err := encCfg.Codec.Marshal(&metaData[i]) - require.NoError(t, err) - denomMetadataStore.Set(key, bz) - } - - require.NoError(t, v3.MigrateStore(ctx, bankKey, encCfg.Codec)) - - denomMetadataStore = prefix.NewStore(store, v2.DenomMetadataPrefix) - denomMetadataIter := denomMetadataStore.Iterator(nil, nil) - defer denomMetadataIter.Close() - for i := 0; denomMetadataIter.Valid(); denomMetadataIter.Next() { - var result types.Metadata - newKey := denomMetadataIter.Key() - - // make sure old entry is deleted - oldKey := append(newKey, newKey[0:]...) - bz := denomMetadataStore.Get(oldKey) - require.Nil(t, bz) - - require.Equal(t, string(newKey), metaData[i].Base, "idx: %d", i) - bz = denomMetadataStore.Get(denomMetadataIter.Key()) - require.NotNil(t, bz) - err := encCfg.Codec.Unmarshal(bz, &result) - require.NoError(t, err) - assertMetaDataEqual(t, metaData[i], result) - i++ - } -} - -func assertMetaDataEqual(t *testing.T, expected, actual types.Metadata) { - require.Equal(t, expected.GetBase(), actual.GetBase()) - require.Equal(t, expected.GetDisplay(), actual.GetDisplay()) - require.Equal(t, expected.GetDescription(), actual.GetDescription()) - require.Equal(t, expected.GetDenomUnits()[1].GetDenom(), actual.GetDenomUnits()[1].GetDenom()) - require.Equal(t, expected.GetDenomUnits()[1].GetExponent(), actual.GetDenomUnits()[1].GetExponent()) - require.Equal(t, expected.GetDenomUnits()[1].GetAliases(), actual.GetDenomUnits()[1].GetAliases()) -} diff --git a/x/bank/migrations/v4/gen_state.go b/x/bank/migrations/v4/gen_state.go deleted file mode 100644 index f81f3b672..000000000 --- a/x/bank/migrations/v4/gen_state.go +++ /dev/null @@ -1,14 +0,0 @@ -package v4 - -import ( - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// MigrateGenState accepts exported v0.43 x/bank genesis state and migrates it to -// v0.47 x/bank genesis state. The migration includes: -// - Move the SendEnabled entries from Params to the new GenesisState.SendEnabled field. -func MigrateGenState(oldState *types.GenesisState) *types.GenesisState { - newState := *oldState - newState.MigrateSendEnabled() - return &newState -} diff --git a/x/bank/migrations/v4/gen_state_test.go b/x/bank/migrations/v4/gen_state_test.go deleted file mode 100644 index 19b15e5a1..000000000 --- a/x/bank/migrations/v4/gen_state_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - sdk "github.com/cosmos/cosmos-sdk/types" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMigrateGenState(t *testing.T) { - tests := []struct { - name string - oldState *types.GenesisState - newState *types.GenesisState - }{ - { - name: "Balances supply metadata all unchanged", - oldState: &types.GenesisState{ - Params: types.Params{}, - Balances: []types.Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, - DenomMetadata: []types.Metadata{{ - Description: "metadesk", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - SendEnabled: []types.SendEnabled{}, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - Balances: []types.Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, - DenomMetadata: []types.Metadata{{ - Description: "metadesk", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - SendEnabled: []types.SendEnabled{}, - }, - }, - - { - name: "default send enabled true not changed", - oldState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: true}, - }, - newState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: true}, - }, - }, - { - name: "default send enabled false not changed", - oldState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: false, SendEnabled: []*types.SendEnabled{}}, - }, - newState: &types.GenesisState{ - Params: types.Params{DefaultSendEnabled: false}, - }, - }, - { - name: "send enabled entries moved", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - { - name: "params entries added to existing", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - }, - { - name: "conflicting params ignored", - oldState: &types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "staycoin", Enabled: false}, - }, - }, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - newState: &types.GenesisState{ - Params: types.Params{}, - SendEnabled: []types.SendEnabled{ - {Denom: "staycoin", Enabled: true}, - }, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - actual := v4.MigrateGenState(tc.oldState) - assert.Equal(t, tc.newState, actual) - }) - } - - t.Run("ensure original not changed", func(t *testing.T) { - origState := types.GenesisState{ - Params: types.Params{ - SendEnabled: []*types.SendEnabled{ - {Denom: "movecointrue", Enabled: true}, - {Denom: "movecoinfalse", Enabled: false}, - }, - }, - } - _ = v4.MigrateGenState(&origState) - assert.Len(t, origState.Params.SendEnabled, 2) - }) -} diff --git a/x/bank/migrations/v4/store.go b/x/bank/migrations/v4/store.go deleted file mode 100644 index fa8b16d18..000000000 --- a/x/bank/migrations/v4/store.go +++ /dev/null @@ -1,36 +0,0 @@ -package v4 - -import ( - storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -const ModuleName = "bank" - -var ParamsKey = []byte{0x05} - -// MigrateStore migrates the x/bank module state from the consensus version 3 to -// version 4. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/bank -// module state. -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - if err := currParams.Validate(); err != nil { - return err - } - - bz, err := cdc.Marshal(&currParams) - if err != nil { - return err - } - - store.Set(ParamsKey, bz) - - return nil -} diff --git a/x/bank/migrations/v4/store_test.go b/x/bank/migrations/v4/store_test.go deleted file mode 100644 index b9d2c035c..000000000 --- a/x/bank/migrations/v4/store_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package v4_test - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/bank/exported" - v4 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v4" - "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/require" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -func TestMigrate(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(bank.AppModuleBasic{}) - cdc := encCfg.Codec - - storeKey := sdk.NewKVStoreKey(v4.ModuleName) - tKey := sdk.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(storeKey, tKey) - store := ctx.KVStore(storeKey) - - legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v4.MigrateStore(ctx, storeKey, legacySubspace, cdc)) - - var res types.Params - bz := store.Get(v4.ParamsKey) - require.NoError(t, cdc.Unmarshal(bz, &res)) - require.Equal(t, legacySubspace.ps, res) -} diff --git a/x/bank/module.go b/x/bank/module.go index edd2db3c6..3359c71ba 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -1,260 +1,46 @@ package bank import ( - "context" - "encoding/json" - "fmt" - "time" - - modulev1 "cosmossdk.io/api/cosmos/bank/module/v1" - "cosmossdk.io/core/appmodule" - "cosmossdk.io/depinject" - abci "github.com/cometbft/cometbft/abci/types" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - store "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - "github.com/cosmos/cosmos-sdk/x/bank/exported" + "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/bank/keeper" - v1bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v1" - "github.com/cosmos/cosmos-sdk/x/bank/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) -// ConsensusVersion defines the current x/bank module consensus version. -const ConsensusVersion = 4 - var ( - _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} _ module.AppModuleSimulation = AppModule{} ) -// AppModuleBasic defines the basic application module used by the bank module. +// AppModuleBasic defines the basic application module used by the distribution module. type AppModuleBasic struct { - cdc codec.Codec -} - -// Name returns the bank module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } - -// RegisterLegacyAminoCodec registers the bank 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 -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the bank module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return data.Validate() -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the bank module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the bank module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.NewTxCmd() -} - -// GetQueryCmd returns no root query command for the bank module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// RegisterInterfaces registers interfaces and implementations of the bank module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) - - // Register legacy interfaces for migration scripts. - v1bank.RegisterInterfaces(registry) + bank.AppModuleBasic } // AppModule implements an application module for the bank module. type AppModule struct { - AppModuleBasic - + bank.AppModule keeper keeper.Keeper accountKeeper types.AccountKeeper - - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace -} - -var _ appmodule.AppModule = AppModule{} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (am AppModule) IsOnePerModuleType() {} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), am.keeper) - - m := keeper.NewMigrator(am.keeper.(keeper.BaseKeeper), am.legacySubspace) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 1 to 2: %v", err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 2 to 3: %v", err)) - } - - if err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil { - panic(fmt.Sprintf("failed to migrate x/bank from version 3 to 4: %v", err)) - } } // NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, ss exported.Subspace) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: accountKeeper, - legacySubspace: ss, + AppModule: bank.NewAppModule(cdc, keeper, accountKeeper), + keeper: keeper, + accountKeeper: accountKeeper, } } -// Name returns the bank module's name. -func (AppModule) Name() string { return types.ModuleName } - -// RegisterInvariants registers the bank module invariants. -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// QuerierRoute returns the bank module's querier route name. -func (AppModule) QuerierRoute() string { return types.RouterKey } - -// InitGenesis performs genesis initialization for the bank module. It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { - start := time.Now() - var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal") - - am.keeper.InitGenesis(ctx, &genesisState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the bank -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } - -// AppModuleSimulation functions - -// GenerateGenesisState creates a randomized GenState of the bank module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalMsgs returns msgs used for governance proposals for simulations. -func (AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { - return simulation.ProposalMsgs() -} - -// RegisterStoreDecoder registers a decoder for supply module's types -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.accountKeeper, am.keeper, - ) -} - -// App Wiring Setup - -func init() { - appmodule.Register(&modulev1.Module{}, - appmodule.Provide(ProvideModule), - ) -} - -type BankInputs struct { - depinject.In - - Config *modulev1.Module - Cdc codec.Codec - Key *store.KVStoreKey - - AccountKeeper types.AccountKeeper - - // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace exported.Subspace `optional:"true"` -} - -type BankOutputs struct { - depinject.Out - - BankKeeper keeper.BaseKeeper - Module appmodule.AppModule -} - -func ProvideModule(in BankInputs) BankOutputs { - // Configure blocked module accounts. - // - // Default behavior for blockedAddresses is to regard any module mentioned in - // AccountKeeper's module account permissions as blocked. - blockedAddresses := make(map[string]bool) - if len(in.Config.BlockedModuleAccountsOverride) > 0 { - for _, moduleName := range in.Config.BlockedModuleAccountsOverride { - blockedAddresses[authtypes.NewModuleAddress(moduleName).String()] = true - } - } else { - for _, permission := range in.AccountKeeper.GetModulePermissions() { - blockedAddresses[permission.GetAddress().String()] = true - } - } - - // default to governance authority if not provided - authority := authtypes.NewModuleAddress(govtypes.ModuleName) - if in.Config.Authority != "" { - authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) - } - - bankKeeper := keeper.NewBaseKeeper( - in.Cdc, - in.Key, - in.AccountKeeper, - blockedAddresses, - authority.String(), - ) - m := NewAppModule(in.Cdc, bankKeeper, in.AccountKeeper, in.LegacySubspace) +// RegisterServices registers module services. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) - return BankOutputs{BankKeeper: bankKeeper, Module: m} + // TODO: Unused bank migration + // m := keeper.NewMigrator(am.keeper.(keeper.BaseKeeper)) + // cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) } diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go deleted file mode 100644 index 8592b08a3..000000000 --- a/x/bank/simulation/genesis.go +++ /dev/null @@ -1,99 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// RandomGenesisDefaultSendEnabledParam computes randomized allow all send transfers param for the bank module -func RandomGenesisDefaultSendEnabledParam(r *rand.Rand) bool { - // 90% chance of transfers being enabled or P(a) = 0.9 for success - return r.Int63n(100) < 90 -} - -// RandomGenesisSendEnabled creates randomized values for the SendEnabled slice. -func RandomGenesisSendEnabled(r *rand.Rand) []types.SendEnabled { - rv := make([]types.SendEnabled, 0, 2) - // 60% of the time, add a denom specific record. - if r.Int63n(100) < 60 { - // 75% of the those times, set send enabled to true. - bondEnabled := r.Int63n(100) < 75 - rv = append(rv, types.SendEnabled{Denom: sdk.DefaultBondDenom, Enabled: bondEnabled}) - } - // Probabilities: - // P(a) = 60.0% = There's SendEnable entry for the bond denom = .600 - // P(a)' = 40.0% = There is NOT a SendEnable entry for the bond denom = 1 - P(a) = 1 - .600 = .400 - // P(b) = 75.0% = The SendEnable entry is true (if there is such an entry) = .750 - // P(b)' = 25.0% = The SendEnable entry is false (if there is such an entry) = 1 - P(b) = 1 - .750 = .250 - // P(c) = 90.0% = The default send enabled is true (defined in RandomGenesisDefaultSendEnabledParam) = .900 - // P(c)' = 10.0% = The default send enabled is false = 1 - P(c) = 1 - .900 = .100 - // - // P(st) = 45.0% = There's a SendEnable entry that's true = P(a)*P(b) = .600*.750 = .450 - // P(sf) = 15.0% = There's a SendEnable entry that's false = P(a)*P(b)' = .600*.250 = .150 - // - // P(a'c) = 36.0% = No SendEnabled entry AND default is true = P(a)'*P(c) = .400*.900 = .360 - // P(a'c') = 4.0% = No SendEnabled entry AND default is false = P(a)'*P(c)' = .400*.100 = .040 - // P(stc) = 40.5% = SendEnabled entry is true AND default is true = P(st)*P(c) = .450*.900 = .405 - // P(stc') = 4.5% = SendEnabled entry is true AND default is false = P(st)*P(c)' = .450*.100 = .045 - // P(sfc) = 13.5% = SendEnabled entry is false AND default is true = P(sf)*P(c) = .150*.900 = .135 - // P(sfc') = 1.5% = SendEnabled entry is false AND default is false = P(sf)*P(c)' = .150*.100 = .015 - // - // P(set) = 42.0% = SendEnabled entry that equals the default = P(stc) + P(sfc') = .405 + .015 = .420 - // P(sef) = 18.0% = SendEnabled entry that does not equal the default = P(stc') + P(sfc) = .045 + .135 = .180 - // - // P(t) = 81.0% = Bond denom is sendable = P(a'c) + P(st) = .360 + .450 = .810 - // P(f) = 19.0% = Bond demon is NOT sendable = P(a'c') + P(sf) = .040 + .150 = .190 - - return rv -} - -// RandomGenesisBalances returns a slice of account balances. Each account has -// a balance of simState.InitialStake for sdk.DefaultBondDenom. -func RandomGenesisBalances(simState *module.SimulationState) []types.Balance { - genesisBalances := []types.Balance{} - - for _, acc := range simState.Accounts { - genesisBalances = append(genesisBalances, types.Balance{ - Address: acc.Address.String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, simState.InitialStake)), - }) - } - - return genesisBalances -} - -// RandomizedGenState generates a random GenesisState for bank -func RandomizedGenState(simState *module.SimulationState) { - var defaultSendEnabledParam bool - simState.AppParams.GetOrGenerate( - simState.Cdc, string(types.KeyDefaultSendEnabled), &defaultSendEnabledParam, simState.Rand, - func(r *rand.Rand) { defaultSendEnabledParam = RandomGenesisDefaultSendEnabledParam(r) }, - ) - - sendEnabled := RandomGenesisSendEnabled(simState.Rand) - - numAccs := int64(len(simState.Accounts)) - totalSupply := simState.InitialStake.Mul(sdk.NewInt((numAccs + simState.NumBonded))) - supply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply)) - - bankGenesis := types.GenesisState{ - Params: types.NewParams(defaultSendEnabledParam), - Balances: RandomGenesisBalances(simState), - Supply: supply, - SendEnabled: sendEnabled, - } - - paramsBytes, err := json.MarshalIndent(&bankGenesis.Params, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", paramsBytes) - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&bankGenesis) -} diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go deleted file mode 100644 index 7782b6cd7..000000000 --- a/x/bank/simulation/genesis_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package simulation_test - -import ( - "encoding/json" - "math/rand" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. -// Abonormal scenarios are not tested here. -func TestRandomizedGenState(t *testing.T) { - interfaceRegistry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - s := rand.NewSource(1) - r := rand.New(s) - - simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), - } - - simulation.RandomizedGenState(&simState) - - var bankGenesis types.GenesisState - simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &bankGenesis) - - assert.Equal(t, true, bankGenesis.Params.GetDefaultSendEnabled(), "Params.GetDefaultSendEnabled") - assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") - if assert.Len(t, bankGenesis.Balances, 3) { - assert.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", bankGenesis.Balances[2].GetAddress().String(), "Balances[2] address") - assert.Equal(t, "1000stake", bankGenesis.Balances[2].GetCoins().String(), "Balances[2] coins") - } - assert.Equal(t, "6000stake", bankGenesis.Supply.String(), "Supply") - if assert.Len(t, bankGenesis.SendEnabled, 1, "SendEnabled") { - assert.Equal(t, true, bankGenesis.SendEnabled[0].Enabled, "SendEnabled[0] value") - } -} - -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. -func TestRandomizedGenState1(t *testing.T) { - interfaceRegistry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - - s := rand.NewSource(1) - r := rand.New(s) - - // all these tests will panic - tests := []struct { - simState module.SimulationState - panicMsg string - }{ - { // panic => reason: incomplete initialization of the simState - module.SimulationState{}, "invalid memory address or nil pointer dereference"}, - { // panic => reason: incomplete initialization of the simState - module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - }, "assignment to entry in nil map"}, - } - - for _, tt := range tests { - require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) - } -} diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go deleted file mode 100644 index 0e92eb711..000000000 --- a/x/bank/simulation/operations.go +++ /dev/null @@ -1,415 +0,0 @@ -package simulation - -import ( - "math/rand" - - distributiontypes "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// Simulation operation weights constants -const ( - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec - OpWeightMsgMultiSend = "op_weight_msg_multisend" //nolint:gosec - DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend - DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend -) - -// WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk keeper.Keeper, -) simulation.WeightedOperations { - var weightMsgSend, weightMsgMultiSend int - appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, - func(_ *rand.Rand) { - weightMsgSend = DefaultWeightMsgSend - }, - ) - - appParams.GetOrGenerate(cdc, OpWeightMsgMultiSend, &weightMsgMultiSend, nil, - func(_ *rand.Rand) { - weightMsgMultiSend = DefaultWeightMsgMultiSend - }, - ) - - return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgSend, - SimulateMsgSend(ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgMultiSend, - SimulateMsgMultiSend(ak, bk), - ), - } -} - -// SimulateMsgSend tests and runs a single msg send where both -// accounts already exist. -func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - from, to, coins, skip := randomSendFields(r, ctx, accs, bk, ak) - - // if coins slice is empty, we can not create valid types.MsgSend - if len(coins) == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgSend, "empty coins slice"), nil, nil - } - - // Check send_enabled status of each coin denom - if err := bk.IsSendEnabledCoins(ctx, coins...); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgSend, err.Error()), nil, nil - } - - if skip { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgSend, "skip all transfers"), nil, nil - } - - msg := types.NewMsgSend(from.Address, to.Address, coins) - - err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "invalid transfers"), nil, err - } - - return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } -} - -// SimulateMsgSendToModuleAccount tests and runs a single msg send where both -// accounts already exist. -func SimulateMsgSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, moduleAccCount int) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - from := accs[0] - - to := getModuleAccounts(ak, ctx, moduleAccCount)[0] - - spendable := bk.SpendableCoins(ctx, from.Address) - coins := simtypes.RandSubsetCoins(r, spendable) - // if coins slice is empty, we can not create valid types.MsgSend - if len(coins) == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgSend, "empty coins slice"), nil, nil - } - - // Check send_enabled status of each coin denom - if err := bk.IsSendEnabledCoins(ctx, coins...); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgSend, err.Error()), nil, nil - } - - msg := types.NewMsgSend(from.Address, to.Address, coins) - - err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{from.PrivKey}) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "invalid transfers"), nil, err - } - - return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } -} - -// sendMsgSend sends a transaction with a MsgSend from a provided random account. -func sendMsgSend( - r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, - msg *types.MsgSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, -) error { - var ( - fees sdk.Coins - err error - ) - - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return err - } - - account := ak.GetAccount(ctx, from) - spendable := bk.SpendableCoins(ctx, account.GetAddress()) - - coins, hasNeg := spendable.SafeSub(msg.Amount...) - if !hasNeg { - fees, err = simtypes.RandomFees(r, ctx, coins) - if err != nil { - return err - } - } - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig - tx, err := simtestutil.GenSignedMockTx( - r, - txGen, - []sdk.Msg{msg}, - fees, - simtestutil.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - privkeys..., - ) - if err != nil { - return err - } - - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) - if err != nil { - return err - } - - return nil -} - -// SimulateMsgMultiSend tests and runs a single msg multisend, with randomized, capped number of inputs/outputs. -// all accounts in msg fields exist in state -func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - // random number of inputs/outputs between [1, 3] - inputs := make([]types.Input, r.Intn(1)+1) //nolint:staticcheck // SA4030: (*math/rand.Rand).Intn(n) generates a random value 0 <= x < n; that is, the generated values don't include n; r.Intn(1) therefore always returns 0 - outputs := make([]types.Output, r.Intn(3)+1) - - // collect signer privKeys - privs := make([]cryptotypes.PrivKey, len(inputs)) - - // use map to check if address already exists as input - usedAddrs := make(map[string]bool) - - var totalSentCoins sdk.Coins - for i := range inputs { - // generate random input fields, ignore to address - from, _, coins, skip := randomSendFields(r, ctx, accs, bk, ak) - - // make sure account is fresh and not used in previous input - for usedAddrs[from.Address.String()] { - from, _, coins, skip = randomSendFields(r, ctx, accs, bk, ak) - } - - if skip { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgMultiSend, "skip all transfers"), nil, nil - } - - // set input address in used address map - usedAddrs[from.Address.String()] = true - - // set signer privkey - privs[i] = from.PrivKey - - // set next input and accumulate total sent coins - inputs[i] = types.NewInput(from.Address, coins) - totalSentCoins = totalSentCoins.Add(coins...) - } - - // Check send_enabled status of each sent coin denom - if err := bk.IsSendEnabledCoins(ctx, totalSentCoins...); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgMultiSend, err.Error()), nil, nil - } - - for o := range outputs { - outAddr, _ := simtypes.RandomAcc(r, accs) - - var outCoins sdk.Coins - // split total sent coins into random subsets for output - if o == len(outputs)-1 { - outCoins = totalSentCoins - } else { - // take random subset of remaining coins for output - // and update remaining coins - outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) - totalSentCoins = totalSentCoins.Sub(outCoins...) - } - - outputs[o] = types.NewOutput(outAddr.Address, outCoins) - } - - // remove any output that has no coins - - for i := 0; i < len(outputs); { - if outputs[i].Coins.Empty() { - outputs[i] = outputs[len(outputs)-1] - outputs = outputs[:len(outputs)-1] - } else { - // continue onto next coin - i++ - } - } - - msg := &types.MsgMultiSend{ - Inputs: inputs, - Outputs: outputs, - } - err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "invalid transfers"), nil, err - } - - return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } -} - -// SimulateMsgMultiSendToModuleAccount sends coins to Module Accounts -func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keeper, moduleAccCount int) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - inputs := make([]types.Input, 2) - outputs := make([]types.Output, moduleAccCount) - // collect signer privKeys - privs := make([]cryptotypes.PrivKey, len(inputs)) - var totalSentCoins sdk.Coins - for i := range inputs { - sender := accs[i] - privs[i] = sender.PrivKey - spendable := bk.SpendableCoins(ctx, sender.Address) - coins := simtypes.RandSubsetCoins(r, spendable) - inputs[i] = types.NewInput(sender.Address, coins) - totalSentCoins = totalSentCoins.Add(coins...) - } - if err := bk.IsSendEnabledCoins(ctx, totalSentCoins...); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgMultiSend, err.Error()), nil, nil - } - moduleAccounts := getModuleAccounts(ak, ctx, moduleAccCount) - for i := range outputs { - var outCoins sdk.Coins - // split total sent coins into random subsets for output - if i == len(outputs)-1 { - outCoins = totalSentCoins - } else { - // take random subset of remaining coins for output - // and update remaining coins - outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) - totalSentCoins = totalSentCoins.Sub(outCoins...) - } - outputs[i] = types.NewOutput(moduleAccounts[i].Address, outCoins) - } - // remove any output that has no coins - for i := 0; i < len(outputs); { - if outputs[i].Coins.Empty() { - outputs[i] = outputs[len(outputs)-1] - outputs = outputs[:len(outputs)-1] - } else { - // continue onto next coin - i++ - } - } - msg := &types.MsgMultiSend{ - Inputs: inputs, - Outputs: outputs, - } - err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "invalid transfers"), nil, err - } - return simtypes.NewOperationMsg(msg, true, "", nil), nil, nil - } -} - -// sendMsgMultiSend sends a transaction with a MsgMultiSend from a provided random -// account. -func sendMsgMultiSend( - r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, - msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, -) error { - accountNumbers := make([]uint64, len(msg.Inputs)) - sequenceNumbers := make([]uint64, len(msg.Inputs)) - for i := 0; i < len(msg.Inputs); i++ { - addr := sdk.MustAccAddressFromBech32(msg.Inputs[i].Address) - acc := ak.GetAccount(ctx, addr) - accountNumbers[i] = acc.GetAccountNumber() - sequenceNumbers[i] = acc.GetSequence() - } - var ( - fees sdk.Coins - err error - ) - addr := sdk.MustAccAddressFromBech32(msg.Inputs[0].Address) - // feePayer is the first signer, i.e. first input address - feePayer := ak.GetAccount(ctx, addr) - spendable := bk.SpendableCoins(ctx, feePayer.GetAddress()) - coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins...) - if !hasNeg { - fees, err = simtypes.RandomFees(r, ctx, coins) - if err != nil { - return err - } - } - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig - tx, err := simtestutil.GenSignedMockTx( - r, - txGen, - []sdk.Msg{msg}, - fees, - simtestutil.DefaultGenTxGas, - chainID, - accountNumbers, - sequenceNumbers, - privkeys..., - ) - if err != nil { - return err - } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) - if err != nil { - return err - } - return nil -} - -// randomSendFields returns the sender and recipient simulation accounts as well -// as the transferred amount. -func randomSendFields( - r *rand.Rand, ctx sdk.Context, accs []simtypes.Account, bk keeper.Keeper, ak types.AccountKeeper, -) (simtypes.Account, simtypes.Account, sdk.Coins, bool) { - from, _ := simtypes.RandomAcc(r, accs) - to, _ := simtypes.RandomAcc(r, accs) - - // disallow sending money to yourself - for from.PubKey.Equals(to.PubKey) { - to, _ = simtypes.RandomAcc(r, accs) - } - - acc := ak.GetAccount(ctx, from.Address) - if acc == nil { - return from, to, nil, true - } - - spendable := bk.SpendableCoins(ctx, acc.GetAddress()) - - sendCoins := simtypes.RandSubsetCoins(r, spendable) - if sendCoins.Empty() { - return from, to, nil, true - } - - return from, to, sendCoins, false -} - -func getModuleAccounts(ak types.AccountKeeper, ctx sdk.Context, moduleAccCount int) []simtypes.Account { - moduleAccounts := make([]simtypes.Account, moduleAccCount) - - for i := 0; i < moduleAccCount; i++ { - acc := ak.GetModuleAccount(ctx, distributiontypes.ModuleName) - mAcc := simtypes.Account{ - Address: acc.GetAddress(), - PrivKey: nil, - ConsKey: nil, - PubKey: acc.GetPubKey(), - } - moduleAccounts[i] = mAcc - } - - return moduleAccounts -} diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go deleted file mode 100644 index e7af77508..000000000 --- a/x/bank/simulation/operations_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package simulation_test - -import ( - "math/rand" - "testing" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/suite" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - _ "github.com/cosmos/cosmos-sdk/x/auth" - _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" - _ "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/cosmos/cosmos-sdk/x/bank/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" - "github.com/cosmos/cosmos-sdk/x/bank/types" - _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/params" - _ "github.com/cosmos/cosmos-sdk/x/staking" -) - -type SimTestSuite struct { - suite.Suite - - ctx sdk.Context - accountKeeper types.AccountKeeper - bankKeeper keeper.Keeper - cdc codec.Codec - app *runtime.App -} - -func (suite *SimTestSuite) SetupTest() { - var ( - appBuilder *runtime.AppBuilder - err error - ) - suite.app, err = simtestutil.Setup(configurator.NewAppConfig( - configurator.AuthModule(), - configurator.ParamsModule(), - configurator.BankModule(), - configurator.StakingModule(), - configurator.ConsensusModule(), - configurator.TxModule(), - ), &suite.accountKeeper, &suite.bankKeeper, &suite.cdc, &appBuilder) - - suite.NoError(err) - - suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) -} - -// TestWeightedOperations tests the weights of the operations. -func (suite *SimTestSuite) TestWeightedOperations() { - cdc := suite.cdc - appParams := make(simtypes.AppParams) - - weightesOps := simulation.WeightedOperations(appParams, cdc, suite.accountKeeper, suite.bankKeeper) - - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accs := suite.getTestingAccounts(r, 3) - - expected := []struct { - weight int - opMsgRoute string - opMsgName string - }{ - {100, types.ModuleName, types.TypeMsgSend}, - {10, types.ModuleName, types.TypeMsgMultiSend}, - } - - for i, w := range weightesOps { - operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "") - suite.Require().NoError(err) - - // the following checks are very much dependent from the ordering of the output given - // by WeightedOperations. if the ordering in WeightedOperations changes some tests - // will fail - suite.Require().Equal(expected[i].weight, w.Weight(), "weight should be the same") - suite.Require().Equal(expected[i].opMsgRoute, operationMsg.Route, "route should be the same") - suite.Require().Equal(expected[i].opMsgName, operationMsg.Name, "operation Msg name should be the same") - } -} - -// TestSimulateMsgSend tests the normal scenario of a valid message of type TypeMsgSend. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgSend() { - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgSend(suite.accountKeeper, suite.bankKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().NoError(err) - - var msg types.MsgSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().True(operationMsg.OK) - suite.Require().Equal("65337742stake", msg.Amount.String()) - suite.Require().Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.FromAddress) - suite.Require().Equal("cosmos1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7u4x9a0", msg.ToAddress) - suite.Require().Equal(types.TypeMsgSend, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -// TestSimulateMsgSend tests the normal scenario of a valid message of type TypeMsgMultiSend. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgMultiSend() { - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgMultiSend(suite.accountKeeper, suite.bankKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - require := suite.Require() - require.NoError(err) - - var msg types.MsgMultiSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - require.True(operationMsg.OK) - require.Len(msg.Inputs, 1) - require.Equal("cosmos1tnh2q55v8wyygtt9srz5safamzdengsnqeycj3", msg.Inputs[0].Address) - require.Equal("114949958stake", msg.Inputs[0].Coins.String()) - require.Len(msg.Outputs, 2) - require.Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.Outputs[1].Address) - require.Equal("107287087stake", msg.Outputs[1].Coins.String()) - require.Equal(types.TypeMsgMultiSend, msg.Type()) - require.Equal(types.ModuleName, msg.Route()) - require.Len(futureOperations, 0) -} - -func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() { - const ( - accCount = 1 - moduleAccCount = 1 - ) - - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, accCount) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, moduleAccCount) - - s = rand.NewSource(1) - r = rand.New(s) - - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().Error(err) - - var msg types.MsgSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().False(operationMsg.OK) - suite.Require().Equal(operationMsg.Comment, "invalid transfers") - suite.Require().Equal(types.TypeMsgSend, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() { - const ( - accCount = 2 - mAccCount = 2 - ) - - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, accCount) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgMultiSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, mAccCount) - - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().Error(err) - - var msg types.MsgMultiSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().False(operationMsg.OK) // sending tokens to a module account should fail - suite.Require().Equal(operationMsg.Comment, "invalid transfers") - suite.Require().Equal(types.TypeMsgMultiSend, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { - accounts := simtypes.RandomAccounts(r, n) - - initAmt := sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) - initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt)) - - // add coins to the accounts - for _, account := range accounts { - acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address) - suite.accountKeeper.SetAccount(suite.ctx, acc) - suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, suite.ctx, account.Address, initCoins)) - } - - return accounts -} - -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go deleted file mode 100644 index 5a63b8632..000000000 --- a/x/bank/simulation/proposals.go +++ /dev/null @@ -1,43 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// Simulation operation weights constants -const ( - DefaultWeightMsgUpdateParams int = 100 - - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec -) - -// ProposalMsgs defines the module weighted proposals' contents -func ProposalMsgs() []simtypes.WeightedProposalMsg { - return []simtypes.WeightedProposalMsg{ - simulation.NewWeightedProposalMsg( - OpWeightMsgUpdateParams, - DefaultWeightMsgUpdateParams, - SimulateMsgUpdateParams, - ), - } -} - -// SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { - // use the default gov module account address as authority - var authority sdk.AccAddress = address.Module("gov") - - params := types.DefaultParams() - params.DefaultSendEnabled = r.Intn(2) == 0 - - return &types.MsgUpdateParams{ - Authority: authority.String(), - Params: params, - } -} diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go deleted file mode 100644 index 8edbda299..000000000 --- a/x/bank/simulation/proposals_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package simulation_test - -import ( - "fmt" - "math/rand" - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "gotest.tools/v3/assert" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/simulation" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestProposalMsgs(t *testing.T) { - // initialize parameters - s := rand.NewSource(1) - r := rand.New(s) - - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) - accounts := simtypes.RandomAccounts(r, 3) - - // execute ProposalMsgs function - weightedProposalMsgs := simulation.ProposalMsgs() - assert.Assert(t, len(weightedProposalMsgs) == 1) - - w0 := weightedProposalMsgs[0] - - // tests w0 interface: - assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) - assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - - msg := w0.MsgSimulatorFn()(r, ctx, accounts) - msgUpdateParams, ok := msg.(*types.MsgUpdateParams) - assert.Assert(t, ok) - - fmt.Println(msgUpdateParams) - assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck - assert.Equal(t, true, msgUpdateParams.Params.DefaultSendEnabled) -} diff --git a/x/bank/testutil/expected_keepers_mocks.go b/x/bank/testutil/expected_keepers_mocks.go deleted file mode 100644 index c27addd02..000000000 --- a/x/bank/testutil/expected_keepers_mocks.go +++ /dev/null @@ -1,228 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: x/bank/types/expected_keepers.go - -// Package testutil is a generated GoMock package. -package testutil - -import ( - reflect "reflect" - - types "github.com/cosmos/cosmos-sdk/types" - types0 "github.com/cosmos/cosmos-sdk/x/auth/types" - gomock "github.com/golang/mock/gomock" -) - -// MockAccountKeeper is a mock of AccountKeeper interface. -type MockAccountKeeper struct { - ctrl *gomock.Controller - recorder *MockAccountKeeperMockRecorder -} - -// MockAccountKeeperMockRecorder is the mock recorder for MockAccountKeeper. -type MockAccountKeeperMockRecorder struct { - mock *MockAccountKeeper -} - -// NewMockAccountKeeper creates a new mock instance. -func NewMockAccountKeeper(ctrl *gomock.Controller) *MockAccountKeeper { - mock := &MockAccountKeeper{ctrl: ctrl} - mock.recorder = &MockAccountKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { - return m.recorder -} - -// GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccount", ctx, addr) - ret0, _ := ret[0].(types0.AccountI) - return ret0 -} - -// GetAccount indicates an expected call of GetAccount. -func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) -} - -// GetAllAccounts mocks base method. -func (m *MockAccountKeeper) GetAllAccounts(ctx types.Context) []types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllAccounts", ctx) - ret0, _ := ret[0].([]types0.AccountI) - return ret0 -} - -// GetAllAccounts indicates an expected call of GetAllAccounts. -func (mr *MockAccountKeeperMockRecorder) GetAllAccounts(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).GetAllAccounts), ctx) -} - -// GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types0.ModuleAccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) - ret0, _ := ret[0].(types0.ModuleAccountI) - return ret0 -} - -// GetModuleAccount indicates an expected call of GetModuleAccount. -func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, moduleName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccount), ctx, moduleName) -} - -// GetModuleAccountAndPermissions mocks base method. -func (m *MockAccountKeeper) GetModuleAccountAndPermissions(ctx types.Context, moduleName string) (types0.ModuleAccountI, []string) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAccountAndPermissions", ctx, moduleName) - ret0, _ := ret[0].(types0.ModuleAccountI) - ret1, _ := ret[1].([]string) - return ret0, ret1 -} - -// GetModuleAccountAndPermissions indicates an expected call of GetModuleAccountAndPermissions. -func (mr *MockAccountKeeperMockRecorder) GetModuleAccountAndPermissions(ctx, moduleName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccountAndPermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccountAndPermissions), ctx, moduleName) -} - -// GetModuleAddress mocks base method. -func (m *MockAccountKeeper) GetModuleAddress(moduleName string) types.AccAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAddress", moduleName) - ret0, _ := ret[0].(types.AccAddress) - return ret0 -} - -// GetModuleAddress indicates an expected call of GetModuleAddress. -func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(moduleName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), moduleName) -} - -// GetModuleAddressAndPermissions mocks base method. -func (m *MockAccountKeeper) GetModuleAddressAndPermissions(moduleName string) (types.AccAddress, []string) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAddressAndPermissions", moduleName) - ret0, _ := ret[0].(types.AccAddress) - ret1, _ := ret[1].([]string) - return ret0, ret1 -} - -// GetModuleAddressAndPermissions indicates an expected call of GetModuleAddressAndPermissions. -func (mr *MockAccountKeeperMockRecorder) GetModuleAddressAndPermissions(moduleName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddressAndPermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddressAndPermissions), moduleName) -} - -// GetModulePermissions mocks base method. -func (m *MockAccountKeeper) GetModulePermissions() map[string]types0.PermissionsForAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModulePermissions") - ret0, _ := ret[0].(map[string]types0.PermissionsForAddress) - return ret0 -} - -// GetModulePermissions indicates an expected call of GetModulePermissions. -func (mr *MockAccountKeeperMockRecorder) GetModulePermissions() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModulePermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModulePermissions)) -} - -// HasAccount mocks base method. -func (m *MockAccountKeeper) HasAccount(ctx types.Context, addr types.AccAddress) bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HasAccount", ctx, addr) - ret0, _ := ret[0].(bool) - return ret0 -} - -// HasAccount indicates an expected call of HasAccount. -func (mr *MockAccountKeeperMockRecorder) HasAccount(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasAccount", reflect.TypeOf((*MockAccountKeeper)(nil).HasAccount), ctx, addr) -} - -// IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, process func(types0.AccountI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateAccounts", ctx, process) -} - -// IterateAccounts indicates an expected call of IterateAccounts. -func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process) -} - -// NewAccount mocks base method. -func (m *MockAccountKeeper) NewAccount(arg0 types.Context, arg1 types0.AccountI) types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NewAccount", arg0, arg1) - ret0, _ := ret[0].(types0.AccountI) - return ret0 -} - -// NewAccount indicates an expected call of NewAccount. -func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccount", reflect.TypeOf((*MockAccountKeeper)(nil).NewAccount), arg0, arg1) -} - -// NewAccountWithAddress mocks base method. -func (m *MockAccountKeeper) NewAccountWithAddress(ctx types.Context, addr types.AccAddress) types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NewAccountWithAddress", ctx, addr) - ret0, _ := ret[0].(types0.AccountI) - return ret0 -} - -// NewAccountWithAddress indicates an expected call of NewAccountWithAddress. -func (mr *MockAccountKeeperMockRecorder) NewAccountWithAddress(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccountWithAddress", reflect.TypeOf((*MockAccountKeeper)(nil).NewAccountWithAddress), ctx, addr) -} - -// SetAccount mocks base method. -func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types0.AccountI) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetAccount", ctx, acc) -} - -// SetAccount indicates an expected call of SetAccount. -func (mr *MockAccountKeeperMockRecorder) SetAccount(ctx, acc interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetAccount), ctx, acc) -} - -// SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(ctx types.Context, macc types0.ModuleAccountI) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetModuleAccount", ctx, macc) -} - -// SetModuleAccount indicates an expected call of SetModuleAccount. -func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(ctx, macc interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), ctx, macc) -} - -// ValidatePermissions mocks base method. -func (m *MockAccountKeeper) ValidatePermissions(macc types0.ModuleAccountI) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidatePermissions", macc) - ret0, _ := ret[0].(error) - return ret0 -} - -// ValidatePermissions indicates an expected call of ValidatePermissions. -func (mr *MockAccountKeeperMockRecorder) ValidatePermissions(macc interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidatePermissions", reflect.TypeOf((*MockAccountKeeper)(nil).ValidatePermissions), macc) -} diff --git a/x/bank/testutil/helpers.go b/x/bank/testutil/helpers.go deleted file mode 100644 index e8805ed7b..000000000 --- a/x/bank/testutil/helpers.go +++ /dev/null @@ -1,35 +0,0 @@ -package testutil - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -// FundAccount is a utility function that funds an account by minting and -// sending the coins to the address. This should be used for testing purposes -// only! -// -// TODO: Instead of using the mint module account, which has the -// permission of minting, create a "faucet" account. (@fdymylja) -func FundAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, addr sdk.AccAddress, amounts sdk.Coins) error { - if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil { - return err - } - - return bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, amounts) -} - -// FundModuleAccount is a utility function that funds a module account by -// minting and sending the coins to the address. This should be used for testing -// purposes only! -// -// TODO: Instead of using the mint module account, which has the -// permission of minting, create a "faucet" account. (@fdymylja) -func FundModuleAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, recipientMod string, amounts sdk.Coins) error { - if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil { - return err - } - - return bankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, recipientMod, amounts) -} diff --git a/x/bank/types/authz.pb.go b/x/bank/types/authz.pb.go deleted file mode 100644 index 17131972c..000000000 --- a/x/bank/types/authz.pb.go +++ /dev/null @@ -1,405 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/bank/v1beta1/authz.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/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 - -// SendAuthorization allows the grantee to spend up to spend_limit coins from -// the granter's account. -// -// Since: cosmos-sdk 0.43 -type SendAuthorization struct { - SpendLimit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=spend_limit,json=spendLimit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"spend_limit"` - // allow_list specifies an optional list of addresses to whom the grantee can send tokens on behalf of the - // granter. If omitted, any recipient is allowed. - // - // Since: cosmos-sdk 0.47 - AllowList []string `protobuf:"bytes,2,rep,name=allow_list,json=allowList,proto3" json:"allow_list,omitempty"` -} - -func (m *SendAuthorization) Reset() { *m = SendAuthorization{} } -func (m *SendAuthorization) String() string { return proto.CompactTextString(m) } -func (*SendAuthorization) ProtoMessage() {} -func (*SendAuthorization) Descriptor() ([]byte, []int) { - return fileDescriptor_a4d2a37888ea779f, []int{0} -} -func (m *SendAuthorization) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SendAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SendAuthorization.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 *SendAuthorization) XXX_Merge(src proto.Message) { - xxx_messageInfo_SendAuthorization.Merge(m, src) -} -func (m *SendAuthorization) XXX_Size() int { - return m.Size() -} -func (m *SendAuthorization) XXX_DiscardUnknown() { - xxx_messageInfo_SendAuthorization.DiscardUnknown(m) -} - -var xxx_messageInfo_SendAuthorization proto.InternalMessageInfo - -func (m *SendAuthorization) GetSpendLimit() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.SpendLimit - } - return nil -} - -func (m *SendAuthorization) GetAllowList() []string { - if m != nil { - return m.AllowList - } - return nil -} - -func init() { - proto.RegisterType((*SendAuthorization)(nil), "cosmos.bank.v1beta1.SendAuthorization") -} - -func init() { proto.RegisterFile("cosmos/bank/v1beta1/authz.proto", fileDescriptor_a4d2a37888ea779f) } - -var fileDescriptor_a4d2a37888ea779f = []byte{ - // 339 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x4a, 0xcc, 0xcb, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, - 0x4f, 0x2c, 0x2d, 0xc9, 0xa8, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x86, 0x28, 0xd0, - 0x03, 0x29, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x4c, 0xcc, 0xcd, 0xcc, 0xcb, 0xd7, 0x07, 0x93, 0x10, - 0x75, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0xa6, 0x3e, 0x88, 0x05, 0x15, 0x95, 0x84, 0xe8, - 0x8e, 0x87, 0x48, 0x40, 0x8d, 0x82, 0x48, 0xc9, 0xc1, 0x6d, 0x2e, 0x4e, 0x85, 0xdb, 0x9c, 0x9c, - 0x9f, 0x99, 0x07, 0x91, 0x57, 0xea, 0x60, 0xe2, 0x12, 0x0c, 0x4e, 0xcd, 0x4b, 0x71, 0x2c, 0x2d, - 0xc9, 0xc8, 0x2f, 0xca, 0xac, 0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0x13, 0x2a, 0xe4, 0xe2, 0x2e, 0x2e, - 0x48, 0xcd, 0x4b, 0x89, 0xcf, 0xc9, 0xcc, 0xcd, 0x2c, 0x91, 0x60, 0x54, 0x60, 0xd6, 0xe0, 0x36, - 0x92, 0xd4, 0x83, 0x3b, 0xb2, 0x38, 0x15, 0xe6, 0x48, 0x3d, 0xe7, 0xfc, 0xcc, 0x3c, 0x27, 0xd3, - 0x13, 0xf7, 0xe4, 0x19, 0x56, 0xdd, 0x97, 0xd7, 0x48, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, - 0xce, 0xcf, 0x85, 0x3a, 0x03, 0x4a, 0xe9, 0x16, 0xa7, 0x64, 0xeb, 0x97, 0x54, 0x16, 0xa4, 0x16, - 0x83, 0x35, 0x14, 0xaf, 0x78, 0xbe, 0x41, 0x8b, 0x31, 0x88, 0x0b, 0x6c, 0x89, 0x0f, 0xc8, 0x0e, - 0x21, 0x73, 0x2e, 0xae, 0xc4, 0x9c, 0x9c, 0xfc, 0xf2, 0xf8, 0x9c, 0xcc, 0xe2, 0x12, 0x09, 0x26, - 0x05, 0x66, 0x0d, 0x4e, 0x27, 0x89, 0x4b, 0x5b, 0x74, 0x45, 0xa0, 0x96, 0x3a, 0xa6, 0xa4, 0x14, - 0xa5, 0x16, 0x17, 0x07, 0x97, 0x14, 0x65, 0xe6, 0xa5, 0x07, 0x71, 0x82, 0xd5, 0xfa, 0x64, 0x16, - 0x97, 0x58, 0xb9, 0x9f, 0xda, 0xa2, 0xab, 0x04, 0x55, 0x04, 0x09, 0x52, 0x98, 0xd3, 0x50, 0xfc, - 0xd4, 0xf5, 0x7c, 0x83, 0x96, 0x0c, 0x92, 0x63, 0x30, 0x3c, 0xed, 0xe4, 0x7c, 0xe2, 0x91, 0x1c, - 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, - 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x9a, 0x78, 0xbd, 0x55, 0x01, 0x89, 0x56, 0xb0, 0xef, - 0x92, 0xd8, 0xc0, 0xc1, 0x6a, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x78, 0xc2, 0x7d, 0xd9, 0xf2, - 0x01, 0x00, 0x00, -} - -func (m *SendAuthorization) 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 *SendAuthorization) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SendAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowList) > 0 { - for iNdEx := len(m.AllowList) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowList[iNdEx]) - copy(dAtA[i:], m.AllowList[iNdEx]) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.AllowList[iNdEx]))) - i-- - dAtA[i] = 0x12 - } - } - if len(m.SpendLimit) > 0 { - for iNdEx := len(m.SpendLimit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SpendLimit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int { - offset -= sovAuthz(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *SendAuthorization) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SpendLimit) > 0 { - for _, e := range m.SpendLimit { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - if len(m.AllowList) > 0 { - for _, s := range m.AllowList { - l = len(s) - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func sovAuthz(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAuthz(x uint64) (n int) { - return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *SendAuthorization) 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 ErrIntOverflowAuthz - } - 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: SendAuthorization: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SendAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpendLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SpendLimit = append(m.SpendLimit, types.Coin{}) - if err := m.SpendLimit[len(m.SpendLimit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowList", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowList = append(m.AllowList, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAuthz(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, ErrIntOverflowAuthz - } - 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, ErrIntOverflowAuthz - } - 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, ErrIntOverflowAuthz - } - 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, ErrInvalidLengthAuthz - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAuthz - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAuthz - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAuthz = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAuthz = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAuthz = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bank/types/balance.go b/x/bank/types/balance.go deleted file mode 100644 index 3b0decadb..000000000 --- a/x/bank/types/balance.go +++ /dev/null @@ -1,91 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "sort" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/exported" -) - -var _ exported.GenesisBalance = (*Balance)(nil) - -// GetAddress returns the account address of the Balance object. -func (b Balance) GetAddress() sdk.AccAddress { - return sdk.MustAccAddressFromBech32(b.Address) -} - -// GetCoins returns the account coins of the Balance object. -func (b Balance) GetCoins() sdk.Coins { - return b.Coins -} - -// Validate checks for address and coins correctness. -func (b Balance) Validate() error { - if _, err := sdk.AccAddressFromBech32(b.Address); err != nil { - return err - } - - if err := b.Coins.Validate(); err != nil { - return err - } - - return nil -} - -type balanceByAddress struct { - addresses []sdk.AccAddress - balances []Balance -} - -func (b balanceByAddress) Len() int { return len(b.addresses) } -func (b balanceByAddress) Less(i, j int) bool { - return bytes.Compare(b.addresses[i], b.addresses[j]) < 0 -} - -func (b balanceByAddress) Swap(i, j int) { - b.addresses[i], b.addresses[j] = b.addresses[j], b.addresses[i] - b.balances[i], b.balances[j] = b.balances[j], b.balances[i] -} - -// SanitizeGenesisBalances sorts addresses and coin sets. -func SanitizeGenesisBalances(balances []Balance) []Balance { - // Given that this function sorts balances, using the standard library's - // Quicksort based algorithms, we have algorithmic complexities of: - // * Best case: O(nlogn) - // * Worst case: O(n^2) - // The comparator used MUST be cheap to use lest we incur expenses like we had - // before whereby sdk.AccAddressFromBech32, which is a very expensive operation - // compared n * n elements yet discarded computations each time, as per: - // https://github.com/cosmos/cosmos-sdk/issues/7766#issuecomment-786671734 - - // 1. Retrieve the address equivalents for each Balance's address. - addresses := make([]sdk.AccAddress, len(balances)) - for i := range balances { - addr, _ := sdk.AccAddressFromBech32(balances[i].Address) - addresses[i] = addr - } - - // 2. Sort balances. - sort.Sort(balanceByAddress{addresses: addresses, balances: balances}) - - return balances -} - -// GenesisBalancesIterator implements genesis account iteration. -type GenesisBalancesIterator struct{} - -// IterateGenesisBalances iterates over all the genesis balances found in -// appGenesis and invokes a callback on each genesis account. If any call -// returns true, iteration stops. -func (GenesisBalancesIterator) IterateGenesisBalances( - cdc codec.JSONCodec, appState map[string]json.RawMessage, cb func(exported.GenesisBalance) (stop bool), -) { - for _, balance := range GetGenesisStateFromAppState(cdc, appState).Balances { - if cb(balance) { - break - } - } -} diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go deleted file mode 100644 index a69cf4826..000000000 --- a/x/bank/types/balance_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package types_test - -import ( - "bytes" - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - bank "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestBalanceValidate(t *testing.T) { - testCases := []struct { - name string - balance bank.Balance - expErr bool - }{ - { - "valid balance", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{sdk.NewInt64Coin("uatom", 1)}, - }, - false, - }, - {"empty balance", bank.Balance{}, true}, - { - "nil balance coins", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - }, - false, - }, - { - "dup coins", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.NewInt64Coin("uatom", 1), - sdk.NewInt64Coin("uatom", 1), - }, - }, - true, - }, - { - "invalid coin denom", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.Coin{Denom: "", Amount: math.OneInt()}, - }, - }, - true, - }, - { - "negative coin", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.Coin{Denom: "uatom", Amount: sdk.NewInt(-1)}, - }, - }, - true, - }, - { - "0 value coin", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.NewInt64Coin("atom", 0), - sdk.NewInt64Coin("zatom", 2), - }, - }, - true, - }, - { - "unsorted coins", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.NewInt64Coin("atom", 2), - sdk.NewInt64Coin("zatom", 2), - sdk.NewInt64Coin("batom", 12), - }, - }, - true, - }, - { - "valid sorted coins", - bank.Balance{ - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{ - sdk.NewInt64Coin("atom", 2), - sdk.NewInt64Coin("batom", 12), - sdk.NewInt64Coin("zatom", 2), - }, - }, - false, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.balance.Validate() - - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestBalance_GetAddress(t *testing.T) { - tests := []struct { - name string - Address string - wantPanic bool - }{ - {"empty address", "", true}, - {"malformed address", "invalid", true}, - {"valid address", "cosmos1vy0ga0klndqy92ceqehfkvgmn4t94eteq4hmqv", false}, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - b := bank.Balance{Address: tt.Address} - if tt.wantPanic { - require.Panics(t, func() { b.GetAddress() }) - } else { - require.False(t, b.GetAddress().Empty()) - } - }) - } -} - -func TestSanitizeBalances(t *testing.T) { - // 1. Generate balances - tokens := sdk.TokensFromConsensusPower(81, sdk.DefaultPowerReduction) - coin := sdk.NewCoin("benchcoin", tokens) - coins := sdk.Coins{coin} - addrs, _ := makeRandomAddressesAndPublicKeys(20) - - var balances []bank.Balance - for _, addr := range addrs { - balances = append(balances, bank.Balance{ - Address: addr.String(), - Coins: coins, - }) - } - // 2. Sort the values. - sorted := bank.SanitizeGenesisBalances(balances) - - // 3. Compare and ensure that all the values are sorted in ascending order. - // Invariant after sorting: - // a[i] <= a[i+1...n] - for i := 0; i < len(sorted); i++ { - ai := sorted[i] - // Ensure that every single value that comes after i is less than it. - for j := i + 1; j < len(sorted); j++ { - aj := sorted[j] - - if got := bytes.Compare(ai.GetAddress(), aj.GetAddress()); got > 0 { - t.Errorf("Balance(%d) > Balance(%d)", i, j) - } - } - } -} - -func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.AccAddress, pkL []*ed25519.PubKey) { - for i := 0; i < n; i++ { - pk := ed25519.GenPrivKey().PubKey().(*ed25519.PubKey) - pkL = append(pkL, pk) - accL = append(accL, sdk.AccAddress(pk.Address())) - } - return accL, pkL -} - -var sink, revert interface{} - -func BenchmarkSanitizeBalances500(b *testing.B) { - benchmarkSanitizeBalances(b, 500) -} - -func BenchmarkSanitizeBalances1000(b *testing.B) { - benchmarkSanitizeBalances(b, 1000) -} - -func benchmarkSanitizeBalances(b *testing.B, nAddresses int) { - b.ReportAllocs() - tokens := sdk.TokensFromConsensusPower(81, sdk.DefaultPowerReduction) - coin := sdk.NewCoin("benchcoin", tokens) - coins := sdk.Coins{coin} - addrs, _ := makeRandomAddressesAndPublicKeys(nAddresses) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - var balances []bank.Balance - for _, addr := range addrs { - balances = append(balances, bank.Balance{ - Address: addr.String(), - Coins: coins, - }) - } - sink = bank.SanitizeGenesisBalances(balances) - } - if sink == nil { - b.Fatal("Benchmark did not run") - } - sink = revert -} diff --git a/x/bank/types/bank.pb.go b/x/bank/types/bank.pb.go deleted file mode 100644 index fe19f342e..000000000 --- a/x/bank/types/bank.pb.go +++ /dev/null @@ -1,2122 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/bank/v1beta1/bank.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/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 - -// Params defines the parameters for the bank module. -type Params struct { - // Deprecated: Use of SendEnabled in params is deprecated. - // For genesis, use the newly added send_enabled field in the genesis object. - // Storage, lookup, and manipulation of this information is now in the keeper. - // - // As of cosmos-sdk 0.47, this only exists for backwards compatibility of genesis files. - SendEnabled []*SendEnabled `protobuf:"bytes,1,rep,name=send_enabled,json=sendEnabled,proto3" json:"send_enabled,omitempty"` // Deprecated: Do not use. - DefaultSendEnabled bool `protobuf:"varint,2,opt,name=default_send_enabled,json=defaultSendEnabled,proto3" json:"default_send_enabled,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -// Deprecated: Do not use. -func (m *Params) GetSendEnabled() []*SendEnabled { - if m != nil { - return m.SendEnabled - } - return nil -} - -func (m *Params) GetDefaultSendEnabled() bool { - if m != nil { - return m.DefaultSendEnabled - } - return false -} - -// SendEnabled maps coin denom to a send_enabled status (whether a denom is -// sendable). -type SendEnabled struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Enabled bool `protobuf:"varint,2,opt,name=enabled,proto3" json:"enabled,omitempty"` -} - -func (m *SendEnabled) Reset() { *m = SendEnabled{} } -func (*SendEnabled) ProtoMessage() {} -func (*SendEnabled) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{1} -} -func (m *SendEnabled) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SendEnabled) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SendEnabled.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 *SendEnabled) XXX_Merge(src proto.Message) { - xxx_messageInfo_SendEnabled.Merge(m, src) -} -func (m *SendEnabled) XXX_Size() int { - return m.Size() -} -func (m *SendEnabled) XXX_DiscardUnknown() { - xxx_messageInfo_SendEnabled.DiscardUnknown(m) -} - -var xxx_messageInfo_SendEnabled proto.InternalMessageInfo - -func (m *SendEnabled) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *SendEnabled) GetEnabled() bool { - if m != nil { - return m.Enabled - } - return false -} - -// Input models transaction input. -type Input struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *Input) Reset() { *m = Input{} } -func (m *Input) String() string { return proto.CompactTextString(m) } -func (*Input) ProtoMessage() {} -func (*Input) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{2} -} -func (m *Input) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Input) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Input.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 *Input) XXX_Merge(src proto.Message) { - xxx_messageInfo_Input.Merge(m, src) -} -func (m *Input) XXX_Size() int { - return m.Size() -} -func (m *Input) XXX_DiscardUnknown() { - xxx_messageInfo_Input.DiscardUnknown(m) -} - -var xxx_messageInfo_Input proto.InternalMessageInfo - -// Output models transaction outputs. -type Output struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *Output) Reset() { *m = Output{} } -func (m *Output) String() string { return proto.CompactTextString(m) } -func (*Output) ProtoMessage() {} -func (*Output) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{3} -} -func (m *Output) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Output) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Output.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 *Output) XXX_Merge(src proto.Message) { - xxx_messageInfo_Output.Merge(m, src) -} -func (m *Output) XXX_Size() int { - return m.Size() -} -func (m *Output) XXX_DiscardUnknown() { - xxx_messageInfo_Output.DiscardUnknown(m) -} - -var xxx_messageInfo_Output proto.InternalMessageInfo - -// Supply represents a struct that passively keeps track of the total supply -// amounts in the network. -// This message is deprecated now that supply is indexed by denom. -// -// Deprecated: Do not use. -type Supply struct { - Total github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=total,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total"` -} - -func (m *Supply) Reset() { *m = Supply{} } -func (m *Supply) String() string { return proto.CompactTextString(m) } -func (*Supply) ProtoMessage() {} -func (*Supply) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{4} -} -func (m *Supply) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Supply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Supply.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 *Supply) XXX_Merge(src proto.Message) { - xxx_messageInfo_Supply.Merge(m, src) -} -func (m *Supply) XXX_Size() int { - return m.Size() -} -func (m *Supply) XXX_DiscardUnknown() { - xxx_messageInfo_Supply.DiscardUnknown(m) -} - -var xxx_messageInfo_Supply proto.InternalMessageInfo - -// DenomUnit represents a struct that describes a given -// denomination unit of the basic token. -type DenomUnit struct { - // denom represents the string name of the given denom unit (e.g uatom). - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // exponent represents power of 10 exponent that one must - // raise the base_denom to in order to equal the given DenomUnit's denom - // 1 denom = 10^exponent base_denom - // (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with - // exponent = 6, thus: 1 atom = 10^6 uatom). - Exponent uint32 `protobuf:"varint,2,opt,name=exponent,proto3" json:"exponent,omitempty"` - // aliases is a list of string aliases for the given denom - Aliases []string `protobuf:"bytes,3,rep,name=aliases,proto3" json:"aliases,omitempty"` -} - -func (m *DenomUnit) Reset() { *m = DenomUnit{} } -func (m *DenomUnit) String() string { return proto.CompactTextString(m) } -func (*DenomUnit) ProtoMessage() {} -func (*DenomUnit) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{5} -} -func (m *DenomUnit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DenomUnit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DenomUnit.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 *DenomUnit) XXX_Merge(src proto.Message) { - xxx_messageInfo_DenomUnit.Merge(m, src) -} -func (m *DenomUnit) XXX_Size() int { - return m.Size() -} -func (m *DenomUnit) XXX_DiscardUnknown() { - xxx_messageInfo_DenomUnit.DiscardUnknown(m) -} - -var xxx_messageInfo_DenomUnit proto.InternalMessageInfo - -func (m *DenomUnit) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *DenomUnit) GetExponent() uint32 { - if m != nil { - return m.Exponent - } - return 0 -} - -func (m *DenomUnit) GetAliases() []string { - if m != nil { - return m.Aliases - } - return nil -} - -// Metadata represents a struct that describes -// a basic token. -type Metadata struct { - Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"` - // denom_units represents the list of DenomUnit's for a given coin - DenomUnits []*DenomUnit `protobuf:"bytes,2,rep,name=denom_units,json=denomUnits,proto3" json:"denom_units,omitempty"` - // base represents the base denom (should be the DenomUnit with exponent = 0). - Base string `protobuf:"bytes,3,opt,name=base,proto3" json:"base,omitempty"` - // display indicates the suggested denom that should be - // displayed in clients. - Display string `protobuf:"bytes,4,opt,name=display,proto3" json:"display,omitempty"` - // name defines the name of the token (eg: Cosmos Atom) - // - // Since: cosmos-sdk 0.43 - Name string `protobuf:"bytes,5,opt,name=name,proto3" json:"name,omitempty"` - // symbol is the token symbol usually shown on exchanges (eg: ATOM). This can - // be the same as the display. - // - // Since: cosmos-sdk 0.43 - Symbol string `protobuf:"bytes,6,opt,name=symbol,proto3" json:"symbol,omitempty"` - // URI to a document (on or off-chain) that contains additional information. Optional. - // - // Since: cosmos-sdk 0.46 - URI string `protobuf:"bytes,7,opt,name=uri,proto3" json:"uri,omitempty"` - // URIHash is a sha256 hash of a document pointed by URI. It's used to verify that - // the document didn't change. Optional. - // - // Since: cosmos-sdk 0.46 - URIHash string `protobuf:"bytes,8,opt,name=uri_hash,json=uriHash,proto3" json:"uri_hash,omitempty"` -} - -func (m *Metadata) Reset() { *m = Metadata{} } -func (m *Metadata) String() string { return proto.CompactTextString(m) } -func (*Metadata) ProtoMessage() {} -func (*Metadata) Descriptor() ([]byte, []int) { - return fileDescriptor_dd052eee12edf988, []int{6} -} -func (m *Metadata) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Metadata.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 *Metadata) XXX_Merge(src proto.Message) { - xxx_messageInfo_Metadata.Merge(m, src) -} -func (m *Metadata) XXX_Size() int { - return m.Size() -} -func (m *Metadata) XXX_DiscardUnknown() { - xxx_messageInfo_Metadata.DiscardUnknown(m) -} - -var xxx_messageInfo_Metadata proto.InternalMessageInfo - -func (m *Metadata) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Metadata) GetDenomUnits() []*DenomUnit { - if m != nil { - return m.DenomUnits - } - return nil -} - -func (m *Metadata) GetBase() string { - if m != nil { - return m.Base - } - return "" -} - -func (m *Metadata) GetDisplay() string { - if m != nil { - return m.Display - } - return "" -} - -func (m *Metadata) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Metadata) GetSymbol() string { - if m != nil { - return m.Symbol - } - return "" -} - -func (m *Metadata) GetURI() string { - if m != nil { - return m.URI - } - return "" -} - -func (m *Metadata) GetURIHash() string { - if m != nil { - return m.URIHash - } - return "" -} - -func init() { - proto.RegisterType((*Params)(nil), "cosmos.bank.v1beta1.Params") - proto.RegisterType((*SendEnabled)(nil), "cosmos.bank.v1beta1.SendEnabled") - proto.RegisterType((*Input)(nil), "cosmos.bank.v1beta1.Input") - proto.RegisterType((*Output)(nil), "cosmos.bank.v1beta1.Output") - proto.RegisterType((*Supply)(nil), "cosmos.bank.v1beta1.Supply") - proto.RegisterType((*DenomUnit)(nil), "cosmos.bank.v1beta1.DenomUnit") - proto.RegisterType((*Metadata)(nil), "cosmos.bank.v1beta1.Metadata") -} - -func init() { proto.RegisterFile("cosmos/bank/v1beta1/bank.proto", fileDescriptor_dd052eee12edf988) } - -var fileDescriptor_dd052eee12edf988 = []byte{ - // 670 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0xbf, 0x6f, 0x13, 0x3f, - 0x14, 0x8f, 0x93, 0xe6, 0x47, 0x9d, 0xef, 0x77, 0xc0, 0x44, 0xe0, 0x16, 0xe9, 0x12, 0x32, 0xa0, - 0xb4, 0x52, 0x13, 0x5a, 0xc4, 0x92, 0x05, 0x91, 0x82, 0x4a, 0x06, 0x04, 0xba, 0xaa, 0x42, 0x62, - 0x89, 0x9c, 0x9c, 0x9b, 0x58, 0xbd, 0xb3, 0x4f, 0x67, 0x5f, 0xd5, 0xac, 0x4c, 0xa8, 0x13, 0x23, - 0x12, 0x4b, 0x27, 0x84, 0x18, 0x50, 0x87, 0x2e, 0xfc, 0x07, 0x15, 0x53, 0xc5, 0xc4, 0x54, 0x50, - 0x3a, 0x94, 0x3f, 0x03, 0xd9, 0xbe, 0x4b, 0x53, 0xa9, 0xb0, 0x21, 0xb1, 0x24, 0xef, 0xbd, 0xcf, - 0xf3, 0xfb, 0x7c, 0xfc, 0xde, 0xf3, 0x41, 0x67, 0x20, 0x64, 0x20, 0x64, 0xab, 0x4f, 0xf8, 0x4e, - 0x6b, 0x77, 0xb5, 0x4f, 0x15, 0x59, 0x35, 0x4e, 0x33, 0x8c, 0x84, 0x12, 0xe8, 0xba, 0xc5, 0x9b, - 0x26, 0x94, 0xe0, 0x8b, 0x95, 0xa1, 0x18, 0x0a, 0x83, 0xb7, 0xb4, 0x65, 0x53, 0x17, 0x17, 0x6c, - 0x6a, 0xcf, 0x02, 0xc9, 0x39, 0x0b, 0x5d, 0xb0, 0x48, 0x3a, 0x65, 0x19, 0x08, 0xc6, 0x13, 0xfc, - 0x66, 0x82, 0x07, 0x72, 0xd8, 0xda, 0x5d, 0xd5, 0x7f, 0x09, 0x70, 0x8d, 0x04, 0x8c, 0x8b, 0x96, - 0xf9, 0xb5, 0xa1, 0xfa, 0x7b, 0x00, 0x0b, 0xcf, 0x49, 0x44, 0x02, 0x89, 0x36, 0xe0, 0x7f, 0x92, - 0x72, 0xaf, 0x47, 0x39, 0xe9, 0xfb, 0xd4, 0xc3, 0xa0, 0x96, 0x6b, 0x94, 0xd7, 0x6a, 0xcd, 0x2b, - 0x34, 0x37, 0x37, 0x29, 0xf7, 0x1e, 0xdb, 0xbc, 0x4e, 0x16, 0x03, 0xb7, 0x2c, 0x2f, 0x02, 0xe8, - 0x2e, 0xac, 0x78, 0x74, 0x9b, 0xc4, 0xbe, 0xea, 0x5d, 0x2a, 0x98, 0xad, 0x81, 0x46, 0xc9, 0x45, - 0x09, 0x36, 0x53, 0xa2, 0x7d, 0xfb, 0xed, 0x41, 0x35, 0xb3, 0x7f, 0x7e, 0xb8, 0x8c, 0x2d, 0xd9, - 0x8a, 0xf4, 0x76, 0x5a, 0x7b, 0xb6, 0x8d, 0x56, 0x5d, 0x7d, 0x03, 0x96, 0x67, 0x4e, 0xa0, 0x0a, - 0xcc, 0x7b, 0x94, 0x8b, 0x00, 0x83, 0x1a, 0x68, 0xcc, 0xbb, 0xd6, 0x41, 0x18, 0x16, 0x2f, 0x93, - 0xa5, 0x6e, 0xbb, 0xa4, 0x19, 0x7e, 0x1e, 0x54, 0x41, 0xfd, 0x33, 0x80, 0xf9, 0x2e, 0x0f, 0x63, - 0x85, 0xd6, 0x60, 0x91, 0x78, 0x5e, 0x44, 0xa5, 0xb4, 0x55, 0x3a, 0xf8, 0xeb, 0xd1, 0x4a, 0x25, - 0xb9, 0xee, 0x43, 0x8b, 0x6c, 0xaa, 0x88, 0xf1, 0xa1, 0x9b, 0x26, 0xa2, 0x6d, 0x98, 0xd7, 0x9d, - 0x96, 0x38, 0x6b, 0xba, 0xb3, 0x70, 0xd1, 0x1d, 0x49, 0xa7, 0xdd, 0x59, 0x17, 0x8c, 0x77, 0xee, - 0x1f, 0x9f, 0x56, 0x33, 0x1f, 0xbf, 0x57, 0x1b, 0x43, 0xa6, 0x46, 0x71, 0xbf, 0x39, 0x10, 0x41, - 0x32, 0xc6, 0xd6, 0xcc, 0x25, 0xd5, 0x38, 0xa4, 0xd2, 0x1c, 0x90, 0x1f, 0xce, 0x0f, 0x97, 0x81, - 0x6b, 0xcb, 0xb7, 0x2b, 0xaf, 0xad, 0xde, 0xcc, 0xab, 0xf3, 0xc3, 0xe5, 0x94, 0xbd, 0xfe, 0x09, - 0xc0, 0xc2, 0xb3, 0x58, 0xfd, 0xeb, 0xe2, 0x4b, 0xa9, 0xf8, 0xfa, 0x3b, 0x00, 0x0b, 0x9b, 0x71, - 0x18, 0xfa, 0x63, 0x4d, 0xae, 0x84, 0x22, 0x7e, 0xb2, 0x57, 0x7f, 0x81, 0xdc, 0x94, 0x6f, 0x2f, - 0x25, 0xe4, 0xe0, 0xcb, 0xd1, 0xca, 0xad, 0x2b, 0x77, 0xd7, 0xe8, 0xe9, 0x62, 0x50, 0x7f, 0x01, - 0xe7, 0x1f, 0xe9, 0xbd, 0xd9, 0xe2, 0x4c, 0xfd, 0x66, 0xa3, 0x16, 0x61, 0x89, 0xee, 0x85, 0x82, - 0x53, 0xae, 0xcc, 0x4a, 0xfd, 0xef, 0x4e, 0x7d, 0xbd, 0x6d, 0xc4, 0x67, 0x44, 0x52, 0x89, 0x73, - 0xb5, 0x5c, 0x63, 0xde, 0x4d, 0xdd, 0xfa, 0x7e, 0x16, 0x96, 0x9e, 0x52, 0x45, 0x3c, 0xa2, 0x08, - 0xaa, 0xc1, 0xb2, 0x47, 0xe5, 0x20, 0x62, 0xa1, 0x62, 0x82, 0x27, 0xe5, 0x67, 0x43, 0xe8, 0x81, - 0xce, 0xe0, 0x22, 0xe8, 0xc5, 0x9c, 0xa9, 0x74, 0x3a, 0xce, 0x95, 0x0f, 0x6f, 0xaa, 0xd7, 0x85, - 0x5e, 0x6a, 0x4a, 0x84, 0xe0, 0x9c, 0x6e, 0x23, 0xce, 0x99, 0xda, 0xc6, 0xd6, 0xea, 0x3c, 0x26, - 0x43, 0x9f, 0x8c, 0xf1, 0x9c, 0x09, 0xa7, 0xae, 0xce, 0xe6, 0x24, 0xa0, 0x38, 0x6f, 0xb3, 0xb5, - 0x8d, 0x6e, 0xc0, 0x82, 0x1c, 0x07, 0x7d, 0xe1, 0xe3, 0x82, 0x89, 0x26, 0x1e, 0x5a, 0x80, 0xb9, - 0x38, 0x62, 0xb8, 0x68, 0x56, 0xac, 0x38, 0x39, 0xad, 0xe6, 0xb6, 0xdc, 0xae, 0xab, 0x63, 0xe8, - 0x0e, 0x2c, 0xc5, 0x11, 0xeb, 0x8d, 0x88, 0x1c, 0xe1, 0x92, 0xc1, 0xcb, 0x93, 0xd3, 0x6a, 0x71, - 0xcb, 0xed, 0x3e, 0x21, 0x72, 0xe4, 0x16, 0xe3, 0x88, 0x69, 0xa3, 0xb3, 0x7e, 0x3c, 0x71, 0xc0, - 0xc9, 0xc4, 0x01, 0x3f, 0x26, 0x0e, 0x78, 0x73, 0xe6, 0x64, 0x4e, 0xce, 0x9c, 0xcc, 0xb7, 0x33, - 0x27, 0xf3, 0x72, 0xe9, 0x8f, 0x03, 0x4e, 0xde, 0xbf, 0x99, 0x73, 0xbf, 0x60, 0x3e, 0x57, 0xf7, - 0x7e, 0x05, 0x00, 0x00, 0xff, 0xff, 0x31, 0xf6, 0x7e, 0x4e, 0x62, 0x05, 0x00, 0x00, -} - -func (this *SendEnabled) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*SendEnabled) - if !ok { - that2, ok := that.(SendEnabled) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Denom != that1.Denom { - return false - } - if this.Enabled != that1.Enabled { - return false - } - return true -} -func (this *Supply) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Supply) - if !ok { - that2, ok := that.(Supply) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Total) != len(that1.Total) { - return false - } - for i := range this.Total { - if !this.Total[i].Equal(&that1.Total[i]) { - return false - } - } - return true -} -func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.DefaultSendEnabled { - i-- - if m.DefaultSendEnabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - } - if len(m.SendEnabled) > 0 { - for iNdEx := len(m.SendEnabled) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SendEnabled[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBank(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *SendEnabled) 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 *SendEnabled) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SendEnabled) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Enabled { - i-- - if m.Enabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintBank(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Input) 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 *Input) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Input) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBank(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintBank(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Output) 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 *Output) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Output) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBank(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintBank(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Supply) 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 *Supply) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Supply) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Total) > 0 { - for iNdEx := len(m.Total) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Total[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBank(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *DenomUnit) 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 *DenomUnit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DenomUnit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Aliases) > 0 { - for iNdEx := len(m.Aliases) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Aliases[iNdEx]) - copy(dAtA[i:], m.Aliases[iNdEx]) - i = encodeVarintBank(dAtA, i, uint64(len(m.Aliases[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if m.Exponent != 0 { - i = encodeVarintBank(dAtA, i, uint64(m.Exponent)) - i-- - dAtA[i] = 0x10 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintBank(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Metadata) 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 *Metadata) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Metadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.URIHash) > 0 { - i -= len(m.URIHash) - copy(dAtA[i:], m.URIHash) - i = encodeVarintBank(dAtA, i, uint64(len(m.URIHash))) - i-- - dAtA[i] = 0x42 - } - if len(m.URI) > 0 { - i -= len(m.URI) - copy(dAtA[i:], m.URI) - i = encodeVarintBank(dAtA, i, uint64(len(m.URI))) - i-- - dAtA[i] = 0x3a - } - if len(m.Symbol) > 0 { - i -= len(m.Symbol) - copy(dAtA[i:], m.Symbol) - i = encodeVarintBank(dAtA, i, uint64(len(m.Symbol))) - i-- - dAtA[i] = 0x32 - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintBank(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0x2a - } - if len(m.Display) > 0 { - i -= len(m.Display) - copy(dAtA[i:], m.Display) - i = encodeVarintBank(dAtA, i, uint64(len(m.Display))) - i-- - dAtA[i] = 0x22 - } - if len(m.Base) > 0 { - i -= len(m.Base) - copy(dAtA[i:], m.Base) - i = encodeVarintBank(dAtA, i, uint64(len(m.Base))) - i-- - dAtA[i] = 0x1a - } - if len(m.DenomUnits) > 0 { - for iNdEx := len(m.DenomUnits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomUnits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintBank(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintBank(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintBank(dAtA []byte, offset int, v uint64) int { - offset -= sovBank(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SendEnabled) > 0 { - for _, e := range m.SendEnabled { - l = e.Size() - n += 1 + l + sovBank(uint64(l)) - } - } - if m.DefaultSendEnabled { - n += 2 - } - return n -} - -func (m *SendEnabled) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - if m.Enabled { - n += 2 - } - return n -} - -func (m *Input) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovBank(uint64(l)) - } - } - return n -} - -func (m *Output) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovBank(uint64(l)) - } - } - return n -} - -func (m *Supply) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Total) > 0 { - for _, e := range m.Total { - l = e.Size() - n += 1 + l + sovBank(uint64(l)) - } - } - return n -} - -func (m *DenomUnit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - if m.Exponent != 0 { - n += 1 + sovBank(uint64(m.Exponent)) - } - if len(m.Aliases) > 0 { - for _, s := range m.Aliases { - l = len(s) - n += 1 + l + sovBank(uint64(l)) - } - } - return n -} - -func (m *Metadata) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Description) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - if len(m.DenomUnits) > 0 { - for _, e := range m.DenomUnits { - l = e.Size() - n += 1 + l + sovBank(uint64(l)) - } - } - l = len(m.Base) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - l = len(m.Display) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - l = len(m.Name) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - l = len(m.Symbol) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - l = len(m.URI) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - l = len(m.URIHash) - if l > 0 { - n += 1 + l + sovBank(uint64(l)) - } - return n -} - -func sovBank(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozBank(x uint64) (n int) { - return sovBank(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) 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 ErrIntOverflowBank - } - 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: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SendEnabled", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SendEnabled = append(m.SendEnabled, &SendEnabled{}) - if err := m.SendEnabled[len(m.SendEnabled)-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 DefaultSendEnabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.DefaultSendEnabled = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SendEnabled) 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 ErrIntOverflowBank - } - 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: SendEnabled: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SendEnabled: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Enabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Enabled = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Input) 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 ErrIntOverflowBank - } - 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: Input: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Input: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Output) 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 ErrIntOverflowBank - } - 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: Output: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Output: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Supply) 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 ErrIntOverflowBank - } - 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: Supply: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Supply: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Total = append(m.Total, types.Coin{}) - if err := m.Total[len(m.Total)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DenomUnit) 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 ErrIntOverflowBank - } - 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: DenomUnit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DenomUnit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Exponent", wireType) - } - m.Exponent = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Exponent |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Aliases", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Aliases = append(m.Aliases, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Metadata) 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 ErrIntOverflowBank - } - 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: Metadata: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Metadata: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomUnits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomUnits = append(m.DenomUnits, &DenomUnit{}) - if err := m.DenomUnits[len(m.DenomUnits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Base", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Base = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Display", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Display = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Symbol", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Symbol = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field URI", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.URI = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field URIHash", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBank - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthBank - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthBank - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.URIHash = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipBank(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBank - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipBank(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, ErrIntOverflowBank - } - 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, ErrIntOverflowBank - } - 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, ErrIntOverflowBank - } - 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, ErrInvalidLengthBank - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupBank - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthBank - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthBank = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowBank = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupBank = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go deleted file mode 100644 index d23ef9c62..000000000 --- a/x/bank/types/codec.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - "github.com/cosmos/cosmos-sdk/x/authz" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - groupcodec "github.com/cosmos/cosmos-sdk/x/group/codec" -) - -// RegisterLegacyAminoCodec registers the necessary x/bank interfaces and concrete types -// on the provided LegacyAmino codec. These types are used for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgSend{}, "cosmos-sdk/MsgSend") - legacy.RegisterAminoMsg(cdc, &MsgMultiSend{}, "cosmos-sdk/MsgMultiSend") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "cosmos-sdk/x/bank/MsgUpdateParams") - legacy.RegisterAminoMsg(cdc, &MsgSetSendEnabled{}, "cosmos-sdk/MsgSetSendEnabled") - - cdc.RegisterConcrete(&SendAuthorization{}, "cosmos-sdk/SendAuthorization", nil) - cdc.RegisterConcrete(&Params{}, "cosmos-sdk/x/bank/Params", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgSend{}, - &MsgMultiSend{}, - &MsgUpdateParams{}, - ) - registry.RegisterImplementations( - (*authz.Authorization)(nil), - &SendAuthorization{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - sdk.RegisterLegacyAminoCodec(amino) - - // Register all Amino interfaces and concrete types on the authz and gov Amino codec so that this can later be - // used to properly serialize MsgGrant, MsgExec and MsgSubmitProposal instances - RegisterLegacyAminoCodec(authzcodec.Amino) - RegisterLegacyAminoCodec(govcodec.Amino) - RegisterLegacyAminoCodec(groupcodec.Amino) -} diff --git a/x/bank/types/errors.go b/x/bank/types/errors.go deleted file mode 100644 index 13af3dc4c..000000000 --- a/x/bank/types/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// x/bank module sentinel errors -var ( - ErrNoInputs = sdkerrors.Register(ModuleName, 2, "no inputs to send transaction") - ErrNoOutputs = sdkerrors.Register(ModuleName, 3, "no outputs to send transaction") - ErrInputOutputMismatch = sdkerrors.Register(ModuleName, 4, "sum inputs != sum outputs") - ErrSendDisabled = sdkerrors.Register(ModuleName, 5, "send transactions are disabled") - ErrDenomMetadataNotFound = sdkerrors.Register(ModuleName, 6, "client denom metadata not found") - ErrInvalidKey = sdkerrors.Register(ModuleName, 7, "invalid key") - ErrDuplicateEntry = sdkerrors.Register(ModuleName, 8, "duplicate entry") - ErrMultipleSenders = sdkerrors.Register(ModuleName, 9, "multiple senders not allowed") -) diff --git a/x/bank/types/events.go b/x/bank/types/events.go deleted file mode 100644 index 098eebc37..000000000 --- a/x/bank/types/events.go +++ /dev/null @@ -1,60 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// bank module event types -const ( - EventTypeTransfer = "transfer" - - AttributeKeyRecipient = "recipient" - AttributeKeySender = sdk.AttributeKeySender - - // supply and balance tracking events name and attributes - EventTypeCoinSpent = "coin_spent" - EventTypeCoinReceived = "coin_received" - EventTypeCoinMint = "coinbase" // NOTE(fdymylja): using mint clashes with mint module event - EventTypeCoinBurn = "burn" - - AttributeKeySpender = "spender" - AttributeKeyReceiver = "receiver" - AttributeKeyMinter = "minter" - AttributeKeyBurner = "burner" -) - -// NewCoinSpentEvent constructs a new coin spent sdk.Event -func NewCoinSpentEvent(spender sdk.AccAddress, amount sdk.Coins) sdk.Event { - return sdk.NewEvent( - EventTypeCoinSpent, - sdk.NewAttribute(AttributeKeySpender, spender.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - ) -} - -// NewCoinReceivedEvent constructs a new coin received sdk.Event -func NewCoinReceivedEvent(receiver sdk.AccAddress, amount sdk.Coins) sdk.Event { - return sdk.NewEvent( - EventTypeCoinReceived, - sdk.NewAttribute(AttributeKeyReceiver, receiver.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - ) -} - -// NewCoinMintEvent construct a new coin minted sdk.Event -func NewCoinMintEvent(minter sdk.AccAddress, amount sdk.Coins) sdk.Event { - return sdk.NewEvent( - EventTypeCoinMint, - sdk.NewAttribute(AttributeKeyMinter, minter.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - ) -} - -// NewCoinBurnEvent constructs a new coin burned sdk.Event -func NewCoinBurnEvent(burner sdk.AccAddress, amount sdk.Coins) sdk.Event { - return sdk.NewEvent( - EventTypeCoinBurn, - sdk.NewAttribute(AttributeKeyBurner, burner.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - ) -} diff --git a/x/bank/types/expected_keepers.go b/x/bank/types/expected_keepers.go index 191d6b5a8..1ef1dd815 100644 --- a/x/bank/types/expected_keepers.go +++ b/x/bank/types/expected_keepers.go @@ -1,29 +1,27 @@ package types import ( + // minttypes "github.com/ODIN-PROTOCOL/odin-core/x/mint/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + + minttypes "github.com/ODIN-PROTOCOL/odin-core/x/mint/types" ) // AccountKeeper defines the account contract that must be fulfilled when // creating a x/bank keeper. type AccountKeeper interface { - NewAccount(sdk.Context, types.AccountI) types.AccountI - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - GetAllAccounts(ctx sdk.Context) []types.AccountI - HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool - SetAccount(ctx sdk.Context, acc types.AccountI) - - IterateAccounts(ctx sdk.Context, process func(types.AccountI) bool) + GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI +} - ValidatePermissions(macc types.ModuleAccountI) error +// DistributionKeeper defines the distribution contract that must be fulfilled when +// creating a x/bank keeper. +type DistributionKeeper interface { + GetFeePool(sdk.Context) disttypes.FeePool + SetFeePool(sdk.Context, disttypes.FeePool) +} - GetModuleAddress(moduleName string) sdk.AccAddress - GetModuleAddressAndPermissions(moduleName string) (addr sdk.AccAddress, permissions []string) - GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (types.ModuleAccountI, []string) - GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI - SetModuleAccount(ctx sdk.Context, macc types.ModuleAccountI) - GetModulePermissions() map[string]types.PermissionsForAddress +type MintKeeper interface { + GetParams(sdk.Context) minttypes.Params } diff --git a/x/bank/types/genesis.go b/x/bank/types/genesis.go deleted file mode 100644 index e414247f3..000000000 --- a/x/bank/types/genesis.go +++ /dev/null @@ -1,144 +0,0 @@ -package types - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Validate performs basic validation of supply genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if len(gs.Params.SendEnabled) > 0 && len(gs.SendEnabled) > 0 { - return errors.New("send_enabled defined in both the send_enabled field and in params (deprecated)") - } - - if err := gs.Params.Validate(); err != nil { - return err - } - - seenSendEnabled := make(map[string]bool) - seenBalances := make(map[string]bool) - seenMetadatas := make(map[string]bool) - - totalSupply := sdk.Coins{} - - for _, p := range gs.GetAllSendEnabled() { - if _, exists := seenSendEnabled[p.Denom]; exists { - return fmt.Errorf("duplicate send enabled found: '%s'", p.Denom) - } - if err := p.Validate(); err != nil { - return err - } - seenSendEnabled[p.Denom] = true - } - - for _, balance := range gs.Balances { - if seenBalances[balance.Address] { - return fmt.Errorf("duplicate balance for address %s", balance.Address) - } - - if err := balance.Validate(); err != nil { - return err - } - - seenBalances[balance.Address] = true - - totalSupply = totalSupply.Add(balance.Coins...) - } - - for _, metadata := range gs.DenomMetadata { - if seenMetadatas[metadata.Base] { - return fmt.Errorf("duplicate client metadata for denom %s", metadata.Base) - } - - if err := metadata.Validate(); err != nil { - return err - } - - seenMetadatas[metadata.Base] = true - } - - if !gs.Supply.Empty() { - // NOTE: this errors if supply for any given coin is zero - err := gs.Supply.Validate() - if err != nil { - return err - } - - if !gs.Supply.IsEqual(totalSupply) { - return fmt.Errorf("genesis supply is incorrect, expected %v, got %v", gs.Supply, totalSupply) - } - } - - return nil -} - -// NewGenesisState creates a new genesis state. -func NewGenesisState(params Params, balances []Balance, supply sdk.Coins, denomMetaData []Metadata, sendEnabled []SendEnabled) *GenesisState { - rv := &GenesisState{ - Params: params, - Balances: balances, - Supply: supply, - DenomMetadata: denomMetaData, - SendEnabled: sendEnabled, - } - rv.MigrateSendEnabled() - return rv -} - -// DefaultGenesisState returns a default bank module genesis state. -func DefaultGenesisState() *GenesisState { - return NewGenesisState(DefaultParams(), []Balance{}, sdk.Coins{}, []Metadata{}, []SendEnabled{}) -} - -// GetGenesisStateFromAppState returns x/bank GenesisState given raw application -// genesis state. -func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { - var genesisState GenesisState - - if appState[ModuleName] != nil { - cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState) - } - - return &genesisState -} - -// MigrateSendEnabled moves the SendEnabled info from Params into the -// GenesisState.SendEnabled field and removes them from Params. If the -// Params.SendEnabled slice is empty, this is a noop. -// -// If the main SendEnabled slice already has entries, the Params.SendEnabled -// entries are added. In case of the same demon in both, preference is given to -// the existing (main GenesisState field) entry. -func (g *GenesisState) MigrateSendEnabled() { - g.SendEnabled = g.GetAllSendEnabled() - g.Params.SendEnabled = nil -} - -// GetAllSendEnabled returns all the SendEnabled entries from both the SendEnabled -// field and the Params. If a denom has an entry in both, the entry in the -// SendEnabled field takes precedence over one in Params. -func (g GenesisState) GetAllSendEnabled() []SendEnabled { - if len(g.Params.SendEnabled) == 0 { - return g.SendEnabled - } - - rv := make([]SendEnabled, len(g.SendEnabled)) - knownSendEnabled := map[string]bool{} - for i, se := range g.SendEnabled { - rv[i] = se - knownSendEnabled[se.Denom] = true - } - - for _, se := range g.Params.SendEnabled { - if _, known := knownSendEnabled[se.Denom]; !known { - rv = append(rv, *se) - } - } - - return rv -} diff --git a/x/bank/types/genesis.pb.go b/x/bank/types/genesis.pb.go deleted file mode 100644 index af5383cc7..000000000 --- a/x/bank/types/genesis.pb.go +++ /dev/null @@ -1,818 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/bank/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/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 bank module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // balances is an array containing the balances of all the accounts. - Balances []Balance `protobuf:"bytes,2,rep,name=balances,proto3" json:"balances"` - // supply represents the total supply. If it is left empty, then supply will be calculated based on the provided - // balances. Otherwise, it will be used to validate that the sum of the balances equals this amount. - Supply github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=supply,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"supply"` - // denom_metadata defines the metadata of the different coins. - DenomMetadata []Metadata `protobuf:"bytes,4,rep,name=denom_metadata,json=denomMetadata,proto3" json:"denom_metadata"` - // send_enabled defines the denoms where send is enabled or disabled. - // - // Since: cosmos-sdk 0.47 - SendEnabled []SendEnabled `protobuf:"bytes,5,rep,name=send_enabled,json=sendEnabled,proto3" json:"send_enabled"` -} - -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_8f007de11b420c6e, []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) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetBalances() []Balance { - if m != nil { - return m.Balances - } - return nil -} - -func (m *GenesisState) GetSupply() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Supply - } - return nil -} - -func (m *GenesisState) GetDenomMetadata() []Metadata { - if m != nil { - return m.DenomMetadata - } - return nil -} - -func (m *GenesisState) GetSendEnabled() []SendEnabled { - if m != nil { - return m.SendEnabled - } - return nil -} - -// Balance defines an account address and balance pair used in the bank module's -// genesis state. -type Balance struct { - // address is the address of the balance holder. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // coins defines the different coins this balance holds. - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *Balance) Reset() { *m = Balance{} } -func (m *Balance) String() string { return proto.CompactTextString(m) } -func (*Balance) ProtoMessage() {} -func (*Balance) Descriptor() ([]byte, []int) { - return fileDescriptor_8f007de11b420c6e, []int{1} -} -func (m *Balance) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Balance) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Balance.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 *Balance) XXX_Merge(src proto.Message) { - xxx_messageInfo_Balance.Merge(m, src) -} -func (m *Balance) XXX_Size() int { - return m.Size() -} -func (m *Balance) XXX_DiscardUnknown() { - xxx_messageInfo_Balance.DiscardUnknown(m) -} - -var xxx_messageInfo_Balance proto.InternalMessageInfo - -func init() { - proto.RegisterType((*GenesisState)(nil), "cosmos.bank.v1beta1.GenesisState") - proto.RegisterType((*Balance)(nil), "cosmos.bank.v1beta1.Balance") -} - -func init() { proto.RegisterFile("cosmos/bank/v1beta1/genesis.proto", fileDescriptor_8f007de11b420c6e) } - -var fileDescriptor_8f007de11b420c6e = []byte{ - // 445 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x92, 0xbd, 0xae, 0xd3, 0x30, - 0x1c, 0xc5, 0x13, 0xca, 0xed, 0xbd, 0xd7, 0xbd, 0x20, 0x61, 0x3a, 0xa4, 0x05, 0x92, 0xd2, 0xa9, - 0x20, 0x35, 0x51, 0x8b, 0x58, 0x18, 0x90, 0x48, 0x85, 0x98, 0xf8, 0x50, 0xbb, 0xb1, 0x54, 0x4e, - 0x6c, 0xd2, 0xa8, 0x8d, 0x1d, 0xc5, 0x2e, 0xa2, 0x6f, 0xc0, 0xc8, 0x13, 0xa0, 0x8e, 0x88, 0x05, - 0x06, 0x1e, 0xa2, 0x63, 0xc5, 0xc4, 0x04, 0xa8, 0x1d, 0xe0, 0x31, 0x50, 0x6c, 0x37, 0x8d, 0x44, - 0xc4, 0xc4, 0x92, 0x44, 0x3e, 0xe7, 0xfc, 0xfe, 0x27, 0xb6, 0xc1, 0xed, 0x90, 0xf1, 0x84, 0x71, - 0x2f, 0x40, 0x74, 0xee, 0xbd, 0x1e, 0x04, 0x44, 0xa0, 0x81, 0x17, 0x11, 0x4a, 0x78, 0xcc, 0xdd, - 0x34, 0x63, 0x82, 0xc1, 0xeb, 0xca, 0xe2, 0xe6, 0x16, 0x57, 0x5b, 0xda, 0xcd, 0x88, 0x45, 0x4c, - 0xea, 0x5e, 0xfe, 0xa5, 0xac, 0x6d, 0xbb, 0xa0, 0x71, 0x52, 0xd0, 0x42, 0x16, 0xd3, 0xbf, 0xf4, - 0xd2, 0x34, 0xc9, 0x55, 0x7a, 0x4b, 0xe9, 0x53, 0x05, 0xd6, 0x73, 0x95, 0x74, 0x0d, 0x25, 0x31, - 0x65, 0x9e, 0x7c, 0xaa, 0xa5, 0xee, 0xfb, 0x1a, 0xb8, 0x78, 0xa2, 0xaa, 0x4e, 0x04, 0x12, 0x04, - 0x3e, 0x04, 0xf5, 0x14, 0x65, 0x28, 0xe1, 0x96, 0xd9, 0x31, 0x7b, 0x8d, 0xe1, 0x0d, 0xb7, 0xa2, - 0xba, 0xfb, 0x42, 0x5a, 0xfc, 0xf3, 0xcd, 0x77, 0xc7, 0xf8, 0xf0, 0xeb, 0xf3, 0x5d, 0x73, 0xac, - 0x53, 0x70, 0x04, 0xce, 0x02, 0xb4, 0x40, 0x34, 0x24, 0xdc, 0xba, 0xd4, 0xa9, 0xf5, 0x1a, 0xc3, - 0x9b, 0x95, 0x04, 0x5f, 0x99, 0xca, 0x88, 0x22, 0x08, 0x67, 0xa0, 0xce, 0x97, 0x69, 0xba, 0x58, - 0x59, 0x35, 0x89, 0x68, 0x1d, 0x11, 0x9c, 0x14, 0x88, 0x11, 0x8b, 0xa9, 0x7f, 0x3f, 0xcf, 0x7f, - 0xfc, 0xe1, 0xf4, 0xa2, 0x58, 0xcc, 0x96, 0x81, 0x1b, 0xb2, 0x44, 0xff, 0xb4, 0x7e, 0xf5, 0x39, - 0x9e, 0x7b, 0x62, 0x95, 0x12, 0x2e, 0x03, 0x5c, 0xd7, 0x55, 0x7c, 0xf8, 0x1c, 0x5c, 0xc5, 0x84, - 0xb2, 0x64, 0x9a, 0x10, 0x81, 0x30, 0x12, 0xc8, 0xba, 0x2c, 0x27, 0xde, 0xaa, 0x2c, 0xfd, 0x54, - 0x9b, 0xca, 0xad, 0xaf, 0xc8, 0xfc, 0x41, 0x81, 0xcf, 0xc0, 0x05, 0x27, 0x14, 0x4f, 0x09, 0x45, - 0xc1, 0x82, 0x60, 0xeb, 0x44, 0xe2, 0x3a, 0x95, 0xb8, 0x09, 0xa1, 0xf8, 0xb1, 0xf2, 0x95, 0x89, - 0x0d, 0x7e, 0x5c, 0xef, 0x7e, 0x32, 0xc1, 0xa9, 0xde, 0x2b, 0x38, 0x04, 0xa7, 0x08, 0xe3, 0x8c, - 0x70, 0x75, 0x38, 0xe7, 0xbe, 0xf5, 0xf5, 0x4b, 0xbf, 0xa9, 0xc9, 0x8f, 0x94, 0x32, 0x11, 0x59, - 0x4c, 0xa3, 0xf1, 0xc1, 0x08, 0x5f, 0x81, 0x93, 0xfc, 0xf2, 0x1c, 0x0e, 0xe3, 0xff, 0xef, 0xa4, - 0xc2, 0x3f, 0x38, 0x7b, 0xbb, 0x76, 0x8c, 0xdf, 0x6b, 0xc7, 0xf0, 0x47, 0x9b, 0x9d, 0x6d, 0x6e, - 0x77, 0xb6, 0xf9, 0x73, 0x67, 0x9b, 0xef, 0xf6, 0xb6, 0xb1, 0xdd, 0xdb, 0xc6, 0xb7, 0xbd, 0x6d, - 0xbc, 0xbc, 0xf3, 0x4f, 0xf2, 0x1b, 0x75, 0xa5, 0xe5, 0x80, 0xa0, 0x2e, 0xaf, 0xe7, 0xbd, 0x3f, - 0x01, 0x00, 0x00, 0xff, 0xff, 0x5d, 0x88, 0xa3, 0x71, 0x5c, 0x03, 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 len(m.SendEnabled) > 0 { - for iNdEx := len(m.SendEnabled) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SendEnabled[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.DenomMetadata) > 0 { - for iNdEx := len(m.DenomMetadata) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomMetadata[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Supply) > 0 { - for iNdEx := len(m.Supply) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Supply[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Balances) > 0 { - for iNdEx := len(m.Balances) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Balances[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.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 (m *Balance) 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 *Balance) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Balance) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Address))) - 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 - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Balances) > 0 { - for _, e := range m.Balances { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Supply) > 0 { - for _, e := range m.Supply { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DenomMetadata) > 0 { - for _, e := range m.DenomMetadata { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.SendEnabled) > 0 { - for _, e := range m.SendEnabled { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Balance) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - 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 Params", 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 - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balances", 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.Balances = append(m.Balances, Balance{}) - if err := m.Balances[len(m.Balances)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supply", 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.Supply = append(m.Supply, types.Coin{}) - if err := m.Supply[len(m.Supply)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomMetadata", 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.DenomMetadata = append(m.DenomMetadata, Metadata{}) - if err := m.DenomMetadata[len(m.DenomMetadata)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SendEnabled", 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.SendEnabled = append(m.SendEnabled, SendEnabled{}) - if err := m.SendEnabled[len(m.SendEnabled)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Balance) 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: Balance: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Balance: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", 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.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (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/bank/types/genesis_test.go b/x/bank/types/genesis_test.go deleted file mode 100644 index 074825c32..000000000 --- a/x/bank/types/genesis_test.go +++ /dev/null @@ -1,509 +0,0 @@ -package types - -import ( - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestGenesisStateValidate(t *testing.T) { - testCases := []struct { - name string - genesisState GenesisState - expErr bool - }{ - { - "valid genesisState", - GenesisState{ - Params: DefaultParams(), - Balances: []Balance{ - { - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{sdk.NewInt64Coin("uatom", 1)}, - }, - }, - Supply: sdk.Coins{sdk.NewInt64Coin("uatom", 1)}, - DenomMetadata: []Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - }, - }, - false, - }, - {"empty genesisState", GenesisState{}, false}, - { - "invalid params ", - GenesisState{ - Params: Params{ - SendEnabled: []*SendEnabled{ - {"", true}, - }, - }, - }, - true, - }, - { - "dup balances", - GenesisState{ - Balances: []Balance{ - { - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{sdk.NewInt64Coin("uatom", 1)}, - }, - { - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - Coins: sdk.Coins{sdk.NewInt64Coin("uatom", 1)}, - }, - }, - }, - true, - }, - { - "0 balance", - GenesisState{ - Balances: []Balance{ - { - Address: "cosmos1yq8lgssgxlx9smjhes6ryjasmqmd3ts2559g0t", - }, - }, - }, - false, - }, - { - "dup Metadata", - GenesisState{ - DenomMetadata: []Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - }, - }, - true, - }, - { - "invalid Metadata", - GenesisState{ - DenomMetadata: []Metadata{ - { - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "", - Display: "", - }, - }, - }, - true, - }, - { - "invalid supply", - GenesisState{ - Supply: sdk.Coins{sdk.Coin{Denom: "", Amount: math.OneInt()}}, - }, - true, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - err := tc.genesisState.Validate() - - if tc.expErr { - require.Error(tt, err) - } else { - require.NoError(tt, err) - } - }) - } -} - -func TestMigrateSendEnabled(t *testing.T) { - tests := []struct { - name string - oldState *GenesisState - newState *GenesisState - }{ - { - name: "Balances supply metadata all unchanged", - oldState: &GenesisState{ - Params: Params{}, - Balances: []Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, - DenomMetadata: []Metadata{{ - Description: "metadesk", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - }, - newState: &GenesisState{ - Params: Params{}, - Balances: []Balance{{ - Address: "balance1", - Coins: sdk.Coins{sdk.NewCoin("balance1coin", sdk.NewInt(8))}, - }}, - Supply: sdk.Coins{sdk.NewCoin("supplycoin", sdk.NewInt(800))}, - DenomMetadata: []Metadata{{ - Description: "metadesk", - DenomUnits: nil, - Base: "meta", - Display: "meta", - Name: "foo", - Symbol: "META", - URI: "", - URIHash: "", - }}, - }, - }, - - { - name: "default send enabled true not changed", - oldState: &GenesisState{ - Params: Params{DefaultSendEnabled: true}, - }, - newState: &GenesisState{ - Params: Params{DefaultSendEnabled: true}, - }, - }, - { - name: "default send enabled false not changed", - oldState: &GenesisState{ - Params: Params{DefaultSendEnabled: false, SendEnabled: []*SendEnabled{}}, - }, - newState: &GenesisState{ - Params: Params{DefaultSendEnabled: false}, - }, - }, - { - name: "send enabled entries moved", - oldState: &GenesisState{ - Params: Params{ - SendEnabled: []*SendEnabled{ - {"movecointrue", true}, - {"movecoinfalse", false}, - }, - }, - }, - newState: &GenesisState{ - Params: Params{}, - SendEnabled: []SendEnabled{ - {"movecointrue", true}, - {"movecoinfalse", false}, - }, - }, - }, - { - name: "params entries added to existing", - oldState: &GenesisState{ - Params: Params{ - SendEnabled: []*SendEnabled{ - {"movecointrue", true}, - {"movecoinfalse", false}, - }, - }, - SendEnabled: []SendEnabled{ - {"staycoin", true}, - }, - }, - newState: &GenesisState{ - Params: Params{}, - SendEnabled: []SendEnabled{ - {"staycoin", true}, - {"movecointrue", true}, - {"movecoinfalse", false}, - }, - }, - }, - { - name: "conflicting params ignored", - oldState: &GenesisState{ - Params: Params{ - SendEnabled: []*SendEnabled{ - {"staycoin", false}, - }, - }, - SendEnabled: []SendEnabled{ - {"staycoin", true}, - }, - }, - newState: &GenesisState{ - Params: Params{}, - SendEnabled: []SendEnabled{ - {"staycoin", true}, - }, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(tt *testing.T) { - tc.oldState.MigrateSendEnabled() - assert.Equal(tt, tc.newState, tc.oldState) - }) - } -} - -func TestGetAllSendEnabled(t *testing.T) { - tests := []struct { - name string - gs GenesisState - exp []SendEnabled - }{ - { - name: "nil and nil", - gs: GenesisState{ - SendEnabled: nil, - Params: Params{ - SendEnabled: nil, - }, - }, - exp: nil, - }, - { - name: "nil and empty", - gs: GenesisState{ - SendEnabled: nil, - Params: Params{ - SendEnabled: []*SendEnabled{}, - }, - }, - exp: nil, - }, - { - name: "empty and nil", - gs: GenesisState{ - SendEnabled: []SendEnabled{}, - Params: Params{ - SendEnabled: nil, - }, - }, - exp: []SendEnabled{}, - }, - { - name: "empty and empty", - gs: GenesisState{ - SendEnabled: []SendEnabled{}, - Params: Params{ - SendEnabled: []*SendEnabled{}, - }, - }, - exp: []SendEnabled{}, - }, - { - name: "one and nil", - gs: GenesisState{ - SendEnabled: []SendEnabled{{"onenilcoin", true}}, - Params: Params{ - SendEnabled: nil, - }, - }, - exp: []SendEnabled{{"onenilcoin", true}}, - }, - { - name: "one and empty", - gs: GenesisState{ - SendEnabled: []SendEnabled{{"oneemptycoin", true}}, - Params: Params{ - SendEnabled: []*SendEnabled{}, - }, - }, - exp: []SendEnabled{{"oneemptycoin", true}}, - }, - { - name: "nil and one", - gs: GenesisState{ - SendEnabled: nil, - Params: Params{ - SendEnabled: []*SendEnabled{{"nilonecoin", true}}, - }, - }, - exp: []SendEnabled{{"nilonecoin", true}}, - }, - { - name: "empty and one", - gs: GenesisState{ - SendEnabled: []SendEnabled{}, - Params: Params{ - SendEnabled: []*SendEnabled{{"emptyonecoin", true}}, - }, - }, - exp: []SendEnabled{{"emptyonecoin", true}}, - }, - { - name: "one and one different denoms", - gs: GenesisState{ - SendEnabled: []SendEnabled{{"oneonediff1coin", true}}, - Params: Params{ - SendEnabled: []*SendEnabled{{"oneonediff2coin", false}}, - }, - }, - exp: []SendEnabled{{"oneonediff1coin", true}, {"oneonediff2coin", false}}, - }, - { - name: "one and one same denoms true", - gs: GenesisState{ - SendEnabled: []SendEnabled{{"oneonesametruecoin", true}}, - Params: Params{ - SendEnabled: []*SendEnabled{{"oneonesametruecoin", false}}, - }, - }, - exp: []SendEnabled{{"oneonesametruecoin", true}}, - }, - { - name: "one and one same denoms false", - gs: GenesisState{ - SendEnabled: []SendEnabled{{"oneonesamefalsecoin", false}}, - Params: Params{ - SendEnabled: []*SendEnabled{{"oneonesamefalsecoin", true}}, - }, - }, - exp: []SendEnabled{{"oneonesamefalsecoin", false}}, - }, - { - name: "three and three with one same denom", - gs: GenesisState{ - SendEnabled: []SendEnabled{ - {"threethree1coin", true}, - {"threethree2coin", true}, - {"threethree3coin", true}, - }, - Params: Params{ - SendEnabled: []*SendEnabled{ - {"threethree4coin", true}, - {"threethree2coin", false}, - {"threethree5coin", true}, - }, - }, - }, - exp: []SendEnabled{ - {"threethree1coin", true}, - {"threethree2coin", true}, - {"threethree3coin", true}, - {"threethree4coin", true}, - {"threethree5coin", true}, - }, - }, - { - name: "three and three all overlap", - gs: GenesisState{ - SendEnabled: []SendEnabled{ - {"threethreedup1coin", false}, - {"threethreedup2coin", true}, - {"threethreedup3coin", false}, - }, - Params: Params{ - SendEnabled: []*SendEnabled{ - {"threethreedup1coin", true}, - {"threethreedup2coin", false}, - {"threethreedup3coin", true}, - }, - }, - }, - exp: []SendEnabled{ - {"threethreedup1coin", false}, - {"threethreedup2coin", true}, - {"threethreedup3coin", false}, - }, - }, - { - name: "three and three no overlap", - gs: GenesisState{ - SendEnabled: []SendEnabled{ - {"threethreediff1coin", true}, - {"threethreediff2coin", false}, - {"threethreediff3coin", true}, - }, - Params: Params{ - SendEnabled: []*SendEnabled{ - {"threethreediff4coin", false}, - {"threethreediff5coin", true}, - {"threethreediff6coin", false}, - }, - }, - }, - exp: []SendEnabled{ - {"threethreediff1coin", true}, - {"threethreediff2coin", false}, - {"threethreediff3coin", true}, - {"threethreediff4coin", false}, - {"threethreediff5coin", true}, - {"threethreediff6coin", false}, - }, - }, - { - name: "one and three with overlap", - gs: GenesisState{ - SendEnabled: []SendEnabled{ - {"onethreeover1coin", false}, - }, - Params: Params{ - SendEnabled: []*SendEnabled{ - {"onethreeover1coin", true}, - {"onethreeover2coin", true}, - {"onethreeover3coin", false}, - }, - }, - }, - exp: []SendEnabled{ - {"onethreeover1coin", false}, - {"onethreeover2coin", true}, - {"onethreeover3coin", false}, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(tt *testing.T) { - actual := tc.gs.GetAllSendEnabled() - assert.Equal(tt, tc.exp, actual) - }) - } -} diff --git a/x/bank/types/keys.go b/x/bank/types/keys.go deleted file mode 100644 index a7ba7114d..000000000 --- a/x/bank/types/keys.go +++ /dev/null @@ -1,89 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/kv" -) - -const ( - // ModuleName defines the module name - ModuleName = "bank" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey defines the module's message routing key - RouterKey = ModuleName - - // ModuleQueryPath defines the ABCI query path of the module - ModuleQueryPath = "store/bank/key" -) - -// KVStore keys -var ( - SupplyKey = []byte{0x00} - DenomMetadataPrefix = []byte{0x1} - DenomAddressPrefix = []byte{0x03} - - // BalancesPrefix is the prefix for the account balances store. We use a byte - // (instead of `[]byte("balances")` to save some disk space). - BalancesPrefix = []byte{0x02} - - // SendEnabledPrefix is the prefix for the SendDisabled flags for a Denom. - SendEnabledPrefix = []byte{0x04} - - // ParamsKey is the prefix for x/bank parameters - ParamsKey = []byte{0x05} -) - -// AddressAndDenomFromBalancesStore returns an account address and denom from a balances prefix -// store. The key must not contain the prefix BalancesPrefix as the prefix store -// iterator discards the actual prefix. -// -// If invalid key is passed, AddressAndDenomFromBalancesStore returns ErrInvalidKey. -func AddressAndDenomFromBalancesStore(key []byte) (sdk.AccAddress, string, error) { - if len(key) == 0 { - return nil, "", ErrInvalidKey - } - - kv.AssertKeyAtLeastLength(key, 1) - - addrBound := int(key[0]) - - if len(key)-1 < addrBound { - return nil, "", ErrInvalidKey - } - - return key[1 : addrBound+1], string(key[addrBound+1:]), nil -} - -// CreatePrefixedAccountStoreKey returns the key for the given account and denomination. -// This method can be used when performing an ABCI query for the balance of an account. -func CreatePrefixedAccountStoreKey(addr []byte, denom []byte) []byte { - return append(CreateAccountBalancesPrefix(addr), denom...) -} - -// CreateAccountBalancesPrefix creates the prefix for an account's balances. -func CreateAccountBalancesPrefix(addr []byte) []byte { - return append(BalancesPrefix, address.MustLengthPrefix(addr)...) -} - -// CreateDenomAddressPrefix creates a prefix for a reverse index of denomination -// to account balance for that denomination. -func CreateDenomAddressPrefix(denom string) []byte { - // we add a "zero" byte at the end - null byte terminator, to allow prefix denom prefix - // scan. Setting it is not needed (key[last] = 0) - because this is the default. - key := make([]byte, len(DenomAddressPrefix)+len(denom)+1) - copy(key, DenomAddressPrefix) - copy(key[len(DenomAddressPrefix):], denom) - return key -} - -// CreateSendEnabledKey creates the key of the SendDisabled flag for a denom. -func CreateSendEnabledKey(denom string) []byte { - key := make([]byte, len(SendEnabledPrefix)+len(denom)) - copy(key, SendEnabledPrefix) - copy(key[len(SendEnabledPrefix):], denom) - return key -} diff --git a/x/bank/types/keys_test.go b/x/bank/types/keys_test.go deleted file mode 100644 index bfffdc2f6..000000000 --- a/x/bank/types/keys_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package types_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func cloneAppend(bz []byte, tail []byte) (res []byte) { - res = make([]byte, len(bz)+len(tail)) - copy(res, bz) - copy(res[len(bz):], tail) - return -} - -func TestAddressFromBalancesStore(t *testing.T) { - addr, err := sdk.AccAddressFromBech32("cosmos1n88uc38xhjgxzw9nwre4ep2c8ga4fjxcar6mn7") - require.NoError(t, err) - addrLen := len(addr) - require.Equal(t, 20, addrLen) - key := cloneAppend(address.MustLengthPrefix(addr), []byte("stake")) - - tests := []struct { - name string - key []byte - wantErr bool - expectedKey sdk.AccAddress - }{ - {"valid", key, false, addr}, - {"#9111", []byte("\xff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), false, nil}, - {"empty", []byte(""), true, nil}, - {"invalid", []byte("3AA"), true, nil}, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - addr, denom, err := types.AddressAndDenomFromBalancesStore(tc.key) - if tc.wantErr { - assert.Error(t, err) - assert.True(t, errors.Is(types.ErrInvalidKey, err)) - } else { - assert.NoError(t, err) - } - if len(tc.expectedKey) > 0 { - assert.Equal(t, tc.expectedKey, addr) - assert.Equal(t, "stake", denom) - } - }) - } -} - -func TestCreateDenomAddressPrefix(t *testing.T) { - require := require.New(t) - - key := types.CreateDenomAddressPrefix("") - require.Len(key, len(types.DenomAddressPrefix)+1) - require.Equal(append(types.DenomAddressPrefix, 0), key) - - key = types.CreateDenomAddressPrefix("abc") - require.Len(key, len(types.DenomAddressPrefix)+4) - require.Equal(append(types.DenomAddressPrefix, 'a', 'b', 'c', 0), key) -} - -func TestCreateSendEnabledKey(t *testing.T) { - denom := "bazcoin" - expected := cloneAppend(types.SendEnabledPrefix, []byte(denom)) - actual := types.CreateSendEnabledKey(denom) - assert.Equal(t, expected, actual, "full byte slice") - assert.Equal(t, types.SendEnabledPrefix, actual[:len(types.SendEnabledPrefix)], "prefix") - assert.Equal(t, []byte(denom), actual[len(types.SendEnabledPrefix):], "denom part") -} diff --git a/x/bank/types/metadata.go b/x/bank/types/metadata.go deleted file mode 100644 index a6df1bf42..000000000 --- a/x/bank/types/metadata.go +++ /dev/null @@ -1,100 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Validate performs a basic validation of the coin metadata fields. It checks: -// - Name and Symbol are not blank -// - Base and Display denominations are valid coin denominations -// - Base and Display denominations are present in the DenomUnit slice -// - Base denomination has exponent 0 -// - Denomination units are sorted in ascending order -// - Denomination units not duplicated -func (m Metadata) Validate() error { - if strings.TrimSpace(m.Name) == "" { - return errors.New("name field cannot be blank") - } - - if strings.TrimSpace(m.Symbol) == "" { - return errors.New("symbol field cannot be blank") - } - - if err := sdk.ValidateDenom(m.Base); err != nil { - return fmt.Errorf("invalid metadata base denom: %w", err) - } - - if err := sdk.ValidateDenom(m.Display); err != nil { - return fmt.Errorf("invalid metadata display denom: %w", err) - } - - var ( - hasDisplay bool - currentExponent uint32 // check that the exponents are increasing - ) - - seenUnits := make(map[string]bool) - - for i, denomUnit := range m.DenomUnits { - // The first denomination unit MUST be the base - if i == 0 { - // validate denomination and exponent - if denomUnit.Denom != m.Base { - return fmt.Errorf("metadata's first denomination unit must be the one with base denom '%s'", m.Base) - } - if denomUnit.Exponent != 0 { - return fmt.Errorf("the exponent for base denomination unit %s must be 0", m.Base) - } - } else if currentExponent >= denomUnit.Exponent { - return errors.New("denom units should be sorted asc by exponent") - } - - currentExponent = denomUnit.Exponent - - if seenUnits[denomUnit.Denom] { - return fmt.Errorf("duplicate denomination unit %s", denomUnit.Denom) - } - - if denomUnit.Denom == m.Display { - hasDisplay = true - } - - if err := denomUnit.Validate(); err != nil { - return err - } - - seenUnits[denomUnit.Denom] = true - } - - if !hasDisplay { - return fmt.Errorf("metadata must contain a denomination unit with display denom '%s'", m.Display) - } - - return nil -} - -// Validate performs a basic validation of the denomination unit fields -func (du DenomUnit) Validate() error { - if err := sdk.ValidateDenom(du.Denom); err != nil { - return fmt.Errorf("invalid denom unit: %w", err) - } - - seenAliases := make(map[string]bool) - for _, alias := range du.Aliases { - if seenAliases[alias] { - return fmt.Errorf("duplicate denomination unit alias %s", alias) - } - - if strings.TrimSpace(alias) == "" { - return fmt.Errorf("alias for denom unit %s cannot be blank", du.Denom) - } - - seenAliases[alias] = true - } - - return nil -} diff --git a/x/bank/types/metadata_test.go b/x/bank/types/metadata_test.go deleted file mode 100644 index 34ff32f6a..000000000 --- a/x/bank/types/metadata_test.go +++ /dev/null @@ -1,277 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -func TestMetadataValidate(t *testing.T) { - testCases := []struct { - name string - metadata types.Metadata - expErr bool - }{ - { - "non-empty coins", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - false, - }, - { - "base coin is display coin", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"atom", uint32(0), []string{"ATOM"}}, - }, - Base: "atom", - Display: "atom", - }, - false, - }, - {"empty metadata", types.Metadata{}, true}, - { - "blank name", - types.Metadata{ - Name: "", - }, - true, - }, - { - "blank symbol", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "", - }, - true, - }, - { - "invalid base denom", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Base: "", - }, - true, - }, - { - "invalid display denom", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Base: "uatom", - Display: "", - }, - true, - }, - { - "duplicate denom unit", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"uatom", uint32(1), []string{"microatom"}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "invalid denom unit", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"", uint32(0), []string{"microatom"}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "invalid denom unit alias", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{""}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "duplicate denom unit alias", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom", "microatom"}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "no base denom unit", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "base denom exponent not zero", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(1), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "invalid denom unit", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"", uint32(3), []string{"milliatom"}}, - }, - Base: "uatom", - Display: "uatom", - }, - true, - }, - { - "no display denom unit", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - { - "denom units not sorted", - types.Metadata{ - Name: "Cosmos Hub Atom", - Symbol: "ATOM", - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"atom", uint32(6), nil}, - {"matom", uint32(3), []string{"milliatom"}}, - }, - Base: "uatom", - Display: "atom", - }, - true, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.metadata.Validate() - - if tc.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMarshalJSONMetaData(t *testing.T) { - cdc := codec.NewLegacyAmino() - - testCases := []struct { - name string - input []types.Metadata - strOutput string - }{ - {"nil metadata", nil, `null`}, - {"empty metadata", []types.Metadata{}, `[]`}, - { - "non-empty coins", - []types.Metadata{ - { - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, // The default exponent value 0 is omitted in the json - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, - }, - Base: "uatom", - Display: "atom", - }, - }, - `[{"description":"The native staking token of the Cosmos Hub.","denom_units":[{"denom":"uatom","aliases":["microatom"]},{"denom":"matom","exponent":3,"aliases":["milliatom"]},{"denom":"atom","exponent":6}],"base":"uatom","display":"atom"}]`, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - bz, err := cdc.MarshalJSON(tc.input) - require.NoError(t, err) - require.Equal(t, tc.strOutput, string(bz)) - - var newMetadata []types.Metadata - require.NoError(t, cdc.UnmarshalJSON(bz, &newMetadata)) - - if len(tc.input) == 0 { - require.Nil(t, newMetadata) - } else { - require.Equal(t, tc.input, newMetadata) - } - }) - } -} diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go deleted file mode 100644 index 81be11f5a..000000000 --- a/x/bank/types/msgs.go +++ /dev/null @@ -1,263 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// bank message types -const ( - TypeMsgSend = "send" - TypeMsgMultiSend = "multisend" - TypeMsgSetSendEnabled = "set_send_enabled" - TypeMsgUpdateParams = "update_params" -) - -var ( - _ sdk.Msg = &MsgSend{} - _ sdk.Msg = &MsgMultiSend{} - _ sdk.Msg = &MsgUpdateParams{} -) - -// NewMsgSend - construct a msg to send coins from one account to another. -// -//nolint:interfacer -func NewMsgSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgSend { - return &MsgSend{FromAddress: fromAddr.String(), ToAddress: toAddr.String(), Amount: amount} -} - -// Route Implements Msg. -func (msg MsgSend) Route() string { return RouterKey } - -// Type Implements Msg. -func (msg MsgSend) Type() string { return TypeMsgSend } - -// ValidateBasic Implements Msg. -func (msg MsgSend) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.FromAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) - } - - if _, err := sdk.AccAddressFromBech32(msg.ToAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err) - } - - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - if !msg.Amount.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - - return nil -} - -// GetSignBytes Implements Msg. -func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -// GetSigners Implements Msg. -func (msg MsgSend) GetSigners() []sdk.AccAddress { - fromAddress, _ := sdk.AccAddressFromBech32(msg.FromAddress) - return []sdk.AccAddress{fromAddress} -} - -// NewMsgMultiSend - construct arbitrary multi-in, multi-out send msg. -func NewMsgMultiSend(in []Input, out []Output) *MsgMultiSend { - return &MsgMultiSend{Inputs: in, Outputs: out} -} - -// Route Implements Msg -func (msg MsgMultiSend) Route() string { return RouterKey } - -// Type Implements Msg -func (msg MsgMultiSend) Type() string { return TypeMsgMultiSend } - -// ValidateBasic Implements Msg. -func (msg MsgMultiSend) ValidateBasic() error { - // this just makes sure the input and all the outputs are properly formatted, - // not that they actually have the money inside - - if len(msg.Inputs) == 0 { - return ErrNoInputs - } - - if len(msg.Inputs) != 1 { - return ErrMultipleSenders - } - - if len(msg.Outputs) == 0 { - return ErrNoOutputs - } - - return ValidateInputsOutputs(msg.Inputs, msg.Outputs) -} - -// GetSignBytes Implements Msg. -func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -// GetSigners Implements Msg. -func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { - addrs := make([]sdk.AccAddress, len(msg.Inputs)) - for i, in := range msg.Inputs { - inAddr, _ := sdk.AccAddressFromBech32(in.Address) - addrs[i] = inAddr - } - - return addrs -} - -// ValidateBasic - validate transaction input -func (in Input) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(in.Address); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid input address: %s", err) - } - - if !in.Coins.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - - if !in.Coins.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String()) - } - - return nil -} - -// NewInput - create a transaction input, used with MsgMultiSend -// -//nolint:interfacer -func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { - return Input{ - Address: addr.String(), - Coins: coins, - } -} - -// ValidateBasic - validate transaction output -func (out Output) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(out.Address); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid output address: %s", err) - } - - if !out.Coins.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - - if !out.Coins.IsAllPositive() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String()) - } - - return nil -} - -// NewOutput - create a transaction output, used with MsgMultiSend -// -//nolint:interfacer -func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { - return Output{ - Address: addr.String(), - Coins: coins, - } -} - -// ValidateInputsOutputs validates that each respective input and output is -// valid and that the sum of inputs is equal to the sum of outputs. -func ValidateInputsOutputs(inputs []Input, outputs []Output) error { - var totalIn, totalOut sdk.Coins - - for _, in := range inputs { - if err := in.ValidateBasic(); err != nil { - return err - } - totalIn = totalIn.Add(in.Coins...) - } - - for _, out := range outputs { - if err := out.ValidateBasic(); err != nil { - return err - } - - totalOut = totalOut.Add(out.Coins...) - } - - // make sure inputs and outputs match - if !totalIn.IsEqual(totalOut) { - return ErrInputOutputMismatch - } - - return nil -} - -// GetSigners returns the signer addresses that are expected to sign the result -// of GetSignBytes. -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - authority, _ := sdk.AccAddressFromBech32(msg.Authority) - return []sdk.AccAddress{authority} -} - -// GetSignBytes returns the raw bytes for a MsgUpdateParams message that -// the expected signer needs to sign. -func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - return msg.Params.Validate() -} - -// NewMsgSetSendEnabled Construct a message to set one or more SendEnabled entries. -func NewMsgSetSendEnabled(authority string, sendEnabled []*SendEnabled, useDefaultFor []string) *MsgSetSendEnabled { - return &MsgSetSendEnabled{ - Authority: authority, - SendEnabled: sendEnabled, - UseDefaultFor: useDefaultFor, - } -} - -// GetSignBytes implements the LegacyMsg interface. -func (msg MsgSetSendEnabled) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -// GetSigners returns the expected signers for MsgSoftwareUpgrade. -func (msg MsgSetSendEnabled) GetSigners() []sdk.AccAddress { - addr, _ := sdk.AccAddressFromBech32(msg.Authority) - return []sdk.AccAddress{addr} -} - -// ValidateBasic runs basic validation on this MsgSetSendEnabled. -func (msg MsgSetSendEnabled) ValidateBasic() error { - if len(msg.Authority) > 0 { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - } - - seen := map[string]bool{} - for _, se := range msg.SendEnabled { - if _, alreadySeen := seen[se.Denom]; alreadySeen { - return sdkerrors.ErrInvalidRequest.Wrapf("duplicate denom entries found for %q", se.Denom) - } - - seen[se.Denom] = true - - if err := se.Validate(); err != nil { - return sdkerrors.ErrInvalidRequest.Wrapf("invalid SendEnabled denom %q: %s", se.Denom, err) - } - } - - for _, denom := range msg.UseDefaultFor { - if err := sdk.ValidateDenom(denom); err != nil { - return sdkerrors.ErrInvalidRequest.Wrapf("invalid UseDefaultFor denom %q: %s", denom, err) - } - } - - return nil -} diff --git a/x/bank/types/msgs_test.go b/x/bank/types/msgs_test.go deleted file mode 100644 index f2fc35352..000000000 --- a/x/bank/types/msgs_test.go +++ /dev/null @@ -1,416 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" -) - -func TestMsgSendRoute(t *testing.T) { - addr1 := sdk.AccAddress([]byte("from")) - addr2 := sdk.AccAddress([]byte("to")) - coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - msg := NewMsgSend(addr1, addr2, coins) - - require.Equal(t, msg.Route(), RouterKey) - require.Equal(t, msg.Type(), "send") -} - -func TestMsgSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("from________________")) - addr2 := sdk.AccAddress([]byte("to__________________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrLong := sdk.AccAddress([]byte("Purposefully long address")) - - atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - atom0 := sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) - atom123eth123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 123)) - atom123eth0 := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 0)} - - cases := []struct { - expectedErr string // empty means no error expected - msg *MsgSend - }{ - {"", NewMsgSend(addr1, addr2, atom123)}, // valid send - {"", NewMsgSend(addr1, addr2, atom123eth123)}, // valid send with multiple coins - {"", NewMsgSend(addrLong, addr2, atom123)}, // valid send with long addr sender - {"", NewMsgSend(addr1, addrLong, atom123)}, // valid send with long addr recipient - {": invalid coins", NewMsgSend(addr1, addr2, atom0)}, // non positive coin - {"123atom,0eth: invalid coins", NewMsgSend(addr1, addr2, atom123eth0)}, // non positive coin in multicoins - {"invalid from address: empty address string is not allowed: invalid address", NewMsgSend(addrEmpty, addr2, atom123)}, - {"invalid to address: empty address string is not allowed: invalid address", NewMsgSend(addr1, addrEmpty, atom123)}, - } - - for _, tc := range cases { - err := tc.msg.ValidateBasic() - if tc.expectedErr == "" { - require.Nil(t, err) - } else { - require.EqualError(t, err, tc.expectedErr) - } - } -} - -func TestMsgSendGetSignBytes(t *testing.T) { - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) - coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - msg := NewMsgSend(addr1, addr2, coins) - res := msg.GetSignBytes() - - expected := `{"type":"cosmos-sdk/MsgSend","value":{"amount":[{"amount":"10","denom":"atom"}],"from_address":"cosmos1d9h8qat57ljhcm","to_address":"cosmos1da6hgur4wsmpnjyg"}}` - require.Equal(t, expected, string(res)) -} - -func TestMsgMultiSendRoute(t *testing.T) { - // Construct a MsgSend - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) - coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - msg := MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{NewOutput(addr2, coins)}, - } - - // TODO some failures for bad result - require.Equal(t, msg.Route(), RouterKey) - require.Equal(t, msg.Type(), "multisend") -} - -func TestInputValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrLong := sdk.AccAddress([]byte("Purposefully long address")) - - someCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - multiCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 20)) - - emptyCoins := sdk.NewCoins() - emptyCoins2 := sdk.NewCoins(sdk.NewInt64Coin("eth", 0)) - someEmptyCoins := sdk.Coins{sdk.NewInt64Coin("eth", 10), sdk.NewInt64Coin("atom", 0)} - unsortedCoins := sdk.Coins{sdk.NewInt64Coin("eth", 1), sdk.NewInt64Coin("atom", 1)} - - cases := []struct { - expectedErr string // empty means no error expected - txIn Input - }{ - // auth works with different apps - {"", NewInput(addr1, someCoins)}, - {"", NewInput(addr2, someCoins)}, - {"", NewInput(addr2, multiCoins)}, - {"", NewInput(addrLong, someCoins)}, - - {"invalid input address: empty address string is not allowed: invalid address", NewInput(addrEmpty, someCoins)}, - {": invalid coins", NewInput(addr1, emptyCoins)}, // invalid coins - {": invalid coins", NewInput(addr1, emptyCoins2)}, // invalid coins - {"10eth,0atom: invalid coins", NewInput(addr1, someEmptyCoins)}, // invalid coins - {"1eth,1atom: invalid coins", NewInput(addr1, unsortedCoins)}, // unsorted coins - } - - for i, tc := range cases { - err := tc.txIn.ValidateBasic() - if tc.expectedErr == "" { - require.Nil(t, err, "%d: %+v", i, err) - } else { - require.EqualError(t, err, tc.expectedErr, "%d", i) - } - } -} - -func TestOutputValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrLong := sdk.AccAddress([]byte("Purposefully long address")) - - someCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - multiCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 20)) - - emptyCoins := sdk.NewCoins() - emptyCoins2 := sdk.NewCoins(sdk.NewInt64Coin("eth", 0)) - someEmptyCoins := sdk.Coins{sdk.NewInt64Coin("eth", 10), sdk.NewInt64Coin("atom", 0)} - unsortedCoins := sdk.Coins{sdk.NewInt64Coin("eth", 1), sdk.NewInt64Coin("atom", 1)} - - cases := []struct { - expectedErr string // empty means no error expected - txOut Output - }{ - // auth works with different apps - {"", NewOutput(addr1, someCoins)}, - {"", NewOutput(addr2, someCoins)}, - {"", NewOutput(addr2, multiCoins)}, - {"", NewOutput(addrLong, someCoins)}, - - {"invalid output address: empty address string is not allowed: invalid address", NewOutput(addrEmpty, someCoins)}, - {": invalid coins", NewOutput(addr1, emptyCoins)}, // invalid coins - {": invalid coins", NewOutput(addr1, emptyCoins2)}, // invalid coins - {"10eth,0atom: invalid coins", NewOutput(addr1, someEmptyCoins)}, // invalid coins - {"1eth,1atom: invalid coins", NewOutput(addr1, unsortedCoins)}, // unsorted coins - } - - for i, tc := range cases { - err := tc.txOut.ValidateBasic() - if tc.expectedErr == "" { - require.Nil(t, err, "%d: %+v", i, err) - } else { - require.EqualError(t, err, tc.expectedErr, "%d", i) - } - } -} - -func TestMsgMultiSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addr3 := sdk.AccAddress([]byte("_______addr3________")) - atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) - atom124 := sdk.NewCoins(sdk.NewInt64Coin("atom", 124)) - atom246 := sdk.NewCoins(sdk.NewInt64Coin("atom", 246)) - - input1 := NewInput(addr1, atom123) - input2 := NewInput(addr1, atom246) - output1 := NewOutput(addr2, atom123) - output2 := NewOutput(addr2, atom124) - output3 := NewOutput(addr2, atom123) - output4 := NewOutput(addr3, atom123) - - var emptyAddr sdk.AccAddress - - cases := []struct { - valid bool - tx MsgMultiSend - expErrMsg string - }{ - {false, MsgMultiSend{}, "no inputs to send transaction"}, // no input or output - {false, MsgMultiSend{Inputs: []Input{input1}}, "no outputs to send transaction"}, // just input - {false, MsgMultiSend{Outputs: []Output{output1}}, "no inputs to send transaction"}, // just output - { - false, - MsgMultiSend{ - Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input - Outputs: []Output{output1}, - }, - "invalid input address", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{{emptyAddr.String(), atom123}}, // invalid output - }, - "invalid output address", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{output2}, // amounts don't match - }, - "sum inputs != sum outputs", - }, - { - true, - MsgMultiSend{ - Inputs: []Input{input1}, - Outputs: []Output{output1}, - }, - "", - }, - { - false, - MsgMultiSend{ - Inputs: []Input{input1, input2}, - Outputs: []Output{output3, output4}, - }, - "multiple senders not allowed", - }, - { - true, - MsgMultiSend{ - Inputs: []Input{NewInput(addr2, atom123.MulInt(sdk.NewInt(2)))}, - Outputs: []Output{output1, output1}, - }, - "", - }, - } - - for i, tc := range cases { - err := tc.tx.ValidateBasic() - if tc.valid { - require.Nil(t, err, "%d: %+v", i, err) - require.Nil(t, err) - } else { - require.NotNil(t, err, "%d", i) - require.Contains(t, err.Error(), tc.expErrMsg) - } - } -} - -func TestMsgMultiSendGetSignBytes(t *testing.T) { - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) - coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - msg := MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{NewOutput(addr2, coins)}, - } - res := msg.GetSignBytes() - - expected := `{"type":"cosmos-sdk/MsgMultiSend","value":{"inputs":[{"address":"cosmos1d9h8qat57ljhcm","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"cosmos1da6hgur4wsmpnjyg","coins":[{"amount":"10","denom":"atom"}]}]}}` - require.Equal(t, expected, string(res)) -} - -func TestMsgMultiSendGetSigners(t *testing.T) { - addrs := make([]string, 3) - inputs := make([]Input, 3) - for i, v := range []string{"input111111111111111", "input222222222222222", "input333333333333333"} { - addr := sdk.AccAddress([]byte(v)) - inputs[i] = NewInput(addr, nil) - addrs[i] = addr.String() - } - msg := NewMsgMultiSend(inputs, nil) - - res := msg.GetSigners() - for i, signer := range res { - require.Equal(t, signer.String(), addrs[i]) - } -} - -func TestNewMsgSetSendEnabled(t *testing.T) { - // Punt. Just setting one to all non-default values and making sure they're as expected. - msg := NewMsgSetSendEnabled("milton", []*SendEnabled{{"barrycoin", true}}, []string{"billcoin"}) - assert.Equal(t, "milton", msg.Authority, "msg.Authority") - if assert.Len(t, msg.SendEnabled, 1, "msg.SendEnabled length") { - assert.Equal(t, "barrycoin", msg.SendEnabled[0].Denom, "msg.SendEnabled[0].Denom") - assert.True(t, msg.SendEnabled[0].Enabled, "msg.SendEnabled[0].Enabled") - } - if assert.Len(t, msg.UseDefaultFor, 1, "msg.UseDefault") { - assert.Equal(t, "billcoin", msg.UseDefaultFor[0], "msg.UseDefault[0]") - } -} - -func TestMsgSendGetSigners(t *testing.T) { - from := sdk.AccAddress([]byte("input111111111111111")) - msg := NewMsgSend(from, sdk.AccAddress{}, sdk.NewCoins()) - res := msg.GetSigners() - require.Equal(t, 1, len(res)) - require.True(t, from.Equals(res[0])) -} - -func TestMsgSetSendEnabledGetSignBytes(t *testing.T) { - msg := NewMsgSetSendEnabled("cartman", []*SendEnabled{{"casafiestacoin", false}, {"kylecoin", true}}, nil) - expected := `{"type":"cosmos-sdk/MsgSetSendEnabled","value":{"authority":"cartman","send_enabled":[{"denom":"casafiestacoin"},{"denom":"kylecoin","enabled":true}]}}` - actualBz := msg.GetSignBytes() - actual := string(actualBz) - assert.Equal(t, expected, actual) -} - -func TestMsgSetSendEnabledGetSigners(t *testing.T) { - govModuleAddr := authtypes.NewModuleAddress(govtypes.ModuleName) - msg := NewMsgSetSendEnabled(govModuleAddr.String(), nil, nil) - expected := []sdk.AccAddress{govModuleAddr} - actual := msg.GetSigners() - assert.Equal(t, expected, actual) -} - -func TestMsgSetSendEnabledValidateBasic(t *testing.T) { - govModuleAddr := authtypes.NewModuleAddress(govtypes.ModuleName).String() - tests := []struct { - name string - msg MsgSetSendEnabled - exp string - }{ - { - name: "valid with two entries", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - UseDefaultFor: []string{"defcoinc", "defcoind"}, - }, - exp: "", - }, - { - name: "valid with two entries but no authority", - msg: MsgSetSendEnabled{ - Authority: "", - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - UseDefaultFor: []string{"defcoinc", "defcoind"}, - }, - exp: "", - }, - { - name: "bad authority", - msg: MsgSetSendEnabled{ - Authority: "farva", - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"somecoinb", false}, - }, - }, - exp: "invalid authority address: decoding bech32 failed: invalid bech32 string length 5: invalid address", - }, - { - name: "bad first denom name", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"Not A Denom", true}, - {"somecoinb", false}, - }, - }, - exp: `invalid SendEnabled denom "Not A Denom": invalid denom: Not A Denom: invalid request`, - }, - { - name: "bad second denom", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"somecoina", true}, - {"", false}, - }, - }, - exp: `invalid SendEnabled denom "": invalid denom: : invalid request`, - }, - { - name: "duplicate denom", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - SendEnabled: []*SendEnabled{ - {"copycoin", true}, - {"copycoin", false}, - }, - }, - exp: `duplicate denom entries found for "copycoin": invalid request`, - }, - { - name: "bad denom to delete", - msg: MsgSetSendEnabled{ - Authority: govModuleAddr, - UseDefaultFor: []string{"very \t bad denom string~~~!"}, - }, - exp: "invalid UseDefaultFor denom \"very \\t bad denom string~~~!\": invalid denom: very \t bad denom string~~~!: invalid request", - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(tt *testing.T) { - actual := tc.msg.ValidateBasic() - if len(tc.exp) > 0 { - require.EqualError(tt, actual, tc.exp) - } else { - require.NoError(tt, actual) - } - }) - } -} diff --git a/x/bank/types/params.go b/x/bank/types/params.go deleted file mode 100644 index d7d1a0504..000000000 --- a/x/bank/types/params.go +++ /dev/null @@ -1,75 +0,0 @@ -package types - -import ( - "errors" - "fmt" - - "sigs.k8s.io/yaml" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultDefaultSendEnabled is the value that DefaultSendEnabled will have from DefaultParams(). -var DefaultDefaultSendEnabled = true - -// NewParams creates a new parameter configuration for the bank module -func NewParams(defaultSendEnabled bool) Params { - return Params{ - SendEnabled: nil, - DefaultSendEnabled: defaultSendEnabled, - } -} - -// DefaultParams is the default parameter configuration for the bank module -func DefaultParams() Params { - return Params{ - SendEnabled: nil, - DefaultSendEnabled: DefaultDefaultSendEnabled, - } -} - -// Validate all bank module parameters -func (p Params) Validate() error { - if len(p.SendEnabled) > 0 { - return errors.New("use of send_enabled in params is no longer supported") - } - return validateIsBool(p.DefaultSendEnabled) -} - -// String implements the Stringer interface. -func (p Params) String() string { - sendEnabled, _ := yaml.Marshal(p.SendEnabled) - d := " " - if len(sendEnabled) > 0 && sendEnabled[0] == '-' { - d = "\n" - } - return fmt.Sprintf("default_send_enabled: %t\nsend_enabled:%s%s", p.DefaultSendEnabled, d, sendEnabled) -} - -// Validate gets any errors with this SendEnabled entry. -func (se SendEnabled) Validate() error { - return sdk.ValidateDenom(se.Denom) -} - -// NewSendEnabled creates a new SendEnabled object -// The denom may be left empty to control the global default setting of send_enabled -func NewSendEnabled(denom string, sendEnabled bool) *SendEnabled { - return &SendEnabled{ - Denom: denom, - Enabled: sendEnabled, - } -} - -// String implements stringer interface -func (se SendEnabled) String() string { - return fmt.Sprintf("denom: %s\nenabled: %t\n", se.Denom, se.Enabled) -} - -// validateIsBool is used by the x/params module to validate that a thing is a bool. -func validateIsBool(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return nil -} diff --git a/x/bank/types/params_legacy.go b/x/bank/types/params_legacy.go deleted file mode 100644 index 668358b4d..000000000 --- a/x/bank/types/params_legacy.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -var ( - // KeySendEnabled is store's key for SendEnabled Params - // Deprecated: Use the SendEnabled functionality in the keeper. - KeySendEnabled = []byte("SendEnabled") - // KeyDefaultSendEnabled is store's key for the DefaultSendEnabled option - KeyDefaultSendEnabled = []byte("DefaultSendEnabled") -) - -// Deprecated: ParamKeyTable for bank module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyDefaultSendEnabled, &p.DefaultSendEnabled, validateIsBool), - } -} diff --git a/x/bank/types/params_test.go b/x/bank/types/params_test.go deleted file mode 100644 index 697e9412a..000000000 --- a/x/bank/types/params_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func Test_sendParamEqual(t *testing.T) { - paramsA := NewSendEnabled(sdk.DefaultBondDenom, true) - paramsB := NewSendEnabled(sdk.DefaultBondDenom, true) - paramsC := NewSendEnabled("foodenom", false) - - ok := paramsA.Equal(paramsB) - require.True(t, ok) - - ok = paramsA.Equal(paramsC) - require.False(t, ok) -} - -func Test_SendEnabledString(t *testing.T) { - paramStringTrue := "denom: foo\nenabled: true\n" - paramTrue := NewSendEnabled("foo", true) - assert.Equal(t, paramStringTrue, paramTrue.String(), "true") - paramStringFalse := "denom: bar\nenabled: false\n" - paramFalse := NewSendEnabled("bar", false) - assert.Equal(t, paramStringFalse, paramFalse.String(), "false") -} - -func Test_ParamsString(t *testing.T) { - tests := []struct { - name string - params Params - expected string - }{ - { - name: "default true empty send enabled", - params: Params{[]*SendEnabled{}, true}, - expected: "default_send_enabled: true\nsend_enabled: []\n", - }, - { - name: "default false empty send enabled", - params: Params{[]*SendEnabled{}, false}, - expected: "default_send_enabled: false\nsend_enabled: []\n", - }, - { - name: "default true one true send enabled", - params: Params{[]*SendEnabled{{"foocoin", true}}, true}, - expected: "default_send_enabled: true\nsend_enabled:\n- denom: foocoin\n enabled: true\n", - }, - { - name: "default true one false send enabled", - params: Params{[]*SendEnabled{{"barcoin", false}}, true}, - expected: "default_send_enabled: true\nsend_enabled:\n- denom: barcoin\n", - }, - } - for _, tc := range tests { - t.Run(tc.name, func(tt *testing.T) { - actual := tc.params.String() - assert.Equal(tt, tc.expected, actual) - }) - } -} - -func Test_validateParams(t *testing.T) { - assert.NoError(t, DefaultParams().Validate(), "default") - assert.NoError(t, NewParams(true).Validate(), "true") - assert.NoError(t, NewParams(false).Validate(), "false") - assert.Error(t, Params{[]*SendEnabled{{"foocoing", false}}, true}.Validate(), "with SendEnabled entry") -} diff --git a/x/bank/types/querier.go b/x/bank/types/querier.go deleted file mode 100644 index a21605b71..000000000 --- a/x/bank/types/querier.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" -) - -// Querier path constants -const ( - QueryBalance = "balance" - QueryAllBalances = "all_balances" - QueryTotalSupply = "total_supply" - QuerySupplyOf = "supply_of" -) - -// NewQueryBalanceRequest creates a new instance of QueryBalanceRequest. -// -//nolint:interfacer -func NewQueryBalanceRequest(addr sdk.AccAddress, denom string) *QueryBalanceRequest { - return &QueryBalanceRequest{Address: addr.String(), Denom: denom} -} - -// NewQueryAllBalancesRequest creates a new instance of QueryAllBalancesRequest. -// -//nolint:interfacer -func NewQueryAllBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *QueryAllBalancesRequest { - return &QueryAllBalancesRequest{Address: addr.String(), Pagination: req} -} - -// NewQuerySpendableBalancesRequest creates a new instance of a -// QuerySpendableBalancesRequest. -// -//nolint:interfacer -func NewQuerySpendableBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *QuerySpendableBalancesRequest { - return &QuerySpendableBalancesRequest{Address: addr.String(), Pagination: req} -} - -// NewQuerySpendableBalanceByDenomRequest creates a new instance of a -// QuerySpendableBalanceByDenomRequest. -// -//nolint:interfacer -func NewQuerySpendableBalanceByDenomRequest(addr sdk.AccAddress, denom string) *QuerySpendableBalanceByDenomRequest { - return &QuerySpendableBalanceByDenomRequest{Address: addr.String(), Denom: denom} -} - -// QueryTotalSupplyParams defines the params for the following queries: -// -// - 'custom/bank/totalSupply' -type QueryTotalSupplyParams struct { - Page, Limit int -} - -// NewQueryTotalSupplyParams creates a new instance to query the total supply -func NewQueryTotalSupplyParams(page, limit int) QueryTotalSupplyParams { - return QueryTotalSupplyParams{page, limit} -} - -// QuerySupplyOfParams defines the params for the following queries: -// -// - 'custom/bank/totalSupplyOf' -type QuerySupplyOfParams struct { - Denom string -} - -// NewQuerySupplyOfParams creates a new instance to query the total supply -// of a given denomination -func NewQuerySupplyOfParams(denom string) QuerySupplyOfParams { - return QuerySupplyOfParams{denom} -} diff --git a/x/bank/types/query.pb.go b/x/bank/types/query.pb.go deleted file mode 100644 index 7f8c6931b..000000000 --- a/x/bank/types/query.pb.go +++ /dev/null @@ -1,5508 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/bank/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - 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 - -// QueryBalanceRequest is the request type for the Query/Balance RPC method. -type QueryBalanceRequest struct { - // address is the address to query balances for. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // denom is the coin denom to query balances for. - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryBalanceRequest) Reset() { *m = QueryBalanceRequest{} } -func (m *QueryBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceRequest) ProtoMessage() {} -func (*QueryBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{0} -} -func (m *QueryBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceRequest.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 *QueryBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceRequest.Merge(m, src) -} -func (m *QueryBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceRequest proto.InternalMessageInfo - -// QueryBalanceResponse is the response type for the Query/Balance RPC method. -type QueryBalanceResponse struct { - // balance is the balance of the coin. - Balance *types.Coin `protobuf:"bytes,1,opt,name=balance,proto3" json:"balance,omitempty"` -} - -func (m *QueryBalanceResponse) Reset() { *m = QueryBalanceResponse{} } -func (m *QueryBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceResponse) ProtoMessage() {} -func (*QueryBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{1} -} -func (m *QueryBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceResponse.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 *QueryBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceResponse.Merge(m, src) -} -func (m *QueryBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceResponse proto.InternalMessageInfo - -func (m *QueryBalanceResponse) GetBalance() *types.Coin { - if m != nil { - return m.Balance - } - return nil -} - -// QueryBalanceRequest is the request type for the Query/AllBalances RPC method. -type QueryAllBalancesRequest struct { - // address is the address to query balances for. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllBalancesRequest) Reset() { *m = QueryAllBalancesRequest{} } -func (m *QueryAllBalancesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllBalancesRequest) ProtoMessage() {} -func (*QueryAllBalancesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{2} -} -func (m *QueryAllBalancesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAllBalancesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllBalancesRequest.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 *QueryAllBalancesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllBalancesRequest.Merge(m, src) -} -func (m *QueryAllBalancesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAllBalancesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllBalancesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllBalancesRequest proto.InternalMessageInfo - -// QueryAllBalancesResponse is the response type for the Query/AllBalances RPC -// method. -type QueryAllBalancesResponse struct { - // balances is the balances of all the coins. - Balances github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=balances,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"balances"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllBalancesResponse) Reset() { *m = QueryAllBalancesResponse{} } -func (m *QueryAllBalancesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllBalancesResponse) ProtoMessage() {} -func (*QueryAllBalancesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{3} -} -func (m *QueryAllBalancesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAllBalancesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllBalancesResponse.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 *QueryAllBalancesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllBalancesResponse.Merge(m, src) -} -func (m *QueryAllBalancesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAllBalancesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllBalancesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllBalancesResponse proto.InternalMessageInfo - -func (m *QueryAllBalancesResponse) GetBalances() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Balances - } - return nil -} - -func (m *QueryAllBalancesResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QuerySpendableBalancesRequest defines the gRPC request structure for querying -// an account's spendable balances. -// -// Since: cosmos-sdk 0.46 -type QuerySpendableBalancesRequest struct { - // address is the address to query spendable balances for. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QuerySpendableBalancesRequest) Reset() { *m = QuerySpendableBalancesRequest{} } -func (m *QuerySpendableBalancesRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySpendableBalancesRequest) ProtoMessage() {} -func (*QuerySpendableBalancesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{4} -} -func (m *QuerySpendableBalancesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpendableBalancesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpendableBalancesRequest.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 *QuerySpendableBalancesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpendableBalancesRequest.Merge(m, src) -} -func (m *QuerySpendableBalancesRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySpendableBalancesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpendableBalancesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpendableBalancesRequest proto.InternalMessageInfo - -// QuerySpendableBalancesResponse defines the gRPC response structure for querying -// an account's spendable balances. -// -// Since: cosmos-sdk 0.46 -type QuerySpendableBalancesResponse struct { - // balances is the spendable balances of all the coins. - Balances github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=balances,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"balances"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QuerySpendableBalancesResponse) Reset() { *m = QuerySpendableBalancesResponse{} } -func (m *QuerySpendableBalancesResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySpendableBalancesResponse) ProtoMessage() {} -func (*QuerySpendableBalancesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{5} -} -func (m *QuerySpendableBalancesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpendableBalancesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpendableBalancesResponse.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 *QuerySpendableBalancesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpendableBalancesResponse.Merge(m, src) -} -func (m *QuerySpendableBalancesResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySpendableBalancesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpendableBalancesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpendableBalancesResponse proto.InternalMessageInfo - -func (m *QuerySpendableBalancesResponse) GetBalances() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Balances - } - return nil -} - -func (m *QuerySpendableBalancesResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QuerySpendableBalanceByDenomRequest defines the gRPC request structure for -// querying an account's spendable balance for a specific denom. -// -// Since: cosmos-sdk 0.47 -type QuerySpendableBalanceByDenomRequest struct { - // address is the address to query balances for. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // denom is the coin denom to query balances for. - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QuerySpendableBalanceByDenomRequest) Reset() { *m = QuerySpendableBalanceByDenomRequest{} } -func (m *QuerySpendableBalanceByDenomRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySpendableBalanceByDenomRequest) ProtoMessage() {} -func (*QuerySpendableBalanceByDenomRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{6} -} -func (m *QuerySpendableBalanceByDenomRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpendableBalanceByDenomRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpendableBalanceByDenomRequest.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 *QuerySpendableBalanceByDenomRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpendableBalanceByDenomRequest.Merge(m, src) -} -func (m *QuerySpendableBalanceByDenomRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySpendableBalanceByDenomRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpendableBalanceByDenomRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpendableBalanceByDenomRequest proto.InternalMessageInfo - -// QuerySpendableBalanceByDenomResponse defines the gRPC response structure for -// querying an account's spendable balance for a specific denom. -// -// Since: cosmos-sdk 0.47 -type QuerySpendableBalanceByDenomResponse struct { - // balance is the balance of the coin. - Balance *types.Coin `protobuf:"bytes,1,opt,name=balance,proto3" json:"balance,omitempty"` -} - -func (m *QuerySpendableBalanceByDenomResponse) Reset() { *m = QuerySpendableBalanceByDenomResponse{} } -func (m *QuerySpendableBalanceByDenomResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySpendableBalanceByDenomResponse) ProtoMessage() {} -func (*QuerySpendableBalanceByDenomResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{7} -} -func (m *QuerySpendableBalanceByDenomResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpendableBalanceByDenomResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpendableBalanceByDenomResponse.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 *QuerySpendableBalanceByDenomResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpendableBalanceByDenomResponse.Merge(m, src) -} -func (m *QuerySpendableBalanceByDenomResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySpendableBalanceByDenomResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpendableBalanceByDenomResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpendableBalanceByDenomResponse proto.InternalMessageInfo - -func (m *QuerySpendableBalanceByDenomResponse) GetBalance() *types.Coin { - if m != nil { - return m.Balance - } - return nil -} - -// QueryTotalSupplyRequest is the request type for the Query/TotalSupply RPC -// method. -type QueryTotalSupplyRequest struct { - // pagination defines an optional pagination for the request. - // - // Since: cosmos-sdk 0.43 - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{8} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.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 *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// QueryTotalSupplyResponse is the response type for the Query/TotalSupply RPC -// method -type QueryTotalSupplyResponse struct { - // supply is the supply of the coins - Supply github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=supply,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"supply"` - // pagination defines the pagination in the response. - // - // Since: cosmos-sdk 0.43 - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{9} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.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 *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func (m *QueryTotalSupplyResponse) GetSupply() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Supply - } - return nil -} - -func (m *QueryTotalSupplyResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QuerySupplyOfRequest is the request type for the Query/SupplyOf RPC method. -type QuerySupplyOfRequest struct { - // denom is the coin denom to query balances for. - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QuerySupplyOfRequest) Reset() { *m = QuerySupplyOfRequest{} } -func (m *QuerySupplyOfRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySupplyOfRequest) ProtoMessage() {} -func (*QuerySupplyOfRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{10} -} -func (m *QuerySupplyOfRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySupplyOfRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySupplyOfRequest.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 *QuerySupplyOfRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySupplyOfRequest.Merge(m, src) -} -func (m *QuerySupplyOfRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySupplyOfRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySupplyOfRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySupplyOfRequest proto.InternalMessageInfo - -func (m *QuerySupplyOfRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QuerySupplyOfResponse is the response type for the Query/SupplyOf RPC method. -type QuerySupplyOfResponse struct { - // amount is the supply of the coin. - Amount types.Coin `protobuf:"bytes,1,opt,name=amount,proto3" json:"amount"` -} - -func (m *QuerySupplyOfResponse) Reset() { *m = QuerySupplyOfResponse{} } -func (m *QuerySupplyOfResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySupplyOfResponse) ProtoMessage() {} -func (*QuerySupplyOfResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{11} -} -func (m *QuerySupplyOfResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySupplyOfResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySupplyOfResponse.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 *QuerySupplyOfResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySupplyOfResponse.Merge(m, src) -} -func (m *QuerySupplyOfResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySupplyOfResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySupplyOfResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySupplyOfResponse proto.InternalMessageInfo - -func (m *QuerySupplyOfResponse) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - -// QueryParamsRequest defines the request type for querying x/bank parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{12} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.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 *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/bank parameters. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{13} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.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 *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryDenomsMetadataRequest is the request type for the Query/DenomsMetadata RPC method. -type QueryDenomsMetadataRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDenomsMetadataRequest) Reset() { *m = QueryDenomsMetadataRequest{} } -func (m *QueryDenomsMetadataRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDenomsMetadataRequest) ProtoMessage() {} -func (*QueryDenomsMetadataRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{14} -} -func (m *QueryDenomsMetadataRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomsMetadataRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomsMetadataRequest.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 *QueryDenomsMetadataRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomsMetadataRequest.Merge(m, src) -} -func (m *QueryDenomsMetadataRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomsMetadataRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomsMetadataRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomsMetadataRequest proto.InternalMessageInfo - -func (m *QueryDenomsMetadataRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDenomsMetadataResponse is the response type for the Query/DenomsMetadata RPC -// method. -type QueryDenomsMetadataResponse struct { - // metadata provides the client information for all the registered tokens. - Metadatas []Metadata `protobuf:"bytes,1,rep,name=metadatas,proto3" json:"metadatas"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDenomsMetadataResponse) Reset() { *m = QueryDenomsMetadataResponse{} } -func (m *QueryDenomsMetadataResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDenomsMetadataResponse) ProtoMessage() {} -func (*QueryDenomsMetadataResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{15} -} -func (m *QueryDenomsMetadataResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomsMetadataResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomsMetadataResponse.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 *QueryDenomsMetadataResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomsMetadataResponse.Merge(m, src) -} -func (m *QueryDenomsMetadataResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomsMetadataResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomsMetadataResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomsMetadataResponse proto.InternalMessageInfo - -func (m *QueryDenomsMetadataResponse) GetMetadatas() []Metadata { - if m != nil { - return m.Metadatas - } - return nil -} - -func (m *QueryDenomsMetadataResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDenomMetadataRequest is the request type for the Query/DenomMetadata RPC method. -type QueryDenomMetadataRequest struct { - // denom is the coin denom to query the metadata for. - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryDenomMetadataRequest) Reset() { *m = QueryDenomMetadataRequest{} } -func (m *QueryDenomMetadataRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDenomMetadataRequest) ProtoMessage() {} -func (*QueryDenomMetadataRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{16} -} -func (m *QueryDenomMetadataRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomMetadataRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomMetadataRequest.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 *QueryDenomMetadataRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomMetadataRequest.Merge(m, src) -} -func (m *QueryDenomMetadataRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomMetadataRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomMetadataRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomMetadataRequest proto.InternalMessageInfo - -func (m *QueryDenomMetadataRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryDenomMetadataResponse is the response type for the Query/DenomMetadata RPC -// method. -type QueryDenomMetadataResponse struct { - // metadata describes and provides all the client information for the requested token. - Metadata Metadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata"` -} - -func (m *QueryDenomMetadataResponse) Reset() { *m = QueryDenomMetadataResponse{} } -func (m *QueryDenomMetadataResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDenomMetadataResponse) ProtoMessage() {} -func (*QueryDenomMetadataResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{17} -} -func (m *QueryDenomMetadataResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomMetadataResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomMetadataResponse.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 *QueryDenomMetadataResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomMetadataResponse.Merge(m, src) -} -func (m *QueryDenomMetadataResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomMetadataResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomMetadataResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomMetadataResponse proto.InternalMessageInfo - -func (m *QueryDenomMetadataResponse) GetMetadata() Metadata { - if m != nil { - return m.Metadata - } - return Metadata{} -} - -// QueryDenomOwnersRequest defines the request type for the DenomOwners RPC query, -// which queries for a paginated set of all account holders of a particular -// denomination. -type QueryDenomOwnersRequest struct { - // denom defines the coin denomination to query all account holders for. - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDenomOwnersRequest) Reset() { *m = QueryDenomOwnersRequest{} } -func (m *QueryDenomOwnersRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDenomOwnersRequest) ProtoMessage() {} -func (*QueryDenomOwnersRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{18} -} -func (m *QueryDenomOwnersRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomOwnersRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomOwnersRequest.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 *QueryDenomOwnersRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomOwnersRequest.Merge(m, src) -} -func (m *QueryDenomOwnersRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomOwnersRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomOwnersRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomOwnersRequest proto.InternalMessageInfo - -func (m *QueryDenomOwnersRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryDenomOwnersRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// DenomOwner defines structure representing an account that owns or holds a -// particular denominated token. It contains the account address and account -// balance of the denominated token. -// -// Since: cosmos-sdk 0.46 -type DenomOwner struct { - // address defines the address that owns a particular denomination. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // balance is the balance of the denominated coin for an account. - Balance types.Coin `protobuf:"bytes,2,opt,name=balance,proto3" json:"balance"` -} - -func (m *DenomOwner) Reset() { *m = DenomOwner{} } -func (m *DenomOwner) String() string { return proto.CompactTextString(m) } -func (*DenomOwner) ProtoMessage() {} -func (*DenomOwner) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{19} -} -func (m *DenomOwner) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DenomOwner) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DenomOwner.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 *DenomOwner) XXX_Merge(src proto.Message) { - xxx_messageInfo_DenomOwner.Merge(m, src) -} -func (m *DenomOwner) XXX_Size() int { - return m.Size() -} -func (m *DenomOwner) XXX_DiscardUnknown() { - xxx_messageInfo_DenomOwner.DiscardUnknown(m) -} - -var xxx_messageInfo_DenomOwner proto.InternalMessageInfo - -func (m *DenomOwner) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *DenomOwner) GetBalance() types.Coin { - if m != nil { - return m.Balance - } - return types.Coin{} -} - -// QueryDenomOwnersResponse defines the RPC response of a DenomOwners RPC query. -// -// Since: cosmos-sdk 0.46 -type QueryDenomOwnersResponse struct { - DenomOwners []*DenomOwner `protobuf:"bytes,1,rep,name=denom_owners,json=denomOwners,proto3" json:"denom_owners,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDenomOwnersResponse) Reset() { *m = QueryDenomOwnersResponse{} } -func (m *QueryDenomOwnersResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDenomOwnersResponse) ProtoMessage() {} -func (*QueryDenomOwnersResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{20} -} -func (m *QueryDenomOwnersResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDenomOwnersResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDenomOwnersResponse.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 *QueryDenomOwnersResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDenomOwnersResponse.Merge(m, src) -} -func (m *QueryDenomOwnersResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDenomOwnersResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDenomOwnersResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDenomOwnersResponse proto.InternalMessageInfo - -func (m *QueryDenomOwnersResponse) GetDenomOwners() []*DenomOwner { - if m != nil { - return m.DenomOwners - } - return nil -} - -func (m *QueryDenomOwnersResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QuerySendEnabledRequest defines the RPC request for looking up SendEnabled entries. -// -// Since: cosmos-sdk 0.47 -type QuerySendEnabledRequest struct { - // denoms is the specific denoms you want look up. Leave empty to get all entries. - Denoms []string `protobuf:"bytes,1,rep,name=denoms,proto3" json:"denoms,omitempty"` - // pagination defines an optional pagination for the request. This field is - // only read if the denoms field is empty. - Pagination *query.PageRequest `protobuf:"bytes,99,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QuerySendEnabledRequest) Reset() { *m = QuerySendEnabledRequest{} } -func (m *QuerySendEnabledRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySendEnabledRequest) ProtoMessage() {} -func (*QuerySendEnabledRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{21} -} -func (m *QuerySendEnabledRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySendEnabledRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySendEnabledRequest.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 *QuerySendEnabledRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySendEnabledRequest.Merge(m, src) -} -func (m *QuerySendEnabledRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySendEnabledRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySendEnabledRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySendEnabledRequest proto.InternalMessageInfo - -func (m *QuerySendEnabledRequest) GetDenoms() []string { - if m != nil { - return m.Denoms - } - return nil -} - -func (m *QuerySendEnabledRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QuerySendEnabledResponse defines the RPC response of a SendEnable query. -// -// Since: cosmos-sdk 0.47 -type QuerySendEnabledResponse struct { - SendEnabled []*SendEnabled `protobuf:"bytes,1,rep,name=send_enabled,json=sendEnabled,proto3" json:"send_enabled,omitempty"` - // pagination defines the pagination in the response. This field is only - // populated if the denoms field in the request is empty. - Pagination *query.PageResponse `protobuf:"bytes,99,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QuerySendEnabledResponse) Reset() { *m = QuerySendEnabledResponse{} } -func (m *QuerySendEnabledResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySendEnabledResponse) ProtoMessage() {} -func (*QuerySendEnabledResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c6fc1939682df13, []int{22} -} -func (m *QuerySendEnabledResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySendEnabledResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySendEnabledResponse.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 *QuerySendEnabledResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySendEnabledResponse.Merge(m, src) -} -func (m *QuerySendEnabledResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySendEnabledResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySendEnabledResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySendEnabledResponse proto.InternalMessageInfo - -func (m *QuerySendEnabledResponse) GetSendEnabled() []*SendEnabled { - if m != nil { - return m.SendEnabled - } - return nil -} - -func (m *QuerySendEnabledResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -func init() { - proto.RegisterType((*QueryBalanceRequest)(nil), "cosmos.bank.v1beta1.QueryBalanceRequest") - proto.RegisterType((*QueryBalanceResponse)(nil), "cosmos.bank.v1beta1.QueryBalanceResponse") - proto.RegisterType((*QueryAllBalancesRequest)(nil), "cosmos.bank.v1beta1.QueryAllBalancesRequest") - proto.RegisterType((*QueryAllBalancesResponse)(nil), "cosmos.bank.v1beta1.QueryAllBalancesResponse") - proto.RegisterType((*QuerySpendableBalancesRequest)(nil), "cosmos.bank.v1beta1.QuerySpendableBalancesRequest") - proto.RegisterType((*QuerySpendableBalancesResponse)(nil), "cosmos.bank.v1beta1.QuerySpendableBalancesResponse") - proto.RegisterType((*QuerySpendableBalanceByDenomRequest)(nil), "cosmos.bank.v1beta1.QuerySpendableBalanceByDenomRequest") - proto.RegisterType((*QuerySpendableBalanceByDenomResponse)(nil), "cosmos.bank.v1beta1.QuerySpendableBalanceByDenomResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "cosmos.bank.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "cosmos.bank.v1beta1.QueryTotalSupplyResponse") - proto.RegisterType((*QuerySupplyOfRequest)(nil), "cosmos.bank.v1beta1.QuerySupplyOfRequest") - proto.RegisterType((*QuerySupplyOfResponse)(nil), "cosmos.bank.v1beta1.QuerySupplyOfResponse") - proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.bank.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.bank.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryDenomsMetadataRequest)(nil), "cosmos.bank.v1beta1.QueryDenomsMetadataRequest") - proto.RegisterType((*QueryDenomsMetadataResponse)(nil), "cosmos.bank.v1beta1.QueryDenomsMetadataResponse") - proto.RegisterType((*QueryDenomMetadataRequest)(nil), "cosmos.bank.v1beta1.QueryDenomMetadataRequest") - proto.RegisterType((*QueryDenomMetadataResponse)(nil), "cosmos.bank.v1beta1.QueryDenomMetadataResponse") - proto.RegisterType((*QueryDenomOwnersRequest)(nil), "cosmos.bank.v1beta1.QueryDenomOwnersRequest") - proto.RegisterType((*DenomOwner)(nil), "cosmos.bank.v1beta1.DenomOwner") - proto.RegisterType((*QueryDenomOwnersResponse)(nil), "cosmos.bank.v1beta1.QueryDenomOwnersResponse") - proto.RegisterType((*QuerySendEnabledRequest)(nil), "cosmos.bank.v1beta1.QuerySendEnabledRequest") - proto.RegisterType((*QuerySendEnabledResponse)(nil), "cosmos.bank.v1beta1.QuerySendEnabledResponse") -} - -func init() { proto.RegisterFile("cosmos/bank/v1beta1/query.proto", fileDescriptor_9c6fc1939682df13) } - -var fileDescriptor_9c6fc1939682df13 = []byte{ - // 1188 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x58, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xf6, 0x04, 0xd5, 0x49, 0x9e, 0x4b, 0xa5, 0x4e, 0x03, 0x4d, 0x36, 0xc4, 0x2e, 0xdb, 0xaa, - 0xf9, 0x41, 0xb2, 0xdb, 0x38, 0x80, 0x68, 0x55, 0x22, 0xd5, 0x29, 0xed, 0x01, 0xa1, 0x16, 0x87, - 0x5e, 0xe0, 0x60, 0xad, 0xbd, 0x83, 0x6b, 0xc5, 0xde, 0x71, 0x3d, 0x6b, 0x8a, 0x55, 0x55, 0x42, - 0x48, 0x48, 0x3d, 0x22, 0xd1, 0x13, 0x12, 0x22, 0x42, 0x02, 0x2a, 0x90, 0x10, 0x42, 0x1c, 0xf9, - 0x03, 0x7a, 0x41, 0x2a, 0x70, 0x28, 0x27, 0x40, 0x09, 0x12, 0xfc, 0x19, 0xc8, 0xf3, 0xc3, 0xbb, - 0x6b, 0x8f, 0x37, 0x9b, 0xd4, 0x95, 0xe8, 0xa5, 0xb5, 0x67, 0xde, 0x9b, 0xf7, 0x7d, 0xef, 0xbd, - 0x99, 0xf7, 0x39, 0x90, 0xab, 0x50, 0xd6, 0xa0, 0xcc, 0x2e, 0x3b, 0xde, 0x96, 0xfd, 0xde, 0x6a, - 0x99, 0xf8, 0xce, 0xaa, 0x7d, 0xa3, 0x4d, 0x5a, 0x1d, 0xab, 0xd9, 0xa2, 0x3e, 0xc5, 0xc7, 0x84, - 0x81, 0xd5, 0x35, 0xb0, 0xa4, 0x81, 0xb1, 0xd4, 0xf3, 0x62, 0x44, 0x58, 0xf7, 0x7c, 0x9b, 0x4e, - 0xb5, 0xe6, 0x39, 0x7e, 0x8d, 0x7a, 0xe2, 0x00, 0x63, 0xaa, 0x4a, 0xab, 0x94, 0x7f, 0xb4, 0xbb, - 0x9f, 0xe4, 0xea, 0x73, 0x55, 0x4a, 0xab, 0x75, 0x62, 0x3b, 0xcd, 0x9a, 0xed, 0x78, 0x1e, 0xf5, - 0xb9, 0x0b, 0x93, 0xbb, 0xd9, 0xf0, 0xf9, 0xea, 0xe4, 0x0a, 0xad, 0x79, 0x03, 0xfb, 0x21, 0xd4, - 0x1c, 0xa1, 0xd8, 0x9f, 0x11, 0xfb, 0x25, 0x11, 0x56, 0x32, 0x10, 0x5b, 0xb3, 0xd2, 0x55, 0xa1, - 0x0e, 0x93, 0x35, 0x8e, 0x3a, 0x8d, 0x9a, 0x47, 0x6d, 0xfe, 0xaf, 0x58, 0x32, 0x6b, 0x70, 0xec, - 0xcd, 0xae, 0x45, 0xc1, 0xa9, 0x3b, 0x5e, 0x85, 0x14, 0xc9, 0x8d, 0x36, 0x61, 0x3e, 0xce, 0xc3, - 0xb8, 0xe3, 0xba, 0x2d, 0xc2, 0xd8, 0x34, 0x3a, 0x81, 0x16, 0x26, 0x0b, 0xd3, 0xbf, 0xfe, 0xb8, - 0x32, 0x25, 0x23, 0x5d, 0x10, 0x3b, 0x9b, 0x7e, 0xab, 0xe6, 0x55, 0x8b, 0xca, 0x10, 0x4f, 0xc1, - 0x21, 0x97, 0x78, 0xb4, 0x31, 0x3d, 0xd6, 0xf5, 0x28, 0x8a, 0x2f, 0xe7, 0x26, 0xee, 0x6c, 0xe7, - 0x52, 0xff, 0x6e, 0xe7, 0x52, 0xe6, 0xeb, 0x30, 0x15, 0x0d, 0xc5, 0x9a, 0xd4, 0x63, 0x04, 0xaf, - 0xc1, 0x78, 0x59, 0x2c, 0xf1, 0x58, 0x99, 0xfc, 0x8c, 0xd5, 0x2b, 0x0a, 0x23, 0xaa, 0x28, 0xd6, - 0x06, 0xad, 0x79, 0x45, 0x65, 0x69, 0x7e, 0x8e, 0xe0, 0x38, 0x3f, 0xed, 0x42, 0xbd, 0x2e, 0x0f, - 0x64, 0x8f, 0x02, 0xfe, 0x12, 0x40, 0x50, 0x5a, 0xce, 0x20, 0x93, 0x3f, 0x1d, 0xc1, 0x21, 0x12, - 0xa9, 0xd0, 0x5c, 0x75, 0xaa, 0x2a, 0x59, 0xc5, 0x90, 0x67, 0x88, 0xee, 0x2f, 0x08, 0xa6, 0x07, - 0x11, 0x4a, 0xce, 0x75, 0x98, 0x90, 0x4c, 0xba, 0x18, 0x9f, 0x8a, 0x25, 0x5d, 0x78, 0xe9, 0xfe, - 0x1f, 0xb9, 0xd4, 0x37, 0x7f, 0xe6, 0x16, 0xaa, 0x35, 0xff, 0x7a, 0xbb, 0x6c, 0x55, 0x68, 0x43, - 0x16, 0x5d, 0xfe, 0xb7, 0xc2, 0xdc, 0x2d, 0xdb, 0xef, 0x34, 0x09, 0xe3, 0x0e, 0xec, 0xde, 0x3f, - 0xdf, 0x2f, 0xa1, 0x62, 0x2f, 0x02, 0xbe, 0xac, 0x21, 0x37, 0xbf, 0x27, 0x39, 0x01, 0x35, 0xcc, - 0xce, 0xfc, 0x12, 0xc1, 0x1c, 0xe7, 0xb4, 0xd9, 0x24, 0x9e, 0xeb, 0x94, 0xeb, 0xe4, 0xff, 0x99, - 0xfb, 0x87, 0x08, 0xb2, 0xc3, 0x70, 0x3e, 0xd9, 0x15, 0xe8, 0xc0, 0x49, 0x2d, 0xb1, 0x42, 0xe7, - 0x62, 0xf7, 0xba, 0x3d, 0xce, 0xfb, 0xfb, 0x0e, 0x9c, 0x8a, 0x0f, 0xfd, 0x28, 0xf7, 0x79, 0x4b, - 0x5e, 0xe7, 0xb7, 0xa8, 0xef, 0xd4, 0x37, 0xdb, 0xcd, 0x66, 0xbd, 0xa3, 0xb8, 0x44, 0xdb, 0x03, - 0x8d, 0xa0, 0x3d, 0x7e, 0x56, 0x57, 0x33, 0x12, 0x4d, 0xc2, 0xbf, 0x0e, 0x69, 0xc6, 0x57, 0x1e, - 0x5b, 0x5b, 0xc8, 0xf3, 0x47, 0xd7, 0x14, 0xcb, 0xf2, 0x65, 0x15, 0x4c, 0xae, 0xbc, 0xab, 0x32, - 0xd7, 0xab, 0x28, 0x0a, 0x55, 0xd4, 0xbc, 0x06, 0xcf, 0xf4, 0x59, 0x4b, 0xe6, 0xe7, 0x21, 0xed, - 0x34, 0x68, 0xdb, 0xf3, 0xf7, 0xac, 0x5b, 0x61, 0xb2, 0xcb, 0x5c, 0xb2, 0x11, 0x3e, 0xe6, 0x14, - 0x60, 0x7e, 0xec, 0x55, 0xa7, 0xe5, 0x34, 0xd4, 0x7b, 0x60, 0x5e, 0x93, 0xf3, 0x45, 0xad, 0xca, - 0x50, 0xeb, 0x90, 0x6e, 0xf2, 0x15, 0x19, 0x6a, 0xd6, 0xd2, 0xcc, 0x61, 0x4b, 0x38, 0x45, 0x82, - 0x09, 0x2f, 0xd3, 0x05, 0x83, 0x1f, 0xcb, 0x3b, 0x8f, 0xbd, 0x41, 0x7c, 0xc7, 0x75, 0x7c, 0x67, - 0xc4, 0x1d, 0x63, 0x7e, 0x87, 0x60, 0x56, 0x1b, 0x46, 0xb2, 0xb8, 0x04, 0x93, 0x0d, 0xb9, 0xa6, - 0x1e, 0x91, 0x39, 0x2d, 0x11, 0xe5, 0x19, 0xa6, 0x12, 0xb8, 0x8e, 0xae, 0x11, 0x56, 0x61, 0x26, - 0xc0, 0xdb, 0x9f, 0x15, 0x7d, 0x37, 0x94, 0xc3, 0x99, 0x1c, 0x60, 0x78, 0x11, 0x26, 0x14, 0x4c, - 0x99, 0xc7, 0xe4, 0x04, 0x7b, 0x9e, 0xe6, 0x4d, 0x79, 0xb9, 0x79, 0x8c, 0x2b, 0x37, 0x3d, 0xd2, - 0x62, 0xb1, 0xa0, 0x46, 0x35, 0x11, 0xcc, 0x0f, 0x10, 0x40, 0x10, 0xf4, 0x40, 0xaf, 0xe2, 0x7a, - 0xf0, 0x9a, 0x8d, 0xed, 0xe3, 0x56, 0xf4, 0x1e, 0xb6, 0xaf, 0xd5, 0x5b, 0x13, 0x21, 0x2f, 0xd3, - 0x5b, 0x80, 0xc3, 0x9c, 0x70, 0x89, 0xf2, 0x75, 0xd9, 0x43, 0x39, 0x6d, 0x8a, 0x03, 0xff, 0x62, - 0xc6, 0x0d, 0xce, 0x1a, 0xe5, 0x68, 0x11, 0x55, 0xda, 0x24, 0x9e, 0xfb, 0x9a, 0xd7, 0x7d, 0xe0, - 0x5d, 0x55, 0xa5, 0x67, 0x21, 0xcd, 0x43, 0x0a, 0x84, 0x93, 0x45, 0xf9, 0xad, 0xaf, 0x4e, 0x95, - 0x03, 0xd7, 0xe9, 0x9e, 0x4a, 0x52, 0x24, 0xb6, 0x4c, 0xd2, 0x06, 0x1c, 0x66, 0xc4, 0x73, 0x4b, - 0x44, 0xac, 0xcb, 0x24, 0x9d, 0xd0, 0x26, 0x29, 0xec, 0x9f, 0x61, 0xc1, 0x97, 0xbe, 0x2c, 0x55, - 0x0e, 0x9c, 0xa5, 0xfc, 0x0f, 0x47, 0xe0, 0x10, 0x87, 0x8a, 0x3f, 0x43, 0x30, 0x2e, 0x47, 0x20, - 0x5e, 0xd0, 0xa2, 0xd1, 0x28, 0x6b, 0x63, 0x31, 0x81, 0xa5, 0x08, 0x6b, 0xbe, 0x7a, 0xa7, 0xdb, - 0x4a, 0x1f, 0xfe, 0xf6, 0xf7, 0x27, 0x63, 0x79, 0x7c, 0xc6, 0xd6, 0xff, 0x28, 0x10, 0x02, 0xc3, - 0xbe, 0x25, 0xfb, 0xf5, 0xb6, 0x5d, 0xee, 0x94, 0xc4, 0x25, 0xda, 0x46, 0x90, 0x09, 0x69, 0x4f, - 0xbc, 0x3c, 0x3c, 0xf2, 0xa0, 0x88, 0x36, 0x56, 0x12, 0x5a, 0x4b, 0xac, 0x2f, 0x06, 0x58, 0x17, - 0xf1, 0x7c, 0x42, 0xac, 0xf8, 0x27, 0x04, 0x47, 0x07, 0x24, 0x1a, 0xce, 0x0f, 0x0f, 0x3d, 0x4c, - 0x77, 0x1a, 0x6b, 0xfb, 0xf2, 0x91, 0xa0, 0xd7, 0x03, 0xd0, 0x6b, 0x78, 0x55, 0x0b, 0x9a, 0x29, - 0xe7, 0x92, 0x06, 0xfe, 0x43, 0x04, 0xc7, 0x87, 0xa8, 0x21, 0xfc, 0x4a, 0x72, 0x40, 0x51, 0xed, - 0x66, 0x9c, 0x3d, 0x80, 0xa7, 0x24, 0x74, 0x39, 0x20, 0x74, 0x1e, 0x9f, 0xdb, 0x37, 0xa1, 0xa0, - 0x77, 0xee, 0x22, 0xc8, 0x84, 0xc4, 0x51, 0x5c, 0xef, 0x0c, 0x2a, 0xb6, 0xb8, 0xde, 0xd1, 0x28, - 0x2e, 0x73, 0x21, 0x40, 0x3d, 0x87, 0x67, 0xf5, 0xa8, 0x05, 0x8c, 0xbb, 0x08, 0x26, 0x94, 0x6c, - 0xc1, 0x31, 0x37, 0xa9, 0x4f, 0x08, 0x19, 0x4b, 0x49, 0x4c, 0x25, 0x9a, 0xd5, 0x00, 0xcd, 0x69, - 0x7c, 0x2a, 0x06, 0x4d, 0x90, 0xad, 0x8f, 0x10, 0xa4, 0x85, 0x56, 0xc1, 0xf3, 0xc3, 0x23, 0x45, - 0x84, 0x91, 0xb1, 0xb0, 0xb7, 0x61, 0xf2, 0xf4, 0x08, 0x55, 0x84, 0xbf, 0x45, 0xf0, 0x74, 0x64, - 0x8e, 0x63, 0x6b, 0x78, 0x14, 0x9d, 0x46, 0x30, 0xec, 0xc4, 0xf6, 0x12, 0xdc, 0xd9, 0x00, 0x9c, - 0x85, 0x97, 0xb5, 0xe0, 0xc4, 0xac, 0x28, 0x29, 0x35, 0x60, 0xdf, 0xe2, 0x0b, 0xb7, 0xf1, 0x57, - 0x08, 0x8e, 0x44, 0x85, 0x15, 0xde, 0x2b, 0x7c, 0xbf, 0xd2, 0x33, 0xce, 0x24, 0x77, 0x48, 0x5e, - 0xde, 0x3e, 0xc0, 0xf8, 0x0b, 0x04, 0x99, 0xd0, 0xf4, 0x8e, 0xbb, 0x0c, 0x83, 0x0a, 0x27, 0xee, - 0x32, 0x68, 0x24, 0x81, 0xf9, 0x72, 0x80, 0xef, 0x05, 0xbc, 0x38, 0x1c, 0x9f, 0x94, 0x0c, 0xbd, - 0x6c, 0x7e, 0x8a, 0x20, 0x13, 0x9a, 0x7e, 0x71, 0x20, 0x07, 0x07, 0x7c, 0x1c, 0x48, 0xcd, 0x48, - 0x36, 0xad, 0x00, 0xe4, 0x49, 0xfc, 0xbc, 0xfe, 0x8e, 0x84, 0x46, 0x76, 0x61, 0xe3, 0xfe, 0x4e, - 0x16, 0x3d, 0xd8, 0xc9, 0xa2, 0xbf, 0x76, 0xb2, 0xe8, 0xe3, 0xdd, 0x6c, 0xea, 0xc1, 0x6e, 0x36, - 0xf5, 0xfb, 0x6e, 0x36, 0xf5, 0xf6, 0x62, 0xec, 0x4f, 0xa7, 0xf7, 0xc5, 0x99, 0xfc, 0x17, 0x54, - 0x39, 0xcd, 0xff, 0x62, 0xb5, 0xf6, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf4, 0x2c, 0x27, 0x2a, - 0xd4, 0x13, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Balance queries the balance of a single coin for a single account. - Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) - // AllBalances queries the balance of all coins for a single account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - AllBalances(ctx context.Context, in *QueryAllBalancesRequest, opts ...grpc.CallOption) (*QueryAllBalancesResponse, error) - // SpendableBalances queries the spendable balance of all coins for a single - // account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.46 - SpendableBalances(ctx context.Context, in *QuerySpendableBalancesRequest, opts ...grpc.CallOption) (*QuerySpendableBalancesResponse, error) - // SpendableBalanceByDenom queries the spendable balance of a single denom for - // a single account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.47 - SpendableBalanceByDenom(ctx context.Context, in *QuerySpendableBalanceByDenomRequest, opts ...grpc.CallOption) (*QuerySpendableBalanceByDenomResponse, error) - // TotalSupply queries the total supply of all coins. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) - // SupplyOf queries the supply of a single coin. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - SupplyOf(ctx context.Context, in *QuerySupplyOfRequest, opts ...grpc.CallOption) (*QuerySupplyOfResponse, error) - // Params queries the parameters of x/bank module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // DenomsMetadata queries the client metadata of a given coin denomination. - DenomMetadata(ctx context.Context, in *QueryDenomMetadataRequest, opts ...grpc.CallOption) (*QueryDenomMetadataResponse, error) - // DenomsMetadata queries the client metadata for all registered coin - // denominations. - DenomsMetadata(ctx context.Context, in *QueryDenomsMetadataRequest, opts ...grpc.CallOption) (*QueryDenomsMetadataResponse, error) - // DenomOwners queries for all account addresses that own a particular token - // denomination. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.46 - DenomOwners(ctx context.Context, in *QueryDenomOwnersRequest, opts ...grpc.CallOption) (*QueryDenomOwnersResponse, error) - // SendEnabled queries for SendEnabled entries. - // - // This query only returns denominations that have specific SendEnabled settings. - // Any denomination that does not have a specific setting will use the default - // params.default_send_enabled, and will not be returned by this query. - // - // Since: cosmos-sdk 0.47 - SendEnabled(ctx context.Context, in *QuerySendEnabledRequest, opts ...grpc.CallOption) (*QuerySendEnabledResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) { - out := new(QueryBalanceResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/Balance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AllBalances(ctx context.Context, in *QueryAllBalancesRequest, opts ...grpc.CallOption) (*QueryAllBalancesResponse, error) { - out := new(QueryAllBalancesResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/AllBalances", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SpendableBalances(ctx context.Context, in *QuerySpendableBalancesRequest, opts ...grpc.CallOption) (*QuerySpendableBalancesResponse, error) { - out := new(QuerySpendableBalancesResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/SpendableBalances", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SpendableBalanceByDenom(ctx context.Context, in *QuerySpendableBalanceByDenomRequest, opts ...grpc.CallOption) (*QuerySpendableBalanceByDenomResponse, error) { - out := new(QuerySpendableBalanceByDenomResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/SpendableBalanceByDenom", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SupplyOf(ctx context.Context, in *QuerySupplyOfRequest, opts ...grpc.CallOption) (*QuerySupplyOfResponse, error) { - out := new(QuerySupplyOfResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/SupplyOf", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DenomMetadata(ctx context.Context, in *QueryDenomMetadataRequest, opts ...grpc.CallOption) (*QueryDenomMetadataResponse, error) { - out := new(QueryDenomMetadataResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/DenomMetadata", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DenomsMetadata(ctx context.Context, in *QueryDenomsMetadataRequest, opts ...grpc.CallOption) (*QueryDenomsMetadataResponse, error) { - out := new(QueryDenomsMetadataResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/DenomsMetadata", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DenomOwners(ctx context.Context, in *QueryDenomOwnersRequest, opts ...grpc.CallOption) (*QueryDenomOwnersResponse, error) { - out := new(QueryDenomOwnersResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/DenomOwners", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SendEnabled(ctx context.Context, in *QuerySendEnabledRequest, opts ...grpc.CallOption) (*QuerySendEnabledResponse, error) { - out := new(QuerySendEnabledResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Query/SendEnabled", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Balance queries the balance of a single coin for a single account. - Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) - // AllBalances queries the balance of all coins for a single account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - AllBalances(context.Context, *QueryAllBalancesRequest) (*QueryAllBalancesResponse, error) - // SpendableBalances queries the spendable balance of all coins for a single - // account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.46 - SpendableBalances(context.Context, *QuerySpendableBalancesRequest) (*QuerySpendableBalancesResponse, error) - // SpendableBalanceByDenom queries the spendable balance of a single denom for - // a single account. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.47 - SpendableBalanceByDenom(context.Context, *QuerySpendableBalanceByDenomRequest) (*QuerySpendableBalanceByDenomResponse, error) - // TotalSupply queries the total supply of all coins. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) - // SupplyOf queries the supply of a single coin. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - SupplyOf(context.Context, *QuerySupplyOfRequest) (*QuerySupplyOfResponse, error) - // Params queries the parameters of x/bank module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // DenomsMetadata queries the client metadata of a given coin denomination. - DenomMetadata(context.Context, *QueryDenomMetadataRequest) (*QueryDenomMetadataResponse, error) - // DenomsMetadata queries the client metadata for all registered coin - // denominations. - DenomsMetadata(context.Context, *QueryDenomsMetadataRequest) (*QueryDenomsMetadataResponse, error) - // DenomOwners queries for all account addresses that own a particular token - // denomination. - // - // When called from another module, this query might consume a high amount of - // gas if the pagination field is incorrectly set. - // - // Since: cosmos-sdk 0.46 - DenomOwners(context.Context, *QueryDenomOwnersRequest) (*QueryDenomOwnersResponse, error) - // SendEnabled queries for SendEnabled entries. - // - // This query only returns denominations that have specific SendEnabled settings. - // Any denomination that does not have a specific setting will use the default - // params.default_send_enabled, and will not be returned by this query. - // - // Since: cosmos-sdk 0.47 - SendEnabled(context.Context, *QuerySendEnabledRequest) (*QuerySendEnabledResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Balance(ctx context.Context, req *QueryBalanceRequest) (*QueryBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Balance not implemented") -} -func (*UnimplementedQueryServer) AllBalances(ctx context.Context, req *QueryAllBalancesRequest) (*QueryAllBalancesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AllBalances not implemented") -} -func (*UnimplementedQueryServer) SpendableBalances(ctx context.Context, req *QuerySpendableBalancesRequest) (*QuerySpendableBalancesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SpendableBalances not implemented") -} -func (*UnimplementedQueryServer) SpendableBalanceByDenom(ctx context.Context, req *QuerySpendableBalanceByDenomRequest) (*QuerySpendableBalanceByDenomResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SpendableBalanceByDenom not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply not implemented") -} -func (*UnimplementedQueryServer) SupplyOf(ctx context.Context, req *QuerySupplyOfRequest) (*QuerySupplyOfResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SupplyOf not implemented") -} -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) DenomMetadata(ctx context.Context, req *QueryDenomMetadataRequest) (*QueryDenomMetadataResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DenomMetadata not implemented") -} -func (*UnimplementedQueryServer) DenomsMetadata(ctx context.Context, req *QueryDenomsMetadataRequest) (*QueryDenomsMetadataResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DenomsMetadata not implemented") -} -func (*UnimplementedQueryServer) DenomOwners(ctx context.Context, req *QueryDenomOwnersRequest) (*QueryDenomOwnersResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DenomOwners not implemented") -} -func (*UnimplementedQueryServer) SendEnabled(ctx context.Context, req *QuerySendEnabledRequest) (*QuerySendEnabledResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SendEnabled not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Balance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Balance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/Balance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Balance(ctx, req.(*QueryBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AllBalances_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllBalancesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AllBalances(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/AllBalances", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AllBalances(ctx, req.(*QueryAllBalancesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SpendableBalances_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySpendableBalancesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SpendableBalances(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/SpendableBalances", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SpendableBalances(ctx, req.(*QuerySpendableBalancesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SpendableBalanceByDenom_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySpendableBalanceByDenomRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SpendableBalanceByDenom(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/SpendableBalanceByDenom", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SpendableBalanceByDenom(ctx, req.(*QuerySpendableBalanceByDenomRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SupplyOf_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySupplyOfRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SupplyOf(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/SupplyOf", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SupplyOf(ctx, req.(*QuerySupplyOfRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DenomMetadata_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDenomMetadataRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DenomMetadata(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/DenomMetadata", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DenomMetadata(ctx, req.(*QueryDenomMetadataRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DenomsMetadata_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDenomsMetadataRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DenomsMetadata(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/DenomsMetadata", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DenomsMetadata(ctx, req.(*QueryDenomsMetadataRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DenomOwners_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDenomOwnersRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DenomOwners(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/DenomOwners", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DenomOwners(ctx, req.(*QueryDenomOwnersRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SendEnabled_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySendEnabledRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SendEnabled(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Query/SendEnabled", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SendEnabled(ctx, req.(*QuerySendEnabledRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.bank.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Balance", - Handler: _Query_Balance_Handler, - }, - { - MethodName: "AllBalances", - Handler: _Query_AllBalances_Handler, - }, - { - MethodName: "SpendableBalances", - Handler: _Query_SpendableBalances_Handler, - }, - { - MethodName: "SpendableBalanceByDenom", - Handler: _Query_SpendableBalanceByDenom_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - { - MethodName: "SupplyOf", - Handler: _Query_SupplyOf_Handler, - }, - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "DenomMetadata", - Handler: _Query_DenomMetadata_Handler, - }, - { - MethodName: "DenomsMetadata", - Handler: _Query_DenomsMetadata_Handler, - }, - { - MethodName: "DenomOwners", - Handler: _Query_DenomOwners_Handler, - }, - { - MethodName: "SendEnabled", - Handler: _Query_SendEnabled_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/bank/v1beta1/query.proto", -} - -func (m *QueryBalanceRequest) 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 *QueryBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryBalanceResponse) 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 *QueryBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Balance != nil { - { - size, err := m.Balance.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAllBalancesRequest) 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 *QueryAllBalancesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllBalancesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAllBalancesResponse) 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 *QueryAllBalancesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllBalancesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Balances) > 0 { - for iNdEx := len(m.Balances) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Balances[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QuerySpendableBalancesRequest) 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 *QuerySpendableBalancesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpendableBalancesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySpendableBalancesResponse) 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 *QuerySpendableBalancesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpendableBalancesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Balances) > 0 { - for iNdEx := len(m.Balances) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Balances[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QuerySpendableBalanceByDenomRequest) 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 *QuerySpendableBalanceByDenomRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpendableBalanceByDenomRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySpendableBalanceByDenomResponse) 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 *QuerySpendableBalanceByDenomResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpendableBalanceByDenomResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Balance != nil { - { - size, err := m.Balance.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyRequest) 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 *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) 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 *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Supply) > 0 { - for iNdEx := len(m.Supply) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Supply[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QuerySupplyOfRequest) 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 *QuerySupplyOfRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySupplyOfRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySupplyOfResponse) 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 *QuerySupplyOfResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySupplyOfResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryParamsRequest) 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 *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) 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 *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryDenomsMetadataRequest) 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 *QueryDenomsMetadataRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomsMetadataRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDenomsMetadataResponse) 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 *QueryDenomsMetadataResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomsMetadataResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Metadatas) > 0 { - for iNdEx := len(m.Metadatas) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Metadatas[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDenomMetadataRequest) 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 *QueryDenomMetadataRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomMetadataRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDenomMetadataResponse) 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 *QueryDenomMetadataResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomMetadataResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Metadata.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryDenomOwnersRequest) 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 *QueryDenomOwnersRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomOwnersRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *DenomOwner) 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 *DenomOwner) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DenomOwner) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Balance.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDenomOwnersResponse) 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 *QueryDenomOwnersResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDenomOwnersResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.DenomOwners) > 0 { - for iNdEx := len(m.DenomOwners) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomOwners[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QuerySendEnabledRequest) 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 *QuerySendEnabledRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySendEnabledRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6 - i-- - dAtA[i] = 0x9a - } - if len(m.Denoms) > 0 { - for iNdEx := len(m.Denoms) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Denoms[iNdEx]) - copy(dAtA[i:], m.Denoms[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denoms[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QuerySendEnabledResponse) 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 *QuerySendEnabledResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySendEnabledResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6 - i-- - dAtA[i] = 0x9a - } - if len(m.SendEnabled) > 0 { - for iNdEx := len(m.SendEnabled) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SendEnabled[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Balance != nil { - l = m.Balance.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAllBalancesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAllBalancesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Balances) > 0 { - for _, e := range m.Balances { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySpendableBalancesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySpendableBalancesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Balances) > 0 { - for _, e := range m.Balances { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySpendableBalanceByDenomRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySpendableBalanceByDenomResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Balance != nil { - l = m.Balance.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Supply) > 0 { - for _, e := range m.Supply { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySupplyOfRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySupplyOfResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Amount.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDenomsMetadataRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDenomsMetadataResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Metadatas) > 0 { - for _, e := range m.Metadatas { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDenomMetadataRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDenomMetadataResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Metadata.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDenomOwnersRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *DenomOwner) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Balance.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDenomOwnersResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DenomOwners) > 0 { - for _, e := range m.DenomOwners { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySendEnabledRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Denoms) > 0 { - for _, s := range m.Denoms { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 2 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySendEnabledResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SendEnabled) > 0 { - for _, e := range m.SendEnabled { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 2 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryBalanceRequest) 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 ErrIntOverflowQuery - } - 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: QueryBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBalanceResponse) 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 ErrIntOverflowQuery - } - 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: QueryBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Balance == nil { - m.Balance = &types.Coin{} - } - if err := m.Balance.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAllBalancesRequest) 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 ErrIntOverflowQuery - } - 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: QueryAllBalancesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllBalancesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAllBalancesResponse) 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 ErrIntOverflowQuery - } - 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: QueryAllBalancesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllBalancesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balances", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Balances = append(m.Balances, types.Coin{}) - if err := m.Balances[len(m.Balances)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySpendableBalancesRequest) 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 ErrIntOverflowQuery - } - 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: QuerySpendableBalancesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpendableBalancesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySpendableBalancesResponse) 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 ErrIntOverflowQuery - } - 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: QuerySpendableBalancesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpendableBalancesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balances", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Balances = append(m.Balances, types.Coin{}) - if err := m.Balances[len(m.Balances)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySpendableBalanceByDenomRequest) 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 ErrIntOverflowQuery - } - 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: QuerySpendableBalanceByDenomRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpendableBalanceByDenomRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySpendableBalanceByDenomResponse) 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 ErrIntOverflowQuery - } - 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: QuerySpendableBalanceByDenomResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpendableBalanceByDenomResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Balance == nil { - m.Balance = &types.Coin{} - } - if err := m.Balance.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyRequest) 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 ErrIntOverflowQuery - } - 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: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyResponse) 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 ErrIntOverflowQuery - } - 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: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supply", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Supply = append(m.Supply, types.Coin{}) - if err := m.Supply[len(m.Supply)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySupplyOfRequest) 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 ErrIntOverflowQuery - } - 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: QuerySupplyOfRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySupplyOfRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySupplyOfResponse) 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 ErrIntOverflowQuery - } - 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: QuerySupplyOfResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySupplyOfResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsRequest) 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 ErrIntOverflowQuery - } - 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: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) 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 ErrIntOverflowQuery - } - 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: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomsMetadataRequest) 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 ErrIntOverflowQuery - } - 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: QueryDenomsMetadataRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomsMetadataRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomsMetadataResponse) 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 ErrIntOverflowQuery - } - 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: QueryDenomsMetadataResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomsMetadataResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Metadatas", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Metadatas = append(m.Metadatas, Metadata{}) - if err := m.Metadatas[len(m.Metadatas)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomMetadataRequest) 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 ErrIntOverflowQuery - } - 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: QueryDenomMetadataRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomMetadataRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomMetadataResponse) 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 ErrIntOverflowQuery - } - 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: QueryDenomMetadataResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomMetadataResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomOwnersRequest) 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 ErrIntOverflowQuery - } - 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: QueryDenomOwnersRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomOwnersRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DenomOwner) 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 ErrIntOverflowQuery - } - 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: DenomOwner: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DenomOwner: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Balance.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDenomOwnersResponse) 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 ErrIntOverflowQuery - } - 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: QueryDenomOwnersResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDenomOwnersResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomOwners", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomOwners = append(m.DenomOwners, &DenomOwner{}) - if err := m.DenomOwners[len(m.DenomOwners)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySendEnabledRequest) 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 ErrIntOverflowQuery - } - 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: QuerySendEnabledRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySendEnabledRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denoms", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denoms = append(m.Denoms, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 99: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QuerySendEnabledResponse) 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 ErrIntOverflowQuery - } - 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: QuerySendEnabledResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySendEnabledResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SendEnabled", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SendEnabled = append(m.SendEnabled, &SendEnabled{}) - if err := m.SendEnabled[len(m.SendEnabled)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 99: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(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, ErrIntOverflowQuery - } - 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, ErrIntOverflowQuery - } - 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, ErrIntOverflowQuery - } - 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, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bank/types/query.pb.gw.go b/x/bank/types/query.pb.gw.go deleted file mode 100644 index 982f53168..000000000 --- a/x/bank/types/query.pb.gw.go +++ /dev/null @@ -1,1181 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmos/bank/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -var ( - filter_Query_Balance_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Balance_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Balance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Balance_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Balance(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_AllBalances_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_AllBalances_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllBalancesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllBalances_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.AllBalances(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AllBalances_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllBalancesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_AllBalances_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.AllBalances(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_SpendableBalances_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_SpendableBalances_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpendableBalancesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpendableBalances_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SpendableBalances(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_SpendableBalances_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpendableBalancesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpendableBalances_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SpendableBalances(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_SpendableBalanceByDenom_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_SpendableBalanceByDenom_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpendableBalanceByDenomRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpendableBalanceByDenom_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SpendableBalanceByDenom(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_SpendableBalanceByDenom_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpendableBalanceByDenomRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpendableBalanceByDenom_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SpendableBalanceByDenom(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalSupply_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalSupply_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalSupply_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalSupply(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_SupplyOf_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_SupplyOf_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySupplyOfRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SupplyOf_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SupplyOf(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_SupplyOf_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySupplyOfRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SupplyOf_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SupplyOf(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_DenomMetadata_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomMetadataRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := client.DenomMetadata(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DenomMetadata_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomMetadataRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := server.DenomMetadata(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_DenomsMetadata_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_DenomsMetadata_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomsMetadataRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_DenomsMetadata_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.DenomsMetadata(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DenomsMetadata_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomsMetadataRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_DenomsMetadata_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.DenomsMetadata(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_DenomOwners_0 = &utilities.DoubleArray{Encoding: map[string]int{"denom": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_DenomOwners_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomOwnersRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_DenomOwners_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.DenomOwners(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DenomOwners_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDenomOwnersRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_DenomOwners_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.DenomOwners(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_SendEnabled_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_SendEnabled_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySendEnabledRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SendEnabled_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SendEnabled(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_SendEnabled_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySendEnabledRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SendEnabled_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SendEnabled(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Balance_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AllBalances_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_AllBalances_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AllBalances_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpendableBalances_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_SpendableBalances_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SpendableBalances_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpendableBalanceByDenom_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_SpendableBalanceByDenom_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SpendableBalanceByDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalSupply_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SupplyOf_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_SupplyOf_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SupplyOf_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DenomMetadata_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomsMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DenomsMetadata_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomsMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomOwners_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DenomOwners_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomOwners_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SendEnabled_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_SendEnabled_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SendEnabled_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Balance_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AllBalances_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_AllBalances_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AllBalances_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpendableBalances_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_SpendableBalances_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SpendableBalances_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpendableBalanceByDenom_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_SpendableBalanceByDenom_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SpendableBalanceByDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalSupply_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SupplyOf_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_SupplyOf_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SupplyOf_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DenomMetadata_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomsMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DenomsMetadata_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomsMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DenomOwners_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DenomOwners_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DenomOwners_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SendEnabled_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_SendEnabled_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_SendEnabled_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "bank", "v1beta1", "balances", "address", "by_denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AllBalances_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "bank", "v1beta1", "balances", "address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SpendableBalances_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "bank", "v1beta1", "spendable_balances", "address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SpendableBalanceByDenom_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "bank", "v1beta1", "spendable_balances", "address", "by_denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "bank", "v1beta1", "supply"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SupplyOf_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmos", "bank", "v1beta1", "supply", "by_denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "bank", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DenomMetadata_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "bank", "v1beta1", "denoms_metadata", "denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DenomsMetadata_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "bank", "v1beta1", "denoms_metadata"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DenomOwners_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "bank", "v1beta1", "denom_owners", "denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SendEnabled_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "bank", "v1beta1", "send_enabled"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Balance_0 = runtime.ForwardResponseMessage - - forward_Query_AllBalances_0 = runtime.ForwardResponseMessage - - forward_Query_SpendableBalances_0 = runtime.ForwardResponseMessage - - forward_Query_SpendableBalanceByDenom_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage - - forward_Query_SupplyOf_0 = runtime.ForwardResponseMessage - - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_DenomMetadata_0 = runtime.ForwardResponseMessage - - forward_Query_DenomsMetadata_0 = runtime.ForwardResponseMessage - - forward_Query_DenomOwners_0 = runtime.ForwardResponseMessage - - forward_Query_SendEnabled_0 = runtime.ForwardResponseMessage -) diff --git a/x/bank/types/send_authorization.go b/x/bank/types/send_authorization.go deleted file mode 100644 index ba2796fe9..000000000 --- a/x/bank/types/send_authorization.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/authz" -) - -// TODO: Revisit this once we have proper gas fee framework. -// Ref: https://github.com/cosmos/cosmos-sdk/issues/9054 -// Ref: https://github.com/cosmos/cosmos-sdk/discussions/9072 -const gasCostPerIteration = uint64(10) - -var _ authz.Authorization = &SendAuthorization{} - -// NewSendAuthorization creates a new SendAuthorization object. -func NewSendAuthorization(spendLimit sdk.Coins, allowed []sdk.AccAddress) *SendAuthorization { - return &SendAuthorization{ - AllowList: toBech32Addresses(allowed), - SpendLimit: spendLimit, - } -} - -// MsgTypeURL implements Authorization.MsgTypeURL. -func (a SendAuthorization) MsgTypeURL() string { - return sdk.MsgTypeURL(&MsgSend{}) -} - -// Accept implements Authorization.Accept. -func (a SendAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptResponse, error) { - mSend, ok := msg.(*MsgSend) - if !ok { - return authz.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("type mismatch") - } - - limitLeft, isNegative := a.SpendLimit.SafeSub(mSend.Amount...) - if isNegative { - return authz.AcceptResponse{}, sdkerrors.ErrInsufficientFunds.Wrapf("requested amount is more than spend limit") - } - - isAddrExists := false - toAddr := mSend.ToAddress - allowedList := a.GetAllowList() - for _, addr := range allowedList { - ctx.GasMeter().ConsumeGas(gasCostPerIteration, "send authorization") - if addr == toAddr { - isAddrExists = true - break - } - } - - if len(allowedList) > 0 && !isAddrExists { - return authz.AcceptResponse{}, sdkerrors.ErrUnauthorized.Wrapf("cannot send to %s address", toAddr) - } - - if limitLeft.IsZero() { - return authz.AcceptResponse{Accept: true, Delete: true}, nil - } - - return authz.AcceptResponse{Accept: true, Delete: false, Updated: &SendAuthorization{SpendLimit: limitLeft, AllowList: allowedList}}, nil -} - -// ValidateBasic implements Authorization.ValidateBasic. -func (a SendAuthorization) ValidateBasic() error { - if len(a.SpendLimit) == 0 { - return sdkerrors.ErrInvalidCoins.Wrap("spend limit cannot be nil") - } - if !a.SpendLimit.IsAllPositive() { - return sdkerrors.ErrInvalidCoins.Wrapf("spend limit must be positive") - } - - found := make(map[string]bool, 0) - for i := 0; i < len(a.AllowList); i++ { - if found[a.AllowList[i]] { - return ErrDuplicateEntry - } - - found[a.AllowList[i]] = true - } - - return nil -} - -func toBech32Addresses(allowed []sdk.AccAddress) []string { - if len(allowed) == 0 { - return nil - } - - allowedAddrs := make([]string, len(allowed)) - for i, addr := range allowed { - allowedAddrs[i] = addr.String() - } - - return allowedAddrs -} diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go deleted file mode 100644 index b4e976806..000000000 --- a/x/bank/types/send_authorization_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var ( - coins1000 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) - coins500 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(500))) - fromAddr = sdk.AccAddress("_____from _____") - toAddr = sdk.AccAddress("_______to________") - unknownAddr = sdk.AccAddress("_____unknown_____") -) - -func TestSendAuthorization(t *testing.T) { - ctx := testutil.DefaultContextWithDB(t, sdk.NewKVStoreKey(types.StoreKey), sdk.NewTransientStoreKey("transient_test")).Ctx.WithBlockHeader(tmproto.Header{}) - allowList := make([]sdk.AccAddress, 1) - allowList[0] = toAddr - authorization := types.NewSendAuthorization(coins1000, nil) - - t.Log("verify authorization returns valid method name") - require.Equal(t, authorization.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send := types.NewMsgSend(fromAddr, toAddr, coins1000) - - require.NoError(t, authorization.ValidateBasic()) - - t.Log("verify updated authorization returns nil") - resp, err := authorization.Accept(ctx, send) - require.NoError(t, err) - require.True(t, resp.Delete) - require.Nil(t, resp.Updated) - - authorization = types.NewSendAuthorization(coins1000, nil) - require.Equal(t, authorization.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send = types.NewMsgSend(fromAddr, toAddr, coins500) - require.NoError(t, authorization.ValidateBasic()) - resp, err = authorization.Accept(ctx, send) - - t.Log("verify updated authorization returns remaining spent limit") - require.NoError(t, err) - require.False(t, resp.Delete) - require.NotNil(t, resp.Updated) - sendAuth := types.NewSendAuthorization(coins500, nil) - require.Equal(t, sendAuth.String(), resp.Updated.String()) - - t.Log("expect updated authorization nil after spending remaining amount") - resp, err = resp.Updated.Accept(ctx, send) - require.NoError(t, err) - require.True(t, resp.Delete) - require.Nil(t, resp.Updated) - - t.Log("allow list and no address") - authzWithAllowList := types.NewSendAuthorization(coins1000, allowList) - require.Equal(t, authzWithAllowList.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send = types.NewMsgSend(fromAddr, unknownAddr, coins500) - require.NoError(t, authzWithAllowList.ValidateBasic()) - resp, err = authzWithAllowList.Accept(ctx, send) - require.False(t, resp.Accept) - require.False(t, resp.Delete) - require.Nil(t, resp.Updated) - require.Error(t, err) - require.Contains(t, err.Error(), fmt.Sprintf("cannot send to %s address", unknownAddr)) - - t.Log("send to address in allow list") - authzWithAllowList = types.NewSendAuthorization(coins1000, allowList) - require.Equal(t, authzWithAllowList.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send = types.NewMsgSend(fromAddr, allowList[0], coins500) - require.NoError(t, authzWithAllowList.ValidateBasic()) - resp, err = authzWithAllowList.Accept(ctx, send) - require.NoError(t, err) - require.True(t, resp.Accept) - require.NotNil(t, resp.Updated) - // coins1000-coins500 = coins500 - require.Equal(t, types.NewSendAuthorization(coins500, allowList).String(), resp.Updated.String()) - - t.Log("send everything to address not in allow list") - authzWithAllowList = types.NewSendAuthorization(coins1000, allowList) - require.Equal(t, authzWithAllowList.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send = types.NewMsgSend(fromAddr, unknownAddr, coins1000) - require.NoError(t, authzWithAllowList.ValidateBasic()) - resp, err = authzWithAllowList.Accept(ctx, send) - require.Error(t, err) - require.Contains(t, err.Error(), fmt.Sprintf("cannot send to %s address", unknownAddr)) - - t.Log("send everything to address in allow list") - authzWithAllowList = types.NewSendAuthorization(coins1000, allowList) - require.Equal(t, authzWithAllowList.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") - require.NoError(t, authorization.ValidateBasic()) - send = types.NewMsgSend(fromAddr, allowList[0], coins1000) - require.NoError(t, authzWithAllowList.ValidateBasic()) - resp, err = authzWithAllowList.Accept(ctx, send) - require.NoError(t, err) - require.True(t, resp.Accept) - require.Nil(t, resp.Updated) -} diff --git a/x/bank/types/tx.pb.go b/x/bank/types/tx.pb.go deleted file mode 100644 index b3fd1ea3d..000000000 --- a/x/bank/types/tx.pb.go +++ /dev/null @@ -1,1924 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/bank/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - 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 - -// MsgSend represents a message to send coins from one account to another. -type MsgSend struct { - FromAddress string `protobuf:"bytes,1,opt,name=from_address,json=fromAddress,proto3" json:"from_address,omitempty"` - ToAddress string `protobuf:"bytes,2,opt,name=to_address,json=toAddress,proto3" json:"to_address,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgSend) Reset() { *m = MsgSend{} } -func (m *MsgSend) String() string { return proto.CompactTextString(m) } -func (*MsgSend) ProtoMessage() {} -func (*MsgSend) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{0} -} -func (m *MsgSend) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSend.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 *MsgSend) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSend.Merge(m, src) -} -func (m *MsgSend) XXX_Size() int { - return m.Size() -} -func (m *MsgSend) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSend.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSend proto.InternalMessageInfo - -// MsgSendResponse defines the Msg/Send response type. -type MsgSendResponse struct { -} - -func (m *MsgSendResponse) Reset() { *m = MsgSendResponse{} } -func (m *MsgSendResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSendResponse) ProtoMessage() {} -func (*MsgSendResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{1} -} -func (m *MsgSendResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSendResponse.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 *MsgSendResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSendResponse.Merge(m, src) -} -func (m *MsgSendResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSendResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSendResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSendResponse proto.InternalMessageInfo - -// MsgMultiSend represents an arbitrary multi-in, multi-out send message. -type MsgMultiSend struct { - // Inputs, despite being `repeated`, only allows one sender input. This is - // checked in MsgMultiSend's ValidateBasic. - Inputs []Input `protobuf:"bytes,1,rep,name=inputs,proto3" json:"inputs"` - Outputs []Output `protobuf:"bytes,2,rep,name=outputs,proto3" json:"outputs"` -} - -func (m *MsgMultiSend) Reset() { *m = MsgMultiSend{} } -func (m *MsgMultiSend) String() string { return proto.CompactTextString(m) } -func (*MsgMultiSend) ProtoMessage() {} -func (*MsgMultiSend) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{2} -} -func (m *MsgMultiSend) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiSend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiSend.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 *MsgMultiSend) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiSend.Merge(m, src) -} -func (m *MsgMultiSend) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiSend) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiSend.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiSend proto.InternalMessageInfo - -func (m *MsgMultiSend) GetInputs() []Input { - if m != nil { - return m.Inputs - } - return nil -} - -func (m *MsgMultiSend) GetOutputs() []Output { - if m != nil { - return m.Outputs - } - return nil -} - -// MsgMultiSendResponse defines the Msg/MultiSend response type. -type MsgMultiSendResponse struct { -} - -func (m *MsgMultiSendResponse) Reset() { *m = MsgMultiSendResponse{} } -func (m *MsgMultiSendResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMultiSendResponse) ProtoMessage() {} -func (*MsgMultiSendResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{3} -} -func (m *MsgMultiSendResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiSendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiSendResponse.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 *MsgMultiSendResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiSendResponse.Merge(m, src) -} -func (m *MsgMultiSendResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiSendResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiSendResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiSendResponse proto.InternalMessageInfo - -// MsgUpdateParams is the Msg/UpdateParams request type. -// -// Since: cosmos-sdk 0.47 -type MsgUpdateParams struct { - // authority is the address that controls the module (defaults to x/gov unless overwritten). - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/bank parameters to update. - // - // NOTE: All parameters must be supplied. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{4} -} -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -func (m *MsgUpdateParams) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgUpdateParams) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: cosmos-sdk 0.47 -type MsgUpdateParamsResponse struct { -} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{5} -} -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -// MsgSetSendEnabled is the Msg/SetSendEnabled request type. -// -// Only entries to add/update/delete need to be included. -// Existing SendEnabled entries that are not included in this -// message are left unchanged. -// -// Since: cosmos-sdk 0.47 -type MsgSetSendEnabled struct { - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // send_enabled is the list of entries to add or update. - SendEnabled []*SendEnabled `protobuf:"bytes,2,rep,name=send_enabled,json=sendEnabled,proto3" json:"send_enabled,omitempty"` - // use_default_for is a list of denoms that should use the params.default_send_enabled value. - // Denoms listed here will have their SendEnabled entries deleted. - // If a denom is included that doesn't have a SendEnabled entry, - // it will be ignored. - UseDefaultFor []string `protobuf:"bytes,3,rep,name=use_default_for,json=useDefaultFor,proto3" json:"use_default_for,omitempty"` -} - -func (m *MsgSetSendEnabled) Reset() { *m = MsgSetSendEnabled{} } -func (m *MsgSetSendEnabled) String() string { return proto.CompactTextString(m) } -func (*MsgSetSendEnabled) ProtoMessage() {} -func (*MsgSetSendEnabled) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{6} -} -func (m *MsgSetSendEnabled) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetSendEnabled) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetSendEnabled.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 *MsgSetSendEnabled) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetSendEnabled.Merge(m, src) -} -func (m *MsgSetSendEnabled) XXX_Size() int { - return m.Size() -} -func (m *MsgSetSendEnabled) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetSendEnabled.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetSendEnabled proto.InternalMessageInfo - -func (m *MsgSetSendEnabled) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgSetSendEnabled) GetSendEnabled() []*SendEnabled { - if m != nil { - return m.SendEnabled - } - return nil -} - -func (m *MsgSetSendEnabled) GetUseDefaultFor() []string { - if m != nil { - return m.UseDefaultFor - } - return nil -} - -// MsgSetSendEnabledResponse defines the Msg/SetSendEnabled response type. -// -// Since: cosmos-sdk 0.47 -type MsgSetSendEnabledResponse struct { -} - -func (m *MsgSetSendEnabledResponse) Reset() { *m = MsgSetSendEnabledResponse{} } -func (m *MsgSetSendEnabledResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSetSendEnabledResponse) ProtoMessage() {} -func (*MsgSetSendEnabledResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1d8cb1613481f5b7, []int{7} -} -func (m *MsgSetSendEnabledResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetSendEnabledResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetSendEnabledResponse.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 *MsgSetSendEnabledResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetSendEnabledResponse.Merge(m, src) -} -func (m *MsgSetSendEnabledResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSetSendEnabledResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetSendEnabledResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetSendEnabledResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgSend)(nil), "cosmos.bank.v1beta1.MsgSend") - proto.RegisterType((*MsgSendResponse)(nil), "cosmos.bank.v1beta1.MsgSendResponse") - proto.RegisterType((*MsgMultiSend)(nil), "cosmos.bank.v1beta1.MsgMultiSend") - proto.RegisterType((*MsgMultiSendResponse)(nil), "cosmos.bank.v1beta1.MsgMultiSendResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "cosmos.bank.v1beta1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "cosmos.bank.v1beta1.MsgUpdateParamsResponse") - proto.RegisterType((*MsgSetSendEnabled)(nil), "cosmos.bank.v1beta1.MsgSetSendEnabled") - proto.RegisterType((*MsgSetSendEnabledResponse)(nil), "cosmos.bank.v1beta1.MsgSetSendEnabledResponse") -} - -func init() { proto.RegisterFile("cosmos/bank/v1beta1/tx.proto", fileDescriptor_1d8cb1613481f5b7) } - -var fileDescriptor_1d8cb1613481f5b7 = []byte{ - // 690 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0xcd, 0x4f, 0xd4, 0x5e, - 0x14, 0x6d, 0x99, 0xdf, 0x6f, 0x48, 0x1f, 0xa3, 0x84, 0x4a, 0x84, 0x29, 0xa4, 0x03, 0x8d, 0x21, - 0x80, 0xd2, 0x0a, 0x7e, 0x25, 0x63, 0x34, 0x3a, 0xa8, 0x89, 0x26, 0x13, 0xcd, 0x10, 0x17, 0xba, - 0x99, 0xb4, 0xf4, 0xd1, 0x69, 0xa0, 0x7d, 0x4d, 0xdf, 0x2b, 0x81, 0x9d, 0xba, 0x32, 0xae, 0xdc, - 0xbb, 0x61, 0x69, 0x5c, 0xb1, 0x70, 0x69, 0xe2, 0x96, 0x25, 0x71, 0xe5, 0x4a, 0x0d, 0x2c, 0xd0, - 0xff, 0xc2, 0xbc, 0x8f, 0x96, 0xce, 0x30, 0xc3, 0x10, 0x37, 0xd3, 0xce, 0xbb, 0xe7, 0x9c, 0x7b, - 0xcf, 0xed, 0x69, 0xc1, 0xe4, 0x2a, 0xc2, 0x01, 0xc2, 0x96, 0x63, 0x87, 0xeb, 0xd6, 0xe6, 0xa2, - 0x03, 0x89, 0xbd, 0x68, 0x91, 0x2d, 0x33, 0x8a, 0x11, 0x41, 0xea, 0x05, 0x5e, 0x35, 0x69, 0xd5, - 0x14, 0x55, 0x6d, 0xd4, 0x43, 0x1e, 0x62, 0x75, 0x8b, 0xde, 0x71, 0xa8, 0xa6, 0x67, 0x42, 0x18, - 0x66, 0x42, 0xab, 0xc8, 0x0f, 0x4f, 0xd4, 0x73, 0x8d, 0x98, 0x2e, 0xaf, 0x97, 0x79, 0xbd, 0xc9, - 0x85, 0x45, 0x5f, 0x5e, 0x1a, 0x13, 0xd4, 0x00, 0x7b, 0xd6, 0xe6, 0x22, 0xbd, 0x88, 0xc2, 0x88, - 0x1d, 0xf8, 0x21, 0xb2, 0xd8, 0x2f, 0x3f, 0x32, 0x3e, 0x0c, 0x80, 0xc1, 0x3a, 0xf6, 0x56, 0x60, - 0xe8, 0xaa, 0xb7, 0x41, 0x69, 0x2d, 0x46, 0x41, 0xd3, 0x76, 0xdd, 0x18, 0x62, 0x3c, 0x2e, 0x4f, - 0xc9, 0xb3, 0x4a, 0x6d, 0xfc, 0xdb, 0xe7, 0x85, 0x51, 0xa1, 0x7f, 0x9f, 0x57, 0x56, 0x48, 0xec, - 0x87, 0x5e, 0x63, 0x88, 0xa2, 0xc5, 0x91, 0x7a, 0x0b, 0x00, 0x82, 0x32, 0xea, 0x40, 0x1f, 0xaa, - 0x42, 0x50, 0x4a, 0x6c, 0x81, 0xa2, 0x1d, 0xa0, 0x24, 0x24, 0xe3, 0x85, 0xa9, 0xc2, 0xec, 0xd0, - 0x52, 0xd9, 0xcc, 0x96, 0x88, 0x61, 0xba, 0x44, 0x73, 0x19, 0xf9, 0x61, 0xed, 0xc6, 0xde, 0x8f, - 0x8a, 0xf4, 0xe9, 0x67, 0x65, 0xd6, 0xf3, 0x49, 0x2b, 0x71, 0xcc, 0x55, 0x14, 0x08, 0xe7, 0xe2, - 0xb2, 0x80, 0xdd, 0x75, 0x8b, 0x6c, 0x47, 0x10, 0x33, 0x02, 0xfe, 0x78, 0xb4, 0x3b, 0x2f, 0x37, - 0x84, 0x7e, 0xf5, 0xea, 0xdb, 0x9d, 0x8a, 0xf4, 0x7b, 0xa7, 0x22, 0xbd, 0x39, 0xda, 0x9d, 0x6f, - 0xb3, 0xfa, 0xee, 0x68, 0x77, 0x5e, 0xcd, 0x49, 0x88, 0x8d, 0x18, 0x23, 0x60, 0x58, 0xdc, 0x36, - 0x20, 0x8e, 0x50, 0x88, 0xa1, 0xf1, 0x45, 0x06, 0xa5, 0x3a, 0xf6, 0xea, 0xc9, 0x06, 0xf1, 0xd9, - 0xd6, 0xee, 0x80, 0xa2, 0x1f, 0x46, 0x09, 0xa1, 0xfb, 0xa2, 0xf3, 0x6b, 0x66, 0x97, 0x10, 0x98, - 0x8f, 0x29, 0xa4, 0xa6, 0x50, 0x03, 0x62, 0x28, 0x4e, 0x52, 0xef, 0x81, 0x41, 0x94, 0x10, 0xc6, - 0x1f, 0x60, 0xfc, 0x89, 0xae, 0xfc, 0xa7, 0x0c, 0x93, 0x17, 0x48, 0x69, 0xd5, 0xcb, 0xa9, 0x25, - 0x21, 0x49, 0xcd, 0x8c, 0xb5, 0x9b, 0xc9, 0xa6, 0x35, 0x2e, 0x82, 0xd1, 0xfc, 0xff, 0xcc, 0xd6, - 0x57, 0x99, 0x59, 0x7d, 0x1e, 0xb9, 0x36, 0x81, 0xcf, 0xec, 0xd8, 0x0e, 0xb0, 0x7a, 0x13, 0x28, - 0x76, 0x42, 0x5a, 0x28, 0xf6, 0xc9, 0x76, 0xdf, 0x30, 0x1c, 0x43, 0xd5, 0xbb, 0xa0, 0x18, 0x31, - 0x05, 0x16, 0x83, 0x5e, 0x8e, 0x78, 0x93, 0xb6, 0x95, 0x70, 0x56, 0xf5, 0x3a, 0x35, 0x73, 0xac, - 0x47, 0xfd, 0x4c, 0xe7, 0xfc, 0x6c, 0xf1, 0x77, 0xa2, 0x63, 0x5a, 0xa3, 0x0c, 0xc6, 0x3a, 0x8e, - 0x32, 0x73, 0x7f, 0x64, 0x30, 0xc2, 0x9e, 0x23, 0xa1, 0x9e, 0x1f, 0x86, 0xb6, 0xb3, 0x01, 0xdd, - 0x7f, 0xb6, 0xb7, 0x0c, 0x4a, 0x18, 0x86, 0x6e, 0x13, 0x72, 0x1d, 0xf1, 0xd8, 0xa6, 0xba, 0x9a, - 0xcc, 0xf5, 0x6b, 0x0c, 0xe1, 0x5c, 0xf3, 0x19, 0x30, 0x9c, 0x60, 0xd8, 0x74, 0xe1, 0x9a, 0x9d, - 0x6c, 0x90, 0xe6, 0x1a, 0x8a, 0x59, 0xfc, 0x95, 0xc6, 0xb9, 0x04, 0xc3, 0x07, 0xfc, 0xf4, 0x11, - 0x8a, 0xab, 0xd6, 0xc9, 0x5d, 0x4c, 0x76, 0x06, 0x35, 0xef, 0xca, 0x98, 0x00, 0xe5, 0x13, 0x87, - 0xe9, 0x22, 0x96, 0x5e, 0x17, 0x40, 0xa1, 0x8e, 0x3d, 0xf5, 0x09, 0xf8, 0x8f, 0x65, 0x77, 0xb2, - 0xeb, 0xd0, 0x22, 0xf2, 0xda, 0xa5, 0xd3, 0xaa, 0xa9, 0xa6, 0xfa, 0x02, 0x28, 0xc7, 0x2f, 0xc3, - 0x74, 0x2f, 0x4a, 0x06, 0xd1, 0xe6, 0xfa, 0x42, 0x32, 0x69, 0x07, 0x94, 0xda, 0x02, 0xd9, 0x73, - 0xa0, 0x3c, 0x4a, 0xbb, 0x72, 0x16, 0x54, 0xd6, 0xa3, 0x05, 0xce, 0x77, 0xe4, 0x62, 0xa6, 0xb7, - 0xed, 0x3c, 0x4e, 0x33, 0xcf, 0x86, 0x4b, 0x3b, 0x69, 0xff, 0xbf, 0xa2, 0x29, 0xaf, 0x2d, 0xef, - 0x1d, 0xe8, 0xf2, 0xfe, 0x81, 0x2e, 0xff, 0x3a, 0xd0, 0xe5, 0xf7, 0x87, 0xba, 0xb4, 0x7f, 0xa8, - 0x4b, 0xdf, 0x0f, 0x75, 0xe9, 0xe5, 0xdc, 0xa9, 0x9f, 0x35, 0x11, 0x7b, 0xf6, 0x75, 0x73, 0x8a, - 0xec, 0xeb, 0x7d, 0xed, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x2f, 0xe8, 0x90, 0x24, 0x8f, 0x06, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // Send defines a method for sending coins from one account to another account. - Send(ctx context.Context, in *MsgSend, opts ...grpc.CallOption) (*MsgSendResponse, error) - // MultiSend defines a method for sending coins from some accounts to other accounts. - MultiSend(ctx context.Context, in *MsgMultiSend, opts ...grpc.CallOption) (*MsgMultiSendResponse, error) - // UpdateParams defines a governance operation for updating the x/bank module parameters. - // The authority is defined in the keeper. - // - // Since: cosmos-sdk 0.47 - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) - // SetSendEnabled is a governance operation for setting the SendEnabled flag - // on any number of Denoms. Only the entries to add or update should be - // included. Entries that already exist in the store, but that aren't - // included in this message, will be left unchanged. - // - // Since: cosmos-sdk 0.47 - SetSendEnabled(ctx context.Context, in *MsgSetSendEnabled, opts ...grpc.CallOption) (*MsgSetSendEnabledResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Send(ctx context.Context, in *MsgSend, opts ...grpc.CallOption) (*MsgSendResponse, error) { - out := new(MsgSendResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Msg/Send", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) MultiSend(ctx context.Context, in *MsgMultiSend, opts ...grpc.CallOption) (*MsgMultiSendResponse, error) { - out := new(MsgMultiSendResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Msg/MultiSend", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SetSendEnabled(ctx context.Context, in *MsgSetSendEnabled, opts ...grpc.CallOption) (*MsgSetSendEnabledResponse, error) { - out := new(MsgSetSendEnabledResponse) - err := c.cc.Invoke(ctx, "/cosmos.bank.v1beta1.Msg/SetSendEnabled", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Send defines a method for sending coins from one account to another account. - Send(context.Context, *MsgSend) (*MsgSendResponse, error) - // MultiSend defines a method for sending coins from some accounts to other accounts. - MultiSend(context.Context, *MsgMultiSend) (*MsgMultiSendResponse, error) - // UpdateParams defines a governance operation for updating the x/bank module parameters. - // The authority is defined in the keeper. - // - // Since: cosmos-sdk 0.47 - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) - // SetSendEnabled is a governance operation for setting the SendEnabled flag - // on any number of Denoms. Only the entries to add or update should be - // included. Entries that already exist in the store, but that aren't - // included in this message, will be left unchanged. - // - // Since: cosmos-sdk 0.47 - SetSendEnabled(context.Context, *MsgSetSendEnabled) (*MsgSetSendEnabledResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Send not implemented") -} -func (*UnimplementedMsgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MultiSend not implemented") -} -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} -func (*UnimplementedMsgServer) SetSendEnabled(ctx context.Context, req *MsgSetSendEnabled) (*MsgSetSendEnabledResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SetSendEnabled not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Send_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSend) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Send(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Msg/Send", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Send(ctx, req.(*MsgSend)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_MultiSend_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMultiSend) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MultiSend(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Msg/MultiSend", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MultiSend(ctx, req.(*MsgMultiSend)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SetSendEnabled_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSetSendEnabled) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SetSendEnabled(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.bank.v1beta1.Msg/SetSendEnabled", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SetSendEnabled(ctx, req.(*MsgSetSendEnabled)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.bank.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Send", - Handler: _Msg_Send_Handler, - }, - { - MethodName: "MultiSend", - Handler: _Msg_MultiSend_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - { - MethodName: "SetSendEnabled", - Handler: _Msg_SetSendEnabled_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/bank/v1beta1/tx.proto", -} - -func (m *MsgSend) 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 *MsgSend) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSend) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.ToAddress) > 0 { - i -= len(m.ToAddress) - copy(dAtA[i:], m.ToAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.ToAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.FromAddress) > 0 { - i -= len(m.FromAddress) - copy(dAtA[i:], m.FromAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.FromAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSendResponse) 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 *MsgSendResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgMultiSend) 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 *MsgMultiSend) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiSend) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Outputs) > 0 { - for iNdEx := len(m.Outputs) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Outputs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Inputs) > 0 { - for iNdEx := len(m.Inputs) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Inputs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgMultiSendResponse) 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 *MsgMultiSendResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiSendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSetSendEnabled) 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 *MsgSetSendEnabled) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetSendEnabled) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.UseDefaultFor) > 0 { - for iNdEx := len(m.UseDefaultFor) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.UseDefaultFor[iNdEx]) - copy(dAtA[i:], m.UseDefaultFor[iNdEx]) - i = encodeVarintTx(dAtA, i, uint64(len(m.UseDefaultFor[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.SendEnabled) > 0 { - for iNdEx := len(m.SendEnabled) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SendEnabled[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSetSendEnabledResponse) 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 *MsgSetSendEnabledResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetSendEnabledResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgSend) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.FromAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.ToAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgSendResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgMultiSend) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Inputs) > 0 { - for _, e := range m.Inputs { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - if len(m.Outputs) > 0 { - for _, e := range m.Outputs { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgMultiSendResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSetSendEnabled) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.SendEnabled) > 0 { - for _, e := range m.SendEnabled { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - if len(m.UseDefaultFor) > 0 { - for _, s := range m.UseDefaultFor { - l = len(s) - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgSetSendEnabledResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgSend) 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 ErrIntOverflowTx - } - 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: MsgSend: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSend: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.FromAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ToAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSendResponse) 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 ErrIntOverflowTx - } - 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: MsgSendResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSendResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiSend) 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 ErrIntOverflowTx - } - 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: MsgMultiSend: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMultiSend: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Inputs", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Inputs = append(m.Inputs, Input{}) - if err := m.Inputs[len(m.Inputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Outputs", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Outputs = append(m.Outputs, Output{}) - if err := m.Outputs[len(m.Outputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiSendResponse) 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 ErrIntOverflowTx - } - 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: MsgMultiSendResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMultiSendResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParams) 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 ErrIntOverflowTx - } - 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: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParamsResponse) 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 ErrIntOverflowTx - } - 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: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSetSendEnabled) 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 ErrIntOverflowTx - } - 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: MsgSetSendEnabled: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetSendEnabled: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SendEnabled", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SendEnabled = append(m.SendEnabled, &SendEnabled{}) - if err := m.SendEnabled[len(m.SendEnabled)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UseDefaultFor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UseDefaultFor = append(m.UseDefaultFor, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSetSendEnabledResponse) 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 ErrIntOverflowTx - } - 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: MsgSetSendEnabledResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetSendEnabledResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/bank/types/vesting.go b/x/bank/types/vesting.go deleted file mode 100644 index a288d4ec8..000000000 --- a/x/bank/types/vesting.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// VestingAccount defines an interface used for account vesting. -type VestingAccount interface { - // LockedCoins returns the set of coins that are not spendable (i.e. locked), - // defined as the vesting coins that are not delegated. - // - // To get spendable coins of a vesting account, first the total balance must - // be retrieved and the locked tokens can be subtracted from the total balance. - // Note, the spendable balance can be negative. - LockedCoins(blockTime time.Time) sdk.Coins - - // TrackDelegation performs internal vesting accounting necessary when - // delegating from a vesting account. It accepts the current block time, the - // delegation amount and balance of all coins whose denomination exists in - // the account's original vesting balance. - TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) - - // TrackUndelegation performs internal vesting accounting necessary when a - // vesting account performs an undelegation. - TrackUndelegation(amount sdk.Coins) - - GetOriginalVesting() sdk.Coins - GetDelegatedFree() sdk.Coins - GetDelegatedVesting() sdk.Coins -} diff --git a/x/coinswap/keeper/exchange.go b/x/coinswap/keeper/exchange.go index 9d0d0c717..aed03ca0a 100644 --- a/x/coinswap/keeper/exchange.go +++ b/x/coinswap/keeper/exchange.go @@ -3,7 +3,7 @@ package keeper import ( "strings" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/coinswap/types/expected_keepers.go b/x/coinswap/types/expected_keepers.go index 8cb94a8e5..7fcb1c3f3 100644 --- a/x/coinswap/types/expected_keepers.go +++ b/x/coinswap/types/expected_keepers.go @@ -1,7 +1,7 @@ package types import ( - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/distribution/README.md b/x/distribution/README.md deleted file mode 100644 index 1712ef954..000000000 --- a/x/distribution/README.md +++ /dev/null @@ -1,1037 +0,0 @@ ---- -sidebar_position: 1 ---- - -# `x/distribution` - -## Overview - -This _simple_ distribution mechanism describes a functional way to passively -distribute rewards between validators and delegators. Note that this mechanism does -not distribute funds in as precisely as active reward distribution mechanisms and -will therefore be upgraded in the future. - -The mechanism operates as follows. Collected rewards are pooled globally and -divided out passively to validators and delegators. Each validator has the -opportunity to charge commission to the delegators on the rewards collected on -behalf of the delegators. Fees are collected directly into a global reward pool -and validator proposer-reward pool. Due to the nature of passive accounting, -whenever changes to parameters which affect the rate of reward distribution -occurs, withdrawal of rewards must also occur. - -* Whenever withdrawing, one must withdraw the maximum amount they are entitled - to, leaving nothing in the pool. -* Whenever bonding, unbonding, or re-delegating tokens to an existing account, a - full withdrawal of the rewards must occur (as the rules for lazy accounting - change). -* Whenever a validator chooses to change the commission on rewards, all accumulated - commission rewards must be simultaneously withdrawn. - -The above scenarios are covered in `hooks.md`. - -The distribution mechanism outlined herein is used to lazily distribute the -following rewards between validators and associated delegators: - -* multi-token fees to be socially distributed -* inflated staked asset provisions -* validator commission on all rewards earned by their delegators stake - -Fees are pooled within a global pool. The mechanisms used allow for validators -and delegators to independently and lazily withdraw their rewards. - -## Shortcomings - -As a part of the lazy computations, each delegator holds an accumulation term -specific to each validator which is used to estimate what their approximate -fair portion of tokens held in the global fee pool is owed to them. - -```text -entitlement = delegator-accumulation / all-delegators-accumulation -``` - -Under the circumstance that there was constant and equal flow of incoming -reward tokens every block, this distribution mechanism would be equal to the -active distribution (distribute individually to all delegators each block). -However, this is unrealistic so deviations from the active distribution will -occur based on fluctuations of incoming reward tokens as well as timing of -reward withdrawal by other delegators. - -If you happen to know that incoming rewards are about to significantly increase, -you are incentivized to not withdraw until after this event, increasing the -worth of your existing _accum_. See [#2764](https://github.com/cosmos/cosmos-sdk/issues/2764) -for further details. - -## Effect on Staking - -Charging commission on Atom provisions while also allowing for Atom-provisions -to be auto-bonded (distributed directly to the validators bonded stake) is -problematic within BPoS. Fundamentally, these two mechanisms are mutually -exclusive. If both commission and auto-bonding mechanisms are simultaneously -applied to the staking-token then the distribution of staking-tokens between -any validator and its delegators will change with each block. This then -necessitates a calculation for each delegation records for each block - -which is considered computationally expensive. - -In conclusion, we can only have Atom commission and unbonded atoms -provisions or bonded atom provisions with no Atom commission, and we elect to -implement the former. Stakeholders wishing to rebond their provisions may elect -to set up a script to periodically withdraw and rebond rewards. - -## Contents - -* [Concepts](#concepts) -* [State](#state) - * [FeePool](#feepool) - * [Validator Distribution](#validator-distribution) - * [Delegation Distribution](#delegation-distribution) - * [Params](#params) -* [Begin Block](#begin-block) -* [Messages](#messages) -* [Hooks](#hooks) -* [Events](#events) -* [Parameters](#parameters) -* [Client](#client) - * [CLI](#cli) - * [gRPC](#grpc) - -## Concepts - -In Proof of Stake (PoS) blockchains, rewards gained from transaction fees are paid to validators. The fee distribution module fairly distributes the rewards to the validators' constituent delegators. - -Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation. -The rewards for a single validator can then be calculated by taking the total rewards for the period before the delegation started, minus the current total rewards. -To learn more, see the [F1 Fee Distribution paper](/docs/spec/fee_distribution/f1_fee_distr.pdf). - -The commission to the validator is paid when the validator is removed or when the validator requests a withdrawal. -The commission is calculated and incremented at every `BeginBlock` operation to update accumulated fee amounts. - -The rewards to a delegator are distributed when the delegation is changed or removed, or a withdrawal is requested. -Before rewards are distributed, all slashes to the validator that occurred during the current delegation are applied. - -### Reference Counting in F1 Fee Distribution - -In F1 fee distribution, the rewards a delegator receives are calculated when their delegation is withdrawn. This calculation must read the terms of the summation of rewards divided by the share of tokens from the period which they ended when they delegated, and the final period that was created for the withdrawal. - -Additionally, as slashes change the amount of tokens a delegation will have (but we calculate this lazily, -only when a delegator un-delegates), we must calculate rewards in separate periods before / after any slashes -which occurred in between when a delegator delegated and when they withdrew their rewards. Thus slashes, like -delegations, reference the period which was ended by the slash event. - -All stored historical rewards records for periods which are no longer referenced by any delegations -or any slashes can thus be safely removed, as they will never be read (future delegations and future -slashes will always reference future periods). This is implemented by tracking a `ReferenceCount` -along with each historical reward storage entry. Each time a new object (delegation or slash) -is created which might need to reference the historical record, the reference count is incremented. -Each time one object which previously needed to reference the historical record is deleted, the reference -count is decremented. If the reference count hits zero, the historical record is deleted. - -## State - -### FeePool - -All globally tracked parameters for distribution are stored within -`FeePool`. Rewards are collected and added to the reward pool and -distributed to validators/delegators from here. - -Note that the reward pool holds decimal coins (`DecCoins`) to allow -for fractions of coins to be received from operations like inflation. -When coins are distributed from the pool they are truncated back to -`sdk.Coins` which are non-decimal. - -* FeePool: `0x00 -> ProtocolBuffer(FeePool)` - -```go -// coins with decimal -type DecCoins []DecCoin - -type DecCoin struct { - Amount sdk.Dec - Denom string -} -``` - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L116-L123 -``` - -### Validator Distribution - -Validator distribution information for the relevant validator is updated each time: - -1. delegation amount to a validator is updated, -2. any delegator withdraws from a validator, or -3. the validator withdraws its commission. - -* ValidatorDistInfo: `0x02 | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(validatorDistribution)` - -```go -type ValidatorDistInfo struct { - OperatorAddress sdk.AccAddress - SelfBondRewards sdk.DecCoins - ValidatorCommission types.ValidatorAccumulatedCommission -} -``` - -### Delegation Distribution - -Each delegation distribution only needs to record the height at which it last -withdrew fees. Because a delegation must withdraw fees each time it's -properties change (aka bonded tokens etc.) its properties will remain constant -and the delegator's _accumulation_ factor can be calculated passively knowing -only the height of the last withdrawal and its current properties. - -* DelegationDistInfo: `0x02 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(delegatorDist)` - -```go -type DelegationDistInfo struct { - WithdrawalHeight int64 // last time this delegation withdrew rewards -} -``` - -### Params - -The distribution module stores it's params in state with the prefix of `0x09`, -it can be updated with governance or the address with authority. - -* Params: `0x09 | ProtocolBuffer(Params)` - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L12-L42 -``` - -## Begin Block - -At each `BeginBlock`, all fees received in the previous block are transferred to -the distribution `ModuleAccount` account. When a delegator or validator -withdraws their rewards, they are taken out of the `ModuleAccount`. During begin -block, the different claims on the fees collected are updated as follows: - -* The reserve community tax is charged. -* The remainder is distributed proportionally by voting power to all bonded validators - -### The Distribution Scheme - -See [params](#params) for description of parameters. - -Let `fees` be the total fees collected in the previous block, including -inflationary rewards to the stake. All fees are collected in a specific module -account during the block. During `BeginBlock`, they are sent to the -`"distribution"` `ModuleAccount`. No other sending of tokens occurs. Instead, the -rewards each account is entitled to are stored, and withdrawals can be triggered -through the messages `FundCommunityPool`, `WithdrawValidatorCommission` and -`WithdrawDelegatorReward`. - -#### Reward to the Community Pool - -The community pool gets `community_tax * fees`, plus any remaining dust after -validators get their rewards that are always rounded down to the nearest -integer value. - -#### Reward To the Validators - -The proposer receives no extra rewards. All fees are distributed among all the -bonded validators, including the proposer, in proportion to their consensus power. - -```text -powFrac = validator power / total bonded validator power -voteMul = 1 - community_tax -``` - -All validators receive `fees * voteMul * powFrac`. - -#### Rewards to Delegators - -Each validator's rewards are distributed to its delegators. The validator also -has a self-delegation that is treated like a regular delegation in -distribution calculations. - -The validator sets a commission rate. The commission rate is flexible, but each -validator sets a maximum rate and a maximum daily increase. These maximums cannot be exceeded and protect delegators from sudden increases of validator commission rates to prevent validators from taking all of the rewards. - -The outstanding rewards that the operator is entitled to are stored in -`ValidatorAccumulatedCommission`, while the rewards the delegators are entitled -to are stored in `ValidatorCurrentRewards`. The [F1 fee distribution scheme](#concepts) is used to calculate the rewards per delegator as they -withdraw or update their delegation, and is thus not handled in `BeginBlock`. - -#### Example Distribution - -For this example distribution, the underlying consensus engine selects block proposers in -proportion to their power relative to the entire bonded power. - -All validators are equally performant at including pre-commits in their proposed -blocks. Then hold `(pre_commits included) / (total bonded validator power)` -constant so that the amortized block reward for the validator is `( validator power / total bonded power) * (1 - community tax rate)` of -the total rewards. Consequently, the reward for a single delegator is: - -```text -(delegator proportion of the validator power / validator power) * (validator power / total bonded power) - * (1 - community tax rate) * (1 - validator commission rate) -= (delegator proportion of the validator power / total bonded power) * (1 - -community tax rate) * (1 - validator commission rate) -``` - -## Messages - -### MsgSetWithdrawAddress - -By default, the withdraw address is the delegator address. To change its withdraw address, a delegator must send a `MsgSetWithdrawAddress` message. -Changing the withdraw address is possible only if the parameter `WithdrawAddrEnabled` is set to `true`. - -The withdraw address cannot be any of the module accounts. These accounts are blocked from being withdraw addresses by being added to the distribution keeper's `blockedAddrs` array at initialization. - -Response: - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L49-L60 -``` - -```go -func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error - if k.blockedAddrs[withdrawAddr.String()] { - fail with "`{withdrawAddr}` is not allowed to receive external funds" - } - - if !k.GetWithdrawAddrEnabled(ctx) { - fail with `ErrSetWithdrawAddrDisabled` - } - - k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) -``` - -### MsgWithdrawDelegatorReward - -A delegator can withdraw its rewards. -Internally in the distribution module, this transaction simultaneously removes the previous delegation with associated rewards, the same as if the delegator simply started a new delegation of the same value. -The rewards are sent immediately from the distribution `ModuleAccount` to the withdraw address. -Any remainder (truncated decimals) are sent to the community pool. -The starting height of the delegation is set to the current validator period, and the reference count for the previous period is decremented. -The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. - -In the F1 distribution, the total rewards are calculated per validator period, and a delegator receives a piece of those rewards in proportion to their stake in the validator. -In basic F1, the total rewards that all the delegators are entitled to between to periods is calculated the following way. -Let `R(X)` be the total accumulated rewards up to period `X` divided by the tokens staked at that time. The delegator allocation is `R(X) * delegator_stake`. -Then the rewards for all the delegators for staking between periods `A` and `B` are `(R(B) - R(A)) * total stake`. -However, these calculated rewards don't account for slashing. - -Taking the slashes into account requires iteration. -Let `F(X)` be the fraction a validator is to be slashed for a slashing event that happened at period `X`. -If the validator was slashed at periods `P1, ..., PN`, where `A < P1`, `PN < B`, the distribution module calculates the individual delegator's rewards, `T(A, B)`, as follows: - -```go -stake := initial stake -rewards := 0 -previous := A -for P in P1, ..., PN`: - rewards = (R(P) - previous) * stake - stake = stake * F(P) - previous = P -rewards = rewards + (R(B) - R(PN)) * stake -``` - -The historical rewards are calculated retroactively by playing back all the slashes and then attenuating the delegator's stake at each step. -The final calculated stake is equivalent to the actual staked coins in the delegation with a margin of error due to rounding errors. - -Response: - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L66-L77 -``` - -### WithdrawValidatorCommission - -The validator can send the WithdrawValidatorCommission message to withdraw their accumulated commission. -The commission is calculated in every block during `BeginBlock`, so no iteration is required to withdraw. -The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. -Only integer amounts can be sent. If the accumulated awards have decimals, the amount is truncated before the withdrawal is sent, and the remainder is left to be withdrawn later. - -### FundCommunityPool - -This message sends coins directly from the sender to the community pool. - -The transaction fails if the amount cannot be transferred from the sender to the distribution module account. - -```go -func (k Keeper) FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { - return err - } - - feePool := k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) - k.SetFeePool(ctx, feePool) - - return nil -} -``` - -### Common distribution operations - -These operations take place during many different messages. - -#### Initialize delegation - -Each time a delegation is changed, the rewards are withdrawn and the delegation is reinitialized. -Initializing a delegation increments the validator period and keeps track of the starting period of the delegation. - -```go -// initialize starting info for a new delegation -func (k Keeper) initializeDelegation(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) { - // period has already been incremented - we want to store the period ended by this delegation action - previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1 - - // increment reference count for the period we're going to track - k.incrementReferenceCount(ctx, val, previousPeriod) - - validator := k.stakingKeeper.Validator(ctx, val) - delegation := k.stakingKeeper.Delegation(ctx, del, val) - - // calculate delegation stake in tokens - // we don't store directly, so multiply delegation shares * (tokens per share) - // note: necessary to truncate so we don't allow withdrawing more rewards than owed - stake := validator.TokensFromSharesTruncated(delegation.GetShares()) - k.SetDelegatorStartingInfo(ctx, val, del, types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(ctx.BlockHeight()))) -} -``` - -### MsgUpdateParams - -Distribution module params can be updated through `MsgUpdateParams`, which can be done using governance proposal and the signer will always be gov module account address. - -```protobuf reference -https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L133-L147 -``` - -The message handling can fail if: - -* signer is not the gov module account address. - -## Hooks - -Available hooks that can be called by and from this module. - -### Create or modify delegation distribution - -* triggered-by: `staking.MsgDelegate`, `staking.MsgBeginRedelegate`, `staking.MsgUndelegate` - -#### Before - -* The delegation rewards are withdrawn to the withdraw address of the delegator. - The rewards include the current period and exclude the starting period. -* The validator period is incremented. - The validator period is incremented because the validator's power and share distribution might have changed. -* The reference count for the delegator's starting period is decremented. - -#### After - -The starting height of the delegation is set to the previous period. -Because of the `Before`-hook, this period is the last period for which the delegator was rewarded. - -### Validator created - -* triggered-by: `staking.MsgCreateValidator` - -When a validator is created, the following validator variables are initialized: - -* Historical rewards -* Current accumulated rewards -* Accumulated commission -* Total outstanding rewards -* Period - -By default, all values are set to a `0`, except period, which is set to `1`. - -### Validator removed - -* triggered-by: `staking.RemoveValidator` - -Outstanding commission is sent to the validator's self-delegation withdrawal address. -Remaining delegator rewards get sent to the community fee pool. - -Note: The validator gets removed only when it has no remaining delegations. -At that time, all outstanding delegator rewards will have been withdrawn. -Any remaining rewards are dust amounts. - -### Validator is slashed - -* triggered-by: `staking.Slash` -* The current validator period reference count is incremented. - The reference count is incremented because the slash event has created a reference to it. -* The validator period is incremented. -* The slash event is stored for later use. - The slash event will be referenced when calculating delegator rewards. - -## Events - -The distribution module emits the following events: - -### BeginBlocker - -| Type | Attribute Key | Attribute Value | -|-----------------|---------------|--------------------| -| proposer_reward | validator | {validatorAddress} | -| proposer_reward | reward | {proposerReward} | -| commission | amount | {commissionAmount} | -| commission | validator | {validatorAddress} | -| rewards | amount | {rewardAmount} | -| rewards | validator | {validatorAddress} | - -### Handlers - -#### MsgSetWithdrawAddress - -| Type | Attribute Key | Attribute Value | -|----------------------|------------------|----------------------| -| set_withdraw_address | withdraw_address | {withdrawAddress} | -| message | module | distribution | -| message | action | set_withdraw_address | -| message | sender | {senderAddress} | - -#### MsgWithdrawDelegatorReward - -| Type | Attribute Key | Attribute Value | -|---------|---------------|---------------------------| -| withdraw_rewards | amount | {rewardAmount} | -| withdraw_rewards | validator | {validatorAddress} | -| message | module | distribution | -| message | action | withdraw_delegator_reward | -| message | sender | {senderAddress} | - -#### MsgWithdrawValidatorCommission - -| Type | Attribute Key | Attribute Value | -|------------|---------------|-------------------------------| -| withdraw_commission | amount | {commissionAmount} | -| message | module | distribution | -| message | action | withdraw_validator_commission | -| message | sender | {senderAddress} | - -## Parameters - -The distribution module contains the following parameters: - -| Key | Type | Example | -| ------------------- | ------------ | -------------------------- | -| communitytax | string (dec) | "0.020000000000000000" [0] | -| withdrawaddrenabled | bool | true | - -* [0] `communitytax` must be positive and cannot exceed 1.00. -* `baseproposerreward` and `bonusproposerreward` were parameters that are deprecated in v0.47 and are not used. - -## Client - -## CLI - -A user can query and interact with the `distribution` module using the CLI. - -#### Query - -The `query` commands allow users to query `distribution` state. - -```shell -simd query distribution --help -``` - -##### commission - -The `commission` command allows users to query validator commission rewards by address. - -```shell -simd query distribution commission [address] [flags] -``` - -Example: - -```shell -simd query distribution commission cosmosvaloper1... -``` - -Example Output: - -```yml -commission: -- amount: "1000000.000000000000000000" - denom: stake -``` - -##### community-pool - -The `community-pool` command allows users to query all coin balances within the community pool. - -```shell -simd query distribution community-pool [flags] -``` - -Example: - -```shell -simd query distribution community-pool -``` - -Example Output: - -```yml -pool: -- amount: "1000000.000000000000000000" - denom: stake -``` - -##### params - -The `params` command allows users to query the parameters of the `distribution` module. - -```shell -simd query distribution params [flags] -``` - -Example: - -```shell -simd query distribution params -``` - -Example Output: - -```yml -base_proposer_reward: "0.000000000000000000" -bonus_proposer_reward: "0.000000000000000000" -community_tax: "0.020000000000000000" -withdraw_addr_enabled: true -``` - -##### rewards - -The `rewards` command allows users to query delegator rewards. Users can optionally include the validator address to query rewards earned from a specific validator. - -```shell -simd query distribution rewards [delegator-addr] [validator-addr] [flags] -``` - -Example: - -```shell -simd query distribution rewards cosmos1... -``` - -Example Output: - -```yml -rewards: -- reward: - - amount: "1000000.000000000000000000" - denom: stake - validator_address: cosmosvaloper1.. -total: -- amount: "1000000.000000000000000000" - denom: stake -``` - -##### slashes - -The `slashes` command allows users to query all slashes for a given block range. - -```shell -simd query distribution slashes [validator] [start-height] [end-height] [flags] -``` - -Example: - -```shell -simd query distribution slashes cosmosvaloper1... 1 1000 -``` - -Example Output: - -```yml -pagination: - next_key: null - total: "0" -slashes: -- validator_period: 20, - fraction: "0.009999999999999999" -``` - -##### validator-outstanding-rewards - -The `validator-outstanding-rewards` command allows users to query all outstanding (un-withdrawn) rewards for a validator and all their delegations. - -```shell -simd query distribution validator-outstanding-rewards [validator] [flags] -``` - -Example: - -```shell -simd query distribution validator-outstanding-rewards cosmosvaloper1... -``` - -Example Output: - -```yml -rewards: -- amount: "1000000.000000000000000000" - denom: stake -``` - -##### validator-distribution-info - -The `validator-distribution-info` command allows users to query validator commission and self-delegation rewards for validator. - -````shell -simd query distribution validator-distribution-info cosmosvaloper1... -``` - -Example Output: - -```yml -commission: -- amount: "100000.000000000000000000" - denom: stake -operator_address: cosmosvaloper1... -self_bond_rewards: -- amount: "100000.000000000000000000" - denom: stake -``` - -#### Transactions - -The `tx` commands allow users to interact with the `distribution` module. - -```shell -simd tx distribution --help -``` - -##### fund-community-pool - -The `fund-community-pool` command allows users to send funds to the community pool. - -```shell -simd tx distribution fund-community-pool [amount] [flags] -``` - -Example: - -```shell -simd tx distribution fund-community-pool 100stake --from cosmos1... -``` - -##### set-withdraw-addr - -The `set-withdraw-addr` command allows users to set the withdraw address for rewards associated with a delegator address. - -```shell -simd tx distribution set-withdraw-addr [withdraw-addr] [flags] -``` - -Example: - -```shell -simd tx distribution set-withdraw-addr cosmos1... --from cosmos1... -``` - -##### withdraw-all-rewards - -The `withdraw-all-rewards` command allows users to withdraw all rewards for a delegator. - -```shell -simd tx distribution withdraw-all-rewards [flags] -``` - -Example: - -```shell -simd tx distribution withdraw-all-rewards --from cosmos1... -``` - -##### withdraw-rewards - -The `withdraw-rewards` command allows users to withdraw all rewards from a given delegation address, -and optionally withdraw validator commission if the delegation address given is a validator operator and the user proves the `--commission` flag. - -```shell -simd tx distribution withdraw-rewards [validator-addr] [flags] -``` - -Example: - -```shell -simd tx distribution withdraw-rewards cosmosvaloper1... --from cosmos1... --commission -``` - -### gRPC - -A user can query the `distribution` module using gRPC endpoints. - -#### Params - -The `Params` endpoint allows users to query parameters of the `distribution` module. - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/Params -``` - -Example Output: - -```json -{ - "params": { - "communityTax": "20000000000000000", - "baseProposerReward": "00000000000000000", - "bonusProposerReward": "00000000000000000", - "withdrawAddrEnabled": true - } -} -``` - -#### ValidatorDistributionInfo - -The `ValidatorDistributionInfo` queries validator commission and self-delegation rewards for validator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1..."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/ValidatorDistributionInfo -``` - -Example Output: - -```json -{ - "commission": { - "commission": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] - }, - "self_bond_rewards": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ], - "validator_address": "cosmosvalop1..." -} -``` - -#### ValidatorOutstandingRewards - -The `ValidatorOutstandingRewards` endpoint allows users to query rewards of a validator address. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards -``` - -Example Output: - -```json -{ - "rewards": { - "rewards": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] - } -} -``` - -#### ValidatorCommission - -The `ValidatorCommission` endpoint allows users to query accumulated commission for a validator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/ValidatorCommission -``` - -Example Output: - -```json -{ - "commission": { - "commission": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] - } -} -``` - -#### ValidatorSlashes - -The `ValidatorSlashes` endpoint allows users to query slash events of a validator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/ValidatorSlashes -``` - -Example Output: - -```json -{ - "slashes": [ - { - "validator_period": "20", - "fraction": "0.009999999999999999" - } - ], - "pagination": { - "total": "1" - } -} -``` - -#### DelegationRewards - -The `DelegationRewards` endpoint allows users to query the total rewards accrued by a delegation. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1...","validator_address":"cosmosvalop1..."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/DelegationRewards -``` - -Example Output: - -```json -{ - "rewards": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] -} -``` - -#### DelegationTotalRewards - -The `DelegationTotalRewards` endpoint allows users to query the total rewards accrued by each validator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/DelegationTotalRewards -``` - -Example Output: - -```json -{ - "rewards": [ - { - "validatorAddress": "cosmosvaloper1...", - "reward": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] - } - ], - "total": [ - { - "denom": "stake", - "amount": "1000000000000000" - } - ] -} -``` - -#### DelegatorValidators - -The `DelegatorValidators` endpoint allows users to query all validators for given delegator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/DelegatorValidators -``` - -Example Output: - -```json -{ - "validators": ["cosmosvaloper1..."] -} -``` - -#### DelegatorWithdrawAddress - -The `DelegatorWithdrawAddress` endpoint allows users to query the withdraw address of a delegator. - -Example: - -```shell -grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress -``` - -Example Output: - -```json -{ - "withdrawAddress": "cosmos1..." -} -``` - -#### CommunityPool - -The `CommunityPool` endpoint allows users to query the community pool coins. - -Example: - -```shell -grpcurl -plaintext \ - localhost:9090 \ - cosmos.distribution.v1beta1.Query/CommunityPool -``` - -Example Output: - -```json -{ - "pool": [ - { - "denom": "stake", - "amount": "1000000000000000000" - } - ] -} -``` diff --git a/x/distribution/abci.go b/x/distribution/abci.go deleted file mode 100644 index 34a0723e6..000000000 --- a/x/distribution/abci.go +++ /dev/null @@ -1,35 +0,0 @@ -package distribution - -import ( - "time" - - abci "github.com/cometbft/cometbft/abci/types" - - "x/distribution/keeper" - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// BeginBlocker sets the proposer for determining distribution during endblock -// and distribute rewards for the previous block. -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - // determine the total power signing the block - var previousTotalPower int64 - for _, voteInfo := range req.LastCommitInfo.GetVotes() { - previousTotalPower += voteInfo.Validator.Power - } - - // TODO this is Tendermint-dependent - // ref https://github.com/cosmos/cosmos-sdk/issues/3095 - if ctx.BlockHeight() > 1 { - k.AllocateTokens(ctx, previousTotalPower, req.LastCommitInfo.GetVotes()) - } - - // record the proposer for when we payout on the next block - consAddr := sdk.ConsAddress(req.Header.ProposerAddress) - k.SetPreviousProposerConsAddr(ctx, consAddr) -} diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go deleted file mode 100644 index b027f99d2..000000000 --- a/x/distribution/client/cli/query.go +++ /dev/null @@ -1,367 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - distQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the distribution module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - distQueryCmd.AddCommand( - GetCmdQueryParams(), - GetCmdQueryValidatorDistributionInfo(), - GetCmdQueryValidatorOutstandingRewards(), - GetCmdQueryValidatorCommission(), - GetCmdQueryValidatorSlashes(), - GetCmdQueryDelegatorRewards(), - GetCmdQueryCommunityPool(), - ) - - return distQueryCmd -} - -// GetCmdQueryParams implements the query params command. -func GetCmdQueryParams() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Args: cobra.NoArgs, - Short: "Query distribution params", - RunE: func(cmd *cobra.Command, _ []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryValidatorDistributionInfo implements the query validator distribution info command. -func GetCmdQueryValidatorDistributionInfo() *cobra.Command { - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "validator-distribution-info [validator]", - Args: cobra.ExactArgs(1), - Short: "Query validator distribution info", - Long: strings.TrimSpace( - fmt.Sprintf(`Query validator distribution info. -Example: -$ %s query distribution validator-distribution-info %s1lwjmdnks33xwnmfayc64ycprww49n33mtm92ne -`, - version.AppName, bech32PrefixValAddr, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.ValidatorDistributionInfo(cmd.Context(), &types.QueryValidatorDistributionInfoRequest{ - ValidatorAddress: validatorAddr.String(), - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryValidatorOutstandingRewards implements the query validator -// outstanding rewards command. -func GetCmdQueryValidatorOutstandingRewards() *cobra.Command { - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "validator-outstanding-rewards [validator]", - Args: cobra.ExactArgs(1), - Short: "Query distribution outstanding (un-withdrawn) rewards for a validator and all their delegations", - Long: strings.TrimSpace( - fmt.Sprintf(`Query distribution outstanding (un-withdrawn) rewards for a validator and all their delegations. - -Example: -$ %s query distribution validator-outstanding-rewards %s1lwjmdnks33xwnmfayc64ycprww49n33mtm92ne -`, - version.AppName, bech32PrefixValAddr, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.ValidatorOutstandingRewards( - cmd.Context(), - &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: validatorAddr.String()}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Rewards) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryValidatorCommission implements the query validator commission command. -func GetCmdQueryValidatorCommission() *cobra.Command { - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "commission [validator]", - Args: cobra.ExactArgs(1), - Short: "Query distribution validator commission", - Long: strings.TrimSpace( - fmt.Sprintf(`Query validator commission rewards from delegators to that validator. - -Example: -$ %s query distribution commission %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj -`, - version.AppName, bech32PrefixValAddr, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.ValidatorCommission( - cmd.Context(), - &types.QueryValidatorCommissionRequest{ValidatorAddress: validatorAddr.String()}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Commission) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryValidatorSlashes implements the query validator slashes command. -func GetCmdQueryValidatorSlashes() *cobra.Command { - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "slashes [validator] [start-height] [end-height]", - Args: cobra.ExactArgs(3), - Short: "Query distribution validator slashes", - Long: strings.TrimSpace( - fmt.Sprintf(`Query all slashes of a validator for a given block range. - -Example: -$ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 100 -`, - version.AppName, bech32PrefixValAddr, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } - - startHeight, err := strconv.ParseUint(args[1], 10, 64) - if err != nil { - return fmt.Errorf("start-height %s not a valid uint, please input a valid start-height", args[1]) - } - - endHeight, err := strconv.ParseUint(args[2], 10, 64) - if err != nil { - return fmt.Errorf("end-height %s not a valid uint, please input a valid end-height", args[2]) - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - res, err := queryClient.ValidatorSlashes( - cmd.Context(), - &types.QueryValidatorSlashesRequest{ - ValidatorAddress: validatorAddr.String(), - StartingHeight: startHeight, - EndingHeight: endHeight, - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "validator slashes") - return cmd -} - -// GetCmdQueryDelegatorRewards implements the query delegator rewards command. -func GetCmdQueryDelegatorRewards() *cobra.Command { - bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "rewards [delegator-addr] [validator-addr]", - Args: cobra.RangeArgs(1, 2), - Short: "Query all distribution delegator rewards or rewards from a particular validator", - Long: strings.TrimSpace( - fmt.Sprintf(`Query all rewards earned by a delegator, optionally restrict to rewards from a single validator. - -Example: -$ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p -$ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj -`, - version.AppName, bech32PrefixAccAddr, version.AppName, bech32PrefixAccAddr, bech32PrefixValAddr, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - // query for rewards from a particular delegation - ctx := cmd.Context() - if len(args) == 2 { - validatorAddr, err := sdk.ValAddressFromBech32(args[1]) - if err != nil { - return err - } - - res, err := queryClient.DelegationRewards( - ctx, - &types.QueryDelegationRewardsRequest{DelegatorAddress: delegatorAddr.String(), ValidatorAddress: validatorAddr.String()}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - } - - res, err := queryClient.DelegationTotalRewards( - ctx, - &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: delegatorAddr.String()}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryCommunityPool returns the command for fetching community pool info. -func GetCmdQueryCommunityPool() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool", - Args: cobra.NoArgs, - Short: "Query the amount of coins in the community pool", - Long: strings.TrimSpace( - fmt.Sprintf(`Query all coins in the community pool which is under Governance control. - -Example: -$ %s query distribution community-pool -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.CommunityPool(cmd.Context(), &types.QueryCommunityPoolRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} diff --git a/x/distribution/client/cli/suite_test.go b/x/distribution/client/cli/suite_test.go index a5d1f6f8f..7f4657b94 100644 --- a/x/distribution/client/cli/suite_test.go +++ b/x/distribution/client/cli/suite_test.go @@ -12,9 +12,10 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" - "x/distribution/client/cli" - distrclitestutil "x/distribution/client/testutil" - distrtestutil "x/distribution/testutil" + distrclitestutil "github.com/cosmos/cosmos-sdk/x/distribution/client/testutil" + distrtestutil "github.com/cosmos/cosmos-sdk/x/distribution/testutil" + + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go deleted file mode 100644 index 2a7830146..000000000 --- a/x/distribution/client/cli/tx.go +++ /dev/null @@ -1,257 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/pflag" - - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" -) - -// Transaction flags for the x/distribution module -var ( - FlagCommission = "commission" - FlagMaxMessagesPerTx = "max-msgs" -) - -const ( - MaxMessagesPerTxDefault = 0 -) - -// NewTxCmd returns a root CLI command handler for all x/distribution transaction commands. -func NewTxCmd() *cobra.Command { - distTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Distribution transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - distTxCmd.AddCommand( - NewWithdrawRewardsCmd(), - NewWithdrawAllRewardsCmd(), - NewSetWithdrawAddrCmd(), - NewFundCommunityPoolCmd(), - ) - - return distTxCmd -} - -type newGenerateOrBroadcastFunc func(client.Context, *pflag.FlagSet, ...sdk.Msg) error - -func newSplitAndApply( - genOrBroadcastFn newGenerateOrBroadcastFunc, clientCtx client.Context, - fs *pflag.FlagSet, msgs []sdk.Msg, chunkSize int, -) error { - if chunkSize == 0 { - return genOrBroadcastFn(clientCtx, fs, msgs...) - } - - // split messages into slices of length chunkSize - totalMessages := len(msgs) - for i := 0; i < len(msgs); i += chunkSize { - - sliceEnd := i + chunkSize - if sliceEnd > totalMessages { - sliceEnd = totalMessages - } - - msgChunk := msgs[i:sliceEnd] - if err := genOrBroadcastFn(clientCtx, fs, msgChunk...); err != nil { - return err - } - } - - return nil -} - -// NewWithdrawRewardsCmd returns a CLI command handler for creating a MsgWithdrawDelegatorReward transaction. -func NewWithdrawRewardsCmd() *cobra.Command { - bech32PrefixValAddr := sdk.GetConfig().GetBech32ValidatorAddrPrefix() - - cmd := &cobra.Command{ - Use: "withdraw-rewards [validator-addr]", - Short: "Withdraw rewards from a given delegation address, and optionally withdraw validator commission if the delegation address given is a validator operator", - Long: strings.TrimSpace( - fmt.Sprintf(`Withdraw rewards from a given delegation address, -and optionally withdraw validator commission if the delegation address given is a validator operator. - -Example: -$ %s tx distribution withdraw-rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey -$ %s tx distribution withdraw-rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --commission -`, - version.AppName, bech32PrefixValAddr, version.AppName, bech32PrefixValAddr, - ), - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - delAddr := clientCtx.GetFromAddress() - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } - - msgs := []sdk.Msg{types.NewMsgWithdrawDelegatorReward(delAddr, valAddr)} - - if commission, _ := cmd.Flags().GetBool(FlagCommission); commission { - msgs = append(msgs, types.NewMsgWithdrawValidatorCommission(valAddr)) - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msgs...) - }, - } - - cmd.Flags().Bool(FlagCommission, false, "Withdraw the validator's commission in addition to the rewards") - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -// NewWithdrawAllRewardsCmd returns a CLI command handler for creating a MsgWithdrawDelegatorReward transaction. -func NewWithdrawAllRewardsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "withdraw-all-rewards", - Short: "withdraw all delegations rewards for a delegator", - Long: strings.TrimSpace( - fmt.Sprintf(`Withdraw all rewards for a single delegator. -Note that if you use this command with --%[2]s=%[3]s or --%[2]s=%[4]s, the %[5]s flag will automatically be set to 0. - -Example: -$ %[1]s tx distribution withdraw-all-rewards --from mykey -`, - version.AppName, flags.FlagBroadcastMode, flags.BroadcastSync, flags.BroadcastAsync, FlagMaxMessagesPerTx, - ), - ), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, _ []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - delAddr := clientCtx.GetFromAddress() - - // The transaction cannot be generated offline since it requires a query - // to get all the validators. - if clientCtx.Offline { - return fmt.Errorf("cannot generate tx in offline mode") - } - - queryClient := types.NewQueryClient(clientCtx) - delValsRes, err := queryClient.DelegatorValidators(cmd.Context(), &types.QueryDelegatorValidatorsRequest{DelegatorAddress: delAddr.String()}) - if err != nil { - return err - } - - validators := delValsRes.Validators - // build multi-message transaction - msgs := make([]sdk.Msg, 0, len(validators)) - for _, valAddr := range validators { - val, err := sdk.ValAddressFromBech32(valAddr) - if err != nil { - return err - } - - msg := types.NewMsgWithdrawDelegatorReward(delAddr, val) - msgs = append(msgs, msg) - } - - chunkSize, _ := cmd.Flags().GetInt(FlagMaxMessagesPerTx) - - return newSplitAndApply(tx.GenerateOrBroadcastTxCLI, clientCtx, cmd.Flags(), msgs, chunkSize) - }, - } - - cmd.Flags().Int(FlagMaxMessagesPerTx, MaxMessagesPerTxDefault, "Limit the number of messages per tx (0 for unlimited)") - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -// NewSetWithdrawAddrCmd returns a CLI command handler for creating a MsgSetWithdrawAddress transaction. -func NewSetWithdrawAddrCmd() *cobra.Command { - bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() - - cmd := &cobra.Command{ - Use: "set-withdraw-addr [withdraw-addr]", - Short: "change the default withdraw address for rewards associated with an address", - Long: strings.TrimSpace( - fmt.Sprintf(`Set the withdraw address for rewards associated with a delegator address. - -Example: -$ %s tx distribution set-withdraw-addr %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from mykey -`, - version.AppName, bech32PrefixAccAddr, - ), - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - delAddr := clientCtx.GetFromAddress() - withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgSetWithdrawAddress(delAddr, withdrawAddr) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -// NewFundCommunityPoolCmd returns a CLI command handler for creating a MsgFundCommunityPool transaction. -func NewFundCommunityPoolCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "fund-community-pool [amount]", - Args: cobra.ExactArgs(1), - Short: "Funds the community pool with the specified amount", - Long: strings.TrimSpace( - fmt.Sprintf(`Funds the community pool with the specified amount - -Example: -$ %s tx distribution fund-community-pool 100uatom --from mykey -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - depositorAddr := clientCtx.GetFromAddress() - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgFundCommunityPool(amount, depositorAddr) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go deleted file mode 100644 index 0c1ea11ff..000000000 --- a/x/distribution/client/cli/tx_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package cli - -import ( - "testing" - - "github.com/spf13/pflag" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func Test_splitAndCall_NoMessages(t *testing.T) { - clientCtx := client.Context{} - - err := newSplitAndApply(nil, clientCtx, nil, nil, 10) - require.NoError(t, err, "") -} - -func Test_splitAndCall_Splitting(t *testing.T) { - clientCtx := client.Context{} - - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - - // Add five messages - msgs := []sdk.Msg{ - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - testdata.NewTestMsg(addr), - } - - // Keep track of number of calls - const chunkSize = 2 - - callCount := 0 - err := newSplitAndApply( - func(clientCtx client.Context, fs *pflag.FlagSet, msgs ...sdk.Msg) error { - callCount++ - - require.NotNil(t, clientCtx) - require.NotNil(t, msgs) - - if callCount < 3 { - require.Equal(t, len(msgs), 2) - } else { - require.Equal(t, len(msgs), 1) - } - - return nil - }, - clientCtx, nil, msgs, chunkSize) - - require.NoError(t, err, "") - require.Equal(t, 3, callCount) -} diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go deleted file mode 100644 index 6217799d9..000000000 --- a/x/distribution/client/common/common.go +++ /dev/null @@ -1,33 +0,0 @@ -package common - -import ( - "fmt" - - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// QueryDelegationRewards queries a delegation rewards between a delegator and a -// validator. -func QueryDelegationRewards(clientCtx client.Context, delAddr, valAddr string) ([]byte, int64, error) { - delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) - if err != nil { - return nil, 0, err - } - - validatorAddr, err := sdk.ValAddressFromBech32(valAddr) - if err != nil { - return nil, 0, err - } - - params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) - bz, err := clientCtx.LegacyAmino.MarshalJSON(params) - if err != nil { - return nil, 0, fmt.Errorf("failed to marshal params: %w", err) - } - - route := fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryDelegationRewards) - return clientCtx.QueryWithData(route, bz) -} diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go deleted file mode 100644 index ff9bb88d1..000000000 --- a/x/distribution/client/common/common_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package common - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec/legacy" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client" -) - -func TestQueryDelegationRewardsAddrValidation(t *testing.T) { - clientCtx := client.Context{}.WithLegacyAmino(legacy.Cdc) - - type args struct { - delAddr string - valAddr string - } - - tests := []struct { - name string - args args - want []byte - wantErr bool - }{ - {"invalid delegator address", args{"invalid", ""}, nil, true}, - {"empty delegator address", args{"", ""}, nil, true}, - {"invalid validator address", args{"cosmos1zxcsu7l5qxs53lvp0fqgd09a9r2g6kqrk2cdpa", "invalid"}, nil, true}, - {"empty validator address", args{"cosmos1zxcsu7l5qxs53lvp0fqgd09a9r2g6kqrk2cdpa", ""}, nil, true}, - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - _, _, err := QueryDelegationRewards(clientCtx, tt.args.delAddr, tt.args.valAddr) - require.True(t, err != nil, tt.wantErr) - }) - } -} diff --git a/x/distribution/client/testutil/helpers.go b/x/distribution/client/testutil/helpers.go index 5c8f491c6..138738e8d 100644 --- a/x/distribution/client/testutil/helpers.go +++ b/x/distribution/client/testutil/helpers.go @@ -5,7 +5,7 @@ import ( "context" "fmt" - distrcli "x/distribution/client/cli" + distrcli "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/client" ) diff --git a/x/distribution/doc.go b/x/distribution/doc.go deleted file mode 100644 index 8b9966c05..000000000 --- a/x/distribution/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -/* -Package distribution implements a Cosmos SDK module, that provides an implementation -of the F1 fee distribution algorithm. It handles reward tracking, allocation, and -distribution. Please refer to the specification under /spec for further information. -*/ -package distribution diff --git a/x/distribution/exported/exported.go b/x/distribution/exported/exported.go deleted file mode 100644 index 000114e61..000000000 --- a/x/distribution/exported/exported.go +++ /dev/null @@ -1,18 +0,0 @@ -package exported - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -type ( - ParamSet = paramtypes.ParamSet - - // Subspace defines an interface that implements the legacy x/params Subspace - // type. - // - // NOTE: This is used solely for migration of x/params managed parameters. - Subspace interface { - GetParamSet(ctx sdk.Context, ps ParamSet) - } -) diff --git a/x/distribution/keeper/alias_functions.go b/x/distribution/keeper/alias_functions.go deleted file mode 100644 index 17ba1751b..000000000 --- a/x/distribution/keeper/alias_functions.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper - -import ( - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// get outstanding rewards -func (k Keeper) GetValidatorOutstandingRewardsCoins(ctx sdk.Context, val sdk.ValAddress) sdk.DecCoins { - return k.GetValidatorOutstandingRewards(ctx, val).Rewards -} - -// get the community coins -func (k Keeper) GetFeePoolCommunityCoins(ctx sdk.Context) sdk.DecCoins { - return k.GetFeePool(ctx).CommunityPool -} - -// GetDistributionAccount returns the distribution ModuleAccount -func (k Keeper) GetDistributionAccount(ctx sdk.Context) authtypes.ModuleAccountI { - return k.authKeeper.GetModuleAccount(ctx, types.ModuleName) -} diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go deleted file mode 100644 index ea9caab91..000000000 --- a/x/distribution/keeper/allocation.go +++ /dev/null @@ -1,103 +0,0 @@ -package keeper - -import ( - "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// AllocateTokens performs reward and fee distribution to all validators based -// on the F1 fee distribution specification. -func (k Keeper) AllocateTokens(ctx sdk.Context, totalPreviousPower int64, bondedVotes []abci.VoteInfo) { - // fetch and clear the collected fees for distribution, since this is - // called in BeginBlock, collected fees will be from the previous block - // (and distributed to the previous proposer) - feeCollector := k.authKeeper.GetModuleAccount(ctx, k.feeCollectorName) - feesCollectedInt := k.bankKeeper.GetAllBalances(ctx, feeCollector.GetAddress()) - feesCollected := sdk.NewDecCoinsFromCoins(feesCollectedInt...) - - // transfer collected fees to the distribution module account - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, k.feeCollectorName, types.ModuleName, feesCollectedInt) - if err != nil { - panic(err) - } - - // temporary workaround to keep CanWithdrawInvariant happy - // general discussions here: https://github.com/cosmos/cosmos-sdk/issues/2906#issuecomment-441867634 - feePool := k.GetFeePool(ctx) - if totalPreviousPower == 0 { - feePool.CommunityPool = feePool.CommunityPool.Add(feesCollected...) - k.SetFeePool(ctx, feePool) - return - } - - // calculate fraction allocated to validators - remaining := feesCollected - communityTax := k.GetCommunityTax(ctx) - voteMultiplier := math.LegacyOneDec().Sub(communityTax) - feeMultiplier := feesCollected.MulDecTruncate(voteMultiplier) - - // allocate tokens proportionally to voting power - // - // TODO: Consider parallelizing later - // - // Ref: https://github.com/cosmos/cosmos-sdk/pull/3099#discussion_r246276376 - for _, vote := range bondedVotes { - validator := k.stakingKeeper.ValidatorByConsAddr(ctx, vote.Validator.Address) - - // TODO: Consider micro-slashing for missing votes. - // - // Ref: https://github.com/cosmos/cosmos-sdk/issues/2525#issuecomment-430838701 - powerFraction := math.LegacyNewDec(vote.Validator.Power).QuoTruncate(math.LegacyNewDec(totalPreviousPower)) - reward := feeMultiplier.MulDecTruncate(powerFraction) - - k.AllocateTokensToValidator(ctx, validator, reward) - remaining = remaining.Sub(reward) - } - - // allocate community funding - feePool.CommunityPool = feePool.CommunityPool.Add(remaining...) - k.SetFeePool(ctx, feePool) -} - -// AllocateTokensToValidator allocate tokens to a particular validator, -// splitting according to commission. -func (k Keeper) AllocateTokensToValidator(ctx sdk.Context, val stakingtypes.ValidatorI, tokens sdk.DecCoins) { - // split tokens between validator and delegators according to commission - commission := tokens.MulDec(val.GetCommission()) - shared := tokens.Sub(commission) - - // update current commission - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCommission, - sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()), - ), - ) - currentCommission := k.GetValidatorAccumulatedCommission(ctx, val.GetOperator()) - currentCommission.Commission = currentCommission.Commission.Add(commission...) - k.SetValidatorAccumulatedCommission(ctx, val.GetOperator(), currentCommission) - - // update current rewards - currentRewards := k.GetValidatorCurrentRewards(ctx, val.GetOperator()) - currentRewards.Rewards = currentRewards.Rewards.Add(shared...) - k.SetValidatorCurrentRewards(ctx, val.GetOperator(), currentRewards) - - // update outstanding rewards - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRewards, - sdk.NewAttribute(sdk.AttributeKeyAmount, tokens.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()), - ), - ) - - outstanding := k.GetValidatorOutstandingRewards(ctx, val.GetOperator()) - outstanding.Rewards = outstanding.Rewards.Add(tokens...) - k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), outstanding) -} diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go deleted file mode 100644 index c6c036fcb..000000000 --- a/x/distribution/keeper/allocation_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - "x/distribution" - "x/distribution/keeper" - distrtestutil "x/distribution/testutil" - disttypes "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestAllocateTokensToValidatorWithCommission(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // create validator with 50% commission - val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val).AnyTimes() - - // allocate tokens - tokens := sdk.DecCoins{ - {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(10)}, - } - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // check commission - expected := sdk.DecCoins{ - {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(5)}, - } - require.Equal(t, expected, distrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission) - - // check current rewards - require.Equal(t, expected, distrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards) -} - -func TestAllocateTokensToManyValidators(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - feeCollectorAcc := authtypes.NewEmptyModuleAccount("fee_collector") - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool & set params - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - - // create validator with 50% commission - valAddr0 := sdk.ValAddress(valConsAddr0) - val0, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - val0.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val0).AnyTimes() - - // create second validator with 0% commission - valAddr1 := sdk.ValAddress(valConsAddr1) - val1, err := distrtestutil.CreateValidator(valConsPk1, math.NewInt(100)) - require.NoError(t, err) - val1.Commission = stakingtypes.NewCommission(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk1)).Return(val1).AnyTimes() - - abciValA := abci.Validator{ - Address: valConsPk0.Address(), - Power: 100, - } - abciValB := abci.Validator{ - Address: valConsPk1.Address(), - Power: 100, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards.IsZero()) - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards.IsZero()) - require.True(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr0).Commission.IsZero()) - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr1).Commission.IsZero()) - require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr0).Rewards.IsZero()) - require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - bankKeeper.EXPECT().GetAllBalances(gomock.Any(), feeCollectorAcc.GetAddress()).Return(fees) - bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), "fee_collector", disttypes.ModuleName, fees) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - } - distrKeeper.AllocateTokens(ctx, 200, votes) - - // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards) - - // 2 community pool coins - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(2)}}, distrKeeper.GetFeePool(ctx).CommunityPool) - - // 50% commission for first proposer, (0.5 * 98%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr0).Commission) - - // zero commission for second proposer - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr1).Commission.IsZero()) - - // just staking.proportional for first proposer less commission = (0.5 * 98%) * 100 / 2 = 24.50 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2450, 2)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr0).Rewards) - - // proposer reward + staking.proportional for second proposer = (0.5 * (98%)) * 100 = 49 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(490, 1)}}, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards) -} - -func TestAllocateTokensTruncation(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - feeCollectorAcc := authtypes.NewEmptyModuleAccount("fee_collector") - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 10% commission - valAddr0 := sdk.ValAddress(valConsAddr0) - val0, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - val0.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk0)).Return(val0).AnyTimes() - - // create second validator with 10% commission - valAddr1 := sdk.ValAddress(valConsAddr1) - val1, err := distrtestutil.CreateValidator(valConsPk1, math.NewInt(100)) - require.NoError(t, err) - val1.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk1)).Return(val1).AnyTimes() - - // create third validator with 10% commission - valAddr2 := sdk.ValAddress(valConsAddr2) - val2, err := stakingtypes.NewValidator(sdk.ValAddress(valConsAddr2), valConsPk1, stakingtypes.Description{}) - require.NoError(t, err) - val2.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), math.LegacyNewDec(0)) - stakingKeeper.EXPECT().ValidatorByConsAddr(gomock.Any(), sdk.GetConsAddress(valConsPk2)).Return(val2).AnyTimes() - - abciValA := abci.Validator{ - Address: valConsPk0.Address(), - Power: 11, - } - abciValB := abci.Validator{ - Address: valConsPk1.Address(), - Power: 10, - } - abciValC := abci.Validator{ - Address: valConsPk2.Address(), - Power: 10, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards.IsZero()) - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards.IsZero()) - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards.IsZero()) - require.True(t, distrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr0).Commission.IsZero()) - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr1).Commission.IsZero()) - require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr0).Rewards.IsZero()) - require.True(t, distrKeeper.GetValidatorCurrentRewards(ctx, valAddr1).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) - bankKeeper.EXPECT().GetAllBalances(gomock.Any(), feeCollectorAcc.GetAddress()).Return(fees) - bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), "fee_collector", disttypes.ModuleName, fees) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - { - Validator: abciValC, - SignedLastBlock: true, - }, - } - distrKeeper.AllocateTokens(ctx, 31, votes) - - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr0).Rewards.IsValid()) - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr1).Rewards.IsValid()) - require.True(t, distrKeeper.GetValidatorOutstandingRewards(ctx, valAddr2).Rewards.IsValid()) -} diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go deleted file mode 100644 index a99c150d2..000000000 --- a/x/distribution/keeper/common_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper_test - -import ( - "x/distribution/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var ( - PKS = simtestutil.CreateTestPubKeys(5) - - valConsPk0 = PKS[0] - valConsPk1 = PKS[1] - valConsPk2 = PKS[2] - - valConsAddr0 = sdk.ConsAddress(valConsPk0.Address()) - valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) - valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) - - distrAcc = authtypes.NewEmptyModuleAccount(types.ModuleName) -) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go deleted file mode 100644 index a015c45fc..000000000 --- a/x/distribution/keeper/delegation.go +++ /dev/null @@ -1,215 +0,0 @@ -package keeper - -import ( - "fmt" - - "cosmossdk.io/math" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// initialize starting info for a new delegation -func (k Keeper) initializeDelegation(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) { - // period has already been incremented - we want to store the period ended by this delegation action - previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1 - - // increment reference count for the period we're going to track - k.incrementReferenceCount(ctx, val, previousPeriod) - - validator := k.stakingKeeper.Validator(ctx, val) - delegation := k.stakingKeeper.Delegation(ctx, del, val) - - // calculate delegation stake in tokens - // we don't store directly, so multiply delegation shares * (tokens per share) - // note: necessary to truncate so we don't allow withdrawing more rewards than owed - stake := validator.TokensFromSharesTruncated(delegation.GetShares()) - k.SetDelegatorStartingInfo(ctx, val, del, types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(ctx.BlockHeight()))) -} - -// calculate the rewards accrued by a delegation between two periods -func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val stakingtypes.ValidatorI, - startingPeriod, endingPeriod uint64, stake sdk.Dec, -) (rewards sdk.DecCoins) { - // sanity check - if startingPeriod > endingPeriod { - panic("startingPeriod cannot be greater than endingPeriod") - } - - // sanity check - if stake.IsNegative() { - panic("stake should not be negative") - } - - // return staking * (ending - starting) - starting := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), startingPeriod) - ending := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), endingPeriod) - difference := ending.CumulativeRewardRatio.Sub(starting.CumulativeRewardRatio) - if difference.IsAnyNegative() { - panic("negative rewards should not be possible") - } - // note: necessary to truncate so we don't allow withdrawing more rewards than owed - rewards = difference.MulDecTruncate(stake) - return -} - -// calculate the total rewards accrued by a delegation -func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins) { - // fetch starting info for delegation - startingInfo := k.GetDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) - - if startingInfo.Height == uint64(ctx.BlockHeight()) { - // started this height, no rewards yet - return - } - - startingPeriod := startingInfo.PreviousPeriod - stake := startingInfo.Stake - - // Iterate through slashes and withdraw with calculated staking for - // distribution periods. These period offsets are dependent on *when* slashes - // happen - namely, in BeginBlock, after rewards are allocated... - // Slashes which happened in the first block would have been before this - // delegation existed, UNLESS they were slashes of a redelegation to this - // validator which was itself slashed (from a fault committed by the - // redelegation source validator) earlier in the same BeginBlock. - startingHeight := startingInfo.Height - // Slashes this block happened after reward allocation, but we have to account - // for them for the stake sanity check below. - endingHeight := uint64(ctx.BlockHeight()) - if endingHeight > startingHeight { - k.IterateValidatorSlashEventsBetween(ctx, del.GetValidatorAddr(), startingHeight, endingHeight, - func(height uint64, event types.ValidatorSlashEvent) (stop bool) { - endingPeriod := event.ValidatorPeriod - if endingPeriod > startingPeriod { - rewards = rewards.Add(k.calculateDelegationRewardsBetween(ctx, val, startingPeriod, endingPeriod, stake)...) - - // Note: It is necessary to truncate so we don't allow withdrawing - // more rewards than owed. - stake = stake.MulTruncate(math.LegacyOneDec().Sub(event.Fraction)) - startingPeriod = endingPeriod - } - return false - }, - ) - } - - // A total stake sanity check; Recalculated final stake should be less than or - // equal to current stake here. We cannot use Equals because stake is truncated - // when multiplied by slash fractions (see above). We could only use equals if - // we had arbitrary-precision rationals. - currentStake := val.TokensFromShares(del.GetShares()) - - if stake.GT(currentStake) { - // AccountI for rounding inconsistencies between: - // - // currentStake: calculated as in staking with a single computation - // stake: calculated as an accumulation of stake - // calculations across validator's distribution periods - // - // These inconsistencies are due to differing order of operations which - // will inevitably have different accumulated rounding and may lead to - // the smallest decimal place being one greater in stake than - // currentStake. When we calculated slashing by period, even if we - // round down for each slash fraction, it's possible due to how much is - // being rounded that we slash less when slashing by period instead of - // for when we slash without periods. In other words, the single slash, - // and the slashing by period could both be rounding down but the - // slashing by period is simply rounding down less, thus making stake > - // currentStake - // - // A small amount of this error is tolerated and corrected for, - // however any greater amount should be considered a breach in expected - // behaviour. - marginOfErr := sdk.SmallestDec().MulInt64(3) - if stake.LTE(currentStake.Add(marginOfErr)) { - stake = currentStake - } else { - panic(fmt.Sprintf("calculated final stake for delegator %s greater than current stake"+ - "\n\tfinal stake:\t%s"+ - "\n\tcurrent stake:\t%s", - del.GetDelegatorAddr(), stake, currentStake)) - } - } - - // calculate rewards for final period - rewards = rewards.Add(k.calculateDelegationRewardsBetween(ctx, val, startingPeriod, endingPeriod, stake)...) - return rewards -} - -func (k Keeper) withdrawDelegationRewards(ctx sdk.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI) (sdk.Coins, error) { - // check existence of delegator starting info - if !k.HasDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) { - return nil, types.ErrEmptyDelegationDistInfo - } - - // end current period and calculate rewards - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewardsRaw := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - outstanding := k.GetValidatorOutstandingRewardsCoins(ctx, del.GetValidatorAddr()) - - // defensive edge case may happen on the very final digits - // of the decCoins due to operation order of the distribution mechanism. - rewards := rewardsRaw.Intersect(outstanding) - if !rewards.IsEqual(rewardsRaw) { - logger := k.Logger(ctx) - logger.Info( - "rounding error withdrawing rewards from validator", - "delegator", del.GetDelegatorAddr().String(), - "validator", val.GetOperator().String(), - "got", rewards.String(), - "expected", rewardsRaw.String(), - ) - } - - // truncate reward dec coins, return remainder to community pool - finalRewards, remainder := rewards.TruncateDecimal() - - // add coins to user account - if !finalRewards.IsZero() { - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, del.GetDelegatorAddr()) - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, finalRewards) - if err != nil { - return nil, err - } - } - - // update the outstanding rewards and the community pool only if the - // transaction was successful - k.SetValidatorOutstandingRewards(ctx, del.GetValidatorAddr(), types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(rewards)}) - feePool := k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(remainder...) - k.SetFeePool(ctx, feePool) - - // decrement reference count of starting period - startingInfo := k.GetDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) - startingPeriod := startingInfo.PreviousPeriod - k.decrementReferenceCount(ctx, del.GetValidatorAddr(), startingPeriod) - - // remove delegator starting info - k.DeleteDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) - - if finalRewards.IsZero() { - baseDenom, _ := sdk.GetBaseDenom() - if baseDenom == "" { - baseDenom = sdk.DefaultBondDenom - } - - // Note, we do not call the NewCoins constructor as we do not want the zero - // coin removed. - finalRewards = sdk.Coins{sdk.NewCoin(baseDenom, math.ZeroInt())} - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeWithdrawRewards, - sdk.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()), - sdk.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr().String()), - ), - ) - - return finalRewards, nil -} diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go deleted file mode 100644 index 360c4864d..000000000 --- a/x/distribution/keeper/delegation_test.go +++ /dev/null @@ -1,977 +0,0 @@ -package keeper_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - "cosmossdk.io/math" - - "x/distribution" - "x/distribution/keeper" - distrtestutil "x/distribution/testutil" - disttypes "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func TestCalculateRewardsBasic(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(1000)) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // delegation mock - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(3) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // historical count should be 2 (once for validator init, once for delegation init) - require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // historical count should be 2 still - require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // allocate some rewards - initial := int64(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestCalculateRewardsAfterSlash(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - valPower := int64(100) - stake := sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction) - val, err := distrtestutil.CreateValidator(valConsPk0, stake) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - - // set mock calls - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(4) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% (simulated with manual calls; we assume the validator is bonded) - slashedTokens := distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial.QuoRaw(2))}}, - distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestCalculateRewardsAfterManySlashes(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - valPower := int64(100) - stake := sdk.TokensFromConsensusPower(valPower, sdk.DefaultPowerReduction) - val, err := distrtestutil.CreateValidator(valConsPk0, stake) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // delegation mocks - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(4) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% (simulated with manual calls; we assume the validator is bonded) - slashedTokens := distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) - - // expect a call for the next slash with the updated validator - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% again - slashedTokens = distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower/2, - sdk.NewDecWithPrec(2, 1), - &val, - &distrKeeper, - ) - require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromInt(initial)}}, - distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestCalculateRewardsMultiDelegator(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr0 := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - del0 := stakingtypes.NewDelegation(addr0, valAddr, val.DelegatorShares) - - // set mock calls - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(4) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr0, valAddr).Return(del0).Times(1) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr0, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // second delegation - addr1 := sdk.AccAddress(valConsAddr1) - _, del1, err := distrtestutil.Delegate(ctx, distrKeeper, addr1, &val, sdk.NewInt(100), nil) - require.NoError(t, err) - - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr1, valAddr).Return(del1) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(1) - - // call necessary hooks to update a delegation - err = distrKeeper.Hooks().AfterDelegationModified(ctx, addr1, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del0, endingPeriod) - - // rewards for del0 should be 3/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial * 3 / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial * 1 / 4)}}, rewards) - - // commission should be equal to initial (50% twice) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestWithdrawDelegationRewardsBasic(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // delegation mock - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(5) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del).Times(3) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} - - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (initial + latest for delegation) - require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // withdraw rewards (the bank keeper should be called with the right amount of tokens to transfer) - expRewards := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, initial.QuoRaw(2))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expRewards) - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddr), valAddr) - require.Nil(t, err) - - // historical count should still be 2 (added one record, cleared one) - require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // withdraw commission (the bank keeper should be called with the right amount of tokens to transfer) - expCommission := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, initial.QuoRaw(2))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expCommission) - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddr) - require.Nil(t, err) -} - -func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, math.NewInt(100)) - require.NoError(t, err) - - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // delegation mock - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(5) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - valPower := int64(100) - // slash the validator by 50% (simulated with manual calls; we assume the validator is bonded) - distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - - // slash the validator by 50% again - // stakingKeeper.Slash(ctx, valConsAddr0, ctx.BlockHeight(), valPower/2, sdk.NewDecWithPrec(5, 1)) - distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower/2, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - valPower := int64(100) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.TokensFromConsensusPower(valPower, sdk.DefaultPowerReduction)) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // validator and delegation mocks - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(3) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(2) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - initial := sdk.NewDecFromInt(sdk.TokensFromConsensusPower(30, sdk.DefaultPowerReduction)) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // update validator mock - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(1) - - // second delegation - _, del2, err := distrtestutil.Delegate( - ctx, - distrKeeper, - sdk.AccAddress(valConsAddr1), - &val, - sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), - nil, - ) - require.NoError(t, err) - - // new delegation mock and update validator mock - stakingKeeper.EXPECT().Delegation(gomock.Any(), sdk.AccAddress(valConsAddr1), valAddr).Return(del2) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(1) - - // call necessary hooks to update a delegation - err = distrKeeper.Hooks().AfterDelegationModified(ctx, sdk.AccAddress(valConsAddr1), valAddr) - require.NoError(t, err) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator again - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - distrtestutil.SlashValidator( - ctx, - valConsAddr0, - ctx.BlockHeight(), - valPower, - sdk.NewDecWithPrec(5, 1), - &val, - &distrKeeper, - ) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be initial / 3 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) - - // commission should be equal to initial (twice 50% commission, unaffected by slashing) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(100)) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), math.LegacyNewDec(0)) - - // validator and delegation mocks - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(3) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del).Times(5) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(2) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(initial))} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (validator init, delegation init) - require.Equal(t, uint64(2), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // second delegation - _, del2, err := distrtestutil.Delegate( - ctx, - distrKeeper, - sdk.AccAddress(valConsAddr1), - &val, - sdk.NewInt(100), - nil, - ) - require.NoError(t, err) - - // new delegation mock and update validator mock - stakingKeeper.EXPECT().Delegation(gomock.Any(), sdk.AccAddress(valConsAddr1), valAddr).Return(del2).Times(3) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(6) - - // call necessary hooks to update a delegation - err = distrKeeper.Hooks().AfterDelegationModified(ctx, sdk.AccAddress(valConsAddr1), valAddr) - require.NoError(t, err) - - // historical count should be 3 (second delegation init) - require.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws - expRewards := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(initial*3/4))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expRewards) - _, err = distrKeeper.WithdrawDelegationRewards(ctx, addr, valAddr) - require.NoError(t, err) - - // second delegator withdraws - expRewards = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(initial*1/4))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, sdk.AccAddress(valConsAddr1), expRewards) - _, err = distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valConsAddr1), valAddr) - require.NoError(t, err) - - // historical count should be 3 (validator init + two delegations) - require.Equal(t, uint64(3), distrKeeper.GetValidatorHistoricalReferenceCount(ctx)) - - // validator withdraws commission - expCommission := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(initial))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expCommission) - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddr) - require.NoError(t, err) - - // end period - endingPeriod := distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be zero - require.True(t, rewards.IsZero()) - - // commission should be zero - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission.IsZero()) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws again - expCommission = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(initial*1/4))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expCommission) - _, err = distrKeeper.WithdrawDelegationRewards(ctx, addr, valAddr) - require.NoError(t, err) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 4)}}, rewards) - - // commission should be half initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // withdraw commission - expCommission = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(initial))} - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(ctx, disttypes.ModuleName, addr, expCommission) - _, err = distrKeeper.WithdrawValidatorCommission(ctx, valAddr) - require.NoError(t, err) - - // end period - endingPeriod = distrKeeper.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards for del1 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = distrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/2 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, rewards) - - // commission should be zero - require.True(t, distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission.IsZero()) -} - -func Test100PercentCommissionReward(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(disttypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, disttypes.InitialFeePool()) - distrKeeper.SetParams(ctx, disttypes.DefaultParams()) - - // create validator with 50% commission - valAddr := sdk.ValAddress(valConsAddr0) - addr := sdk.AccAddress(valAddr) - val, err := distrtestutil.CreateValidator(valConsPk0, sdk.NewInt(100)) - require.NoError(t, err) - val.Commission = stakingtypes.NewCommission(sdk.NewDecWithPrec(10, 1), sdk.NewDecWithPrec(10, 1), math.LegacyNewDec(0)) - - // validator and delegation mocks - del := stakingtypes.NewDelegation(addr, valAddr, val.DelegatorShares) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(3) - stakingKeeper.EXPECT().Delegation(gomock.Any(), addr, valAddr).Return(del).Times(3) - - // run the necessary hooks manually (given that we are not running an actual staking module) - err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) - require.NoError(t, err) - stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val).Times(2) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, math.NewInt(initial))} - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - distrKeeper.AllocateTokensToValidator(ctx, val, tokens) - - rewards, err := distrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(addr), valAddr) - require.NoError(t, err) - - zeroRewards := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, math.ZeroInt())} - require.True(t, rewards.IsEqual(zeroRewards)) - - events := ctx.EventManager().Events() - lastEvent := events[len(events)-1] - - var hasValue bool - for _, attr := range lastEvent.Attributes { - if attr.Key == "amount" && attr.Value == "0stake" { - hasValue = true - } - } - require.True(t, hasValue) -} diff --git a/x/distribution/keeper/fee_pool.go b/x/distribution/keeper/fee_pool.go deleted file mode 100644 index b8866f5da..000000000 --- a/x/distribution/keeper/fee_pool.go +++ /dev/null @@ -1,31 +0,0 @@ -package keeper - -import ( - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DistributeFromFeePool distributes funds from the distribution module account to -// a receiver address while updating the community pool -func (k Keeper) DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error { - feePool := k.GetFeePool(ctx) - - // NOTE the community pool isn't a module account, however its coins - // are held in the distribution module account. Thus the community pool - // must be reduced separately from the SendCoinsFromModuleToAccount call - newPool, negative := feePool.CommunityPool.SafeSub(sdk.NewDecCoinsFromCoins(amount...)) - if negative { - return types.ErrBadDistribution - } - - feePool.CommunityPool = newPool - - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, receiveAddr, amount) - if err != nil { - return err - } - - k.SetFeePool(ctx, feePool) - return nil -} diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go deleted file mode 100644 index 1a0c52d45..000000000 --- a/x/distribution/keeper/genesis.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper - -import ( - "fmt" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// InitGenesis sets distribution information for genesis -func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { - var moduleHoldings sdk.DecCoins - - k.SetFeePool(ctx, data.FeePool) - - if err := k.SetParams(ctx, data.Params); err != nil { - panic(err) - } - - for _, dwi := range data.DelegatorWithdrawInfos { - delegatorAddress := sdk.MustAccAddressFromBech32(dwi.DelegatorAddress) - withdrawAddress := sdk.MustAccAddressFromBech32(dwi.WithdrawAddress) - k.SetDelegatorWithdrawAddr(ctx, delegatorAddress, withdrawAddress) - } - - var previousProposer sdk.ConsAddress - if data.PreviousProposer != "" { - var err error - previousProposer, err = sdk.ConsAddressFromBech32(data.PreviousProposer) - if err != nil { - panic(err) - } - } - - k.SetPreviousProposerConsAddr(ctx, previousProposer) - - for _, rew := range data.OutstandingRewards { - valAddr, err := sdk.ValAddressFromBech32(rew.ValidatorAddress) - if err != nil { - panic(err) - } - k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: rew.OutstandingRewards}) - moduleHoldings = moduleHoldings.Add(rew.OutstandingRewards...) - } - for _, acc := range data.ValidatorAccumulatedCommissions { - valAddr, err := sdk.ValAddressFromBech32(acc.ValidatorAddress) - if err != nil { - panic(err) - } - k.SetValidatorAccumulatedCommission(ctx, valAddr, acc.Accumulated) - } - for _, his := range data.ValidatorHistoricalRewards { - valAddr, err := sdk.ValAddressFromBech32(his.ValidatorAddress) - if err != nil { - panic(err) - } - k.SetValidatorHistoricalRewards(ctx, valAddr, his.Period, his.Rewards) - } - for _, cur := range data.ValidatorCurrentRewards { - valAddr, err := sdk.ValAddressFromBech32(cur.ValidatorAddress) - if err != nil { - panic(err) - } - k.SetValidatorCurrentRewards(ctx, valAddr, cur.Rewards) - } - for _, del := range data.DelegatorStartingInfos { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) - } - delegatorAddress := sdk.MustAccAddressFromBech32(del.DelegatorAddress) - - k.SetDelegatorStartingInfo(ctx, valAddr, delegatorAddress, del.StartingInfo) - } - for _, evt := range data.ValidatorSlashEvents { - valAddr, err := sdk.ValAddressFromBech32(evt.ValidatorAddress) - if err != nil { - panic(err) - } - k.SetValidatorSlashEvent(ctx, valAddr, evt.Height, evt.Period, evt.ValidatorSlashEvent) - } - - moduleHoldings = moduleHoldings.Add(data.FeePool.CommunityPool...) - moduleHoldingsInt, _ := moduleHoldings.TruncateDecimal() - - // check if the module account exists - moduleAcc := k.GetDistributionAccount(ctx) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - - balances := k.bankKeeper.GetAllBalances(ctx, moduleAcc.GetAddress()) - if balances.IsZero() { - k.authKeeper.SetModuleAccount(ctx, moduleAcc) - } - if !balances.IsEqual(moduleHoldingsInt) { - panic(fmt.Sprintf("distribution module balance does not match the module holdings: %s <-> %s", balances, moduleHoldingsInt)) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - feePool := k.GetFeePool(ctx) - params := k.GetParams(ctx) - - dwi := make([]types.DelegatorWithdrawInfo, 0) - k.IterateDelegatorWithdrawAddrs(ctx, func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool) { - dwi = append(dwi, types.DelegatorWithdrawInfo{ - DelegatorAddress: del.String(), - WithdrawAddress: addr.String(), - }) - return false - }) - - pp := k.GetPreviousProposerConsAddr(ctx) - outstanding := make([]types.ValidatorOutstandingRewardsRecord, 0) - - k.IterateValidatorOutstandingRewards(ctx, - func(addr sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) { - outstanding = append(outstanding, types.ValidatorOutstandingRewardsRecord{ - ValidatorAddress: addr.String(), - OutstandingRewards: rewards.Rewards, - }) - return false - }, - ) - - acc := make([]types.ValidatorAccumulatedCommissionRecord, 0) - k.IterateValidatorAccumulatedCommissions(ctx, - func(addr sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool) { - acc = append(acc, types.ValidatorAccumulatedCommissionRecord{ - ValidatorAddress: addr.String(), - Accumulated: commission, - }) - return false - }, - ) - - his := make([]types.ValidatorHistoricalRewardsRecord, 0) - k.IterateValidatorHistoricalRewards(ctx, - func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool) { - his = append(his, types.ValidatorHistoricalRewardsRecord{ - ValidatorAddress: val.String(), - Period: period, - Rewards: rewards, - }) - return false - }, - ) - - cur := make([]types.ValidatorCurrentRewardsRecord, 0) - k.IterateValidatorCurrentRewards(ctx, - func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool) { - cur = append(cur, types.ValidatorCurrentRewardsRecord{ - ValidatorAddress: val.String(), - Rewards: rewards, - }) - return false - }, - ) - - dels := make([]types.DelegatorStartingInfoRecord, 0) - k.IterateDelegatorStartingInfos(ctx, - func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool) { - dels = append(dels, types.DelegatorStartingInfoRecord{ - ValidatorAddress: val.String(), - DelegatorAddress: del.String(), - StartingInfo: info, - }) - return false - }, - ) - - slashes := make([]types.ValidatorSlashEventRecord, 0) - k.IterateValidatorSlashEvents(ctx, - func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool) { - slashes = append(slashes, types.ValidatorSlashEventRecord{ - ValidatorAddress: val.String(), - Height: height, - Period: event.ValidatorPeriod, - ValidatorSlashEvent: event, - }) - return false - }, - ) - - return types.NewGenesisState(params, feePool, dwi, pp, outstanding, acc, his, cur, dels, slashes) -} diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go deleted file mode 100644 index 674768279..000000000 --- a/x/distribution/keeper/grpc_query.go +++ /dev/null @@ -1,296 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "x/distribution/types" - - "cosmossdk.io/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -var _ types.QueryServer = Querier{} - -type Querier struct { - Keeper -} - -func NewQuerier(keeper Keeper) Querier { - return Querier{Keeper: keeper} -} - -// Params queries params of distribution module -func (k Querier) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - params := k.GetParams(ctx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// ValidatorDistributionInfo query validator's commission and self-delegation rewards -func (k Querier) ValidatorDistributionInfo(c context.Context, req *types.QueryValidatorDistributionInfoRequest) (*types.QueryValidatorDistributionInfoResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.ValidatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty validator address") - } - - ctx := sdk.UnwrapSDKContext(c) - - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) - if err != nil { - return nil, err - } - - // self-delegation rewards - val := k.stakingKeeper.Validator(ctx, valAdr) - if val == nil { - return nil, sdkerrors.Wrap(types.ErrNoValidatorExists, req.ValidatorAddress) - } - - delAdr := sdk.AccAddress(valAdr) - - del := k.stakingKeeper.Delegation(ctx, delAdr, valAdr) - if del == nil { - return nil, types.ErrNoDelegationExists - } - - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // validator's commission - validatorCommission := k.GetValidatorAccumulatedCommission(ctx, valAdr) - - return &types.QueryValidatorDistributionInfoResponse{ - Commission: validatorCommission.Commission, - OperatorAddress: delAdr.String(), - SelfBondRewards: rewards, - }, nil -} - -// ValidatorOutstandingRewards queries rewards of a validator address -func (k Querier) ValidatorOutstandingRewards(c context.Context, req *types.QueryValidatorOutstandingRewardsRequest) (*types.QueryValidatorOutstandingRewardsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.ValidatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty validator address") - } - - ctx := sdk.UnwrapSDKContext(c) - - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) - if err != nil { - return nil, err - } - rewards := k.GetValidatorOutstandingRewards(ctx, valAdr) - - return &types.QueryValidatorOutstandingRewardsResponse{Rewards: rewards}, nil -} - -// ValidatorCommission queries accumulated commission for a validator -func (k Querier) ValidatorCommission(c context.Context, req *types.QueryValidatorCommissionRequest) (*types.QueryValidatorCommissionResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.ValidatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty validator address") - } - - ctx := sdk.UnwrapSDKContext(c) - - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) - if err != nil { - return nil, err - } - commission := k.GetValidatorAccumulatedCommission(ctx, valAdr) - - return &types.QueryValidatorCommissionResponse{Commission: commission}, nil -} - -// ValidatorSlashes queries slash events of a validator -func (k Querier) ValidatorSlashes(c context.Context, req *types.QueryValidatorSlashesRequest) (*types.QueryValidatorSlashesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.ValidatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty validator address") - } - - if req.EndingHeight < req.StartingHeight { - return nil, status.Errorf(codes.InvalidArgument, "starting height greater than ending height (%d > %d)", req.StartingHeight, req.EndingHeight) - } - - ctx := sdk.UnwrapSDKContext(c) - store := ctx.KVStore(k.storeKey) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid validator address") - } - slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(valAddr)) - - events, pageRes, err := query.GenericFilteredPaginate(k.cdc, slashesStore, req.Pagination, func(key []byte, result *types.ValidatorSlashEvent) (*types.ValidatorSlashEvent, error) { - if result.ValidatorPeriod < req.StartingHeight || result.ValidatorPeriod > req.EndingHeight { - return nil, nil - } - - return result, nil - }, func() *types.ValidatorSlashEvent { - return &types.ValidatorSlashEvent{} - }) - if err != nil { - return nil, err - } - - slashes := []types.ValidatorSlashEvent{} - for _, event := range events { - slashes = append(slashes, *event) - } - - return &types.QueryValidatorSlashesResponse{Slashes: slashes, Pagination: pageRes}, nil -} - -// DelegationRewards the total rewards accrued by a delegation -func (k Querier) DelegationRewards(c context.Context, req *types.QueryDelegationRewardsRequest) (*types.QueryDelegationRewardsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.DelegatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty delegator address") - } - - if req.ValidatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty validator address") - } - - ctx := sdk.UnwrapSDKContext(c) - - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) - if err != nil { - return nil, err - } - - val := k.stakingKeeper.Validator(ctx, valAdr) - if val == nil { - return nil, sdkerrors.Wrap(types.ErrNoValidatorExists, req.ValidatorAddress) - } - - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) - if err != nil { - return nil, err - } - del := k.stakingKeeper.Delegation(ctx, delAdr, valAdr) - if del == nil { - return nil, types.ErrNoDelegationExists - } - - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - return &types.QueryDelegationRewardsResponse{Rewards: rewards}, nil -} - -// DelegationTotalRewards the total rewards accrued by a each validator -func (k Querier) DelegationTotalRewards(c context.Context, req *types.QueryDelegationTotalRewardsRequest) (*types.QueryDelegationTotalRewardsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.DelegatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty delegator address") - } - - ctx := sdk.UnwrapSDKContext(c) - - total := sdk.DecCoins{} - var delRewards []types.DelegationDelegatorReward - - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) - if err != nil { - return nil, err - } - - k.stakingKeeper.IterateDelegations( - ctx, delAdr, - func(_ int64, del stakingtypes.DelegationI) (stop bool) { - valAddr := del.GetValidatorAddr() - val := k.stakingKeeper.Validator(ctx, valAddr) - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - delReward := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - delRewards = append(delRewards, types.NewDelegationDelegatorReward(valAddr, delReward)) - total = total.Add(delReward...) - return false - }, - ) - - return &types.QueryDelegationTotalRewardsResponse{Rewards: delRewards, Total: total}, nil -} - -// DelegatorValidators queries the validators list of a delegator -func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegatorValidatorsRequest) (*types.QueryDelegatorValidatorsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.DelegatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty delegator address") - } - - ctx := sdk.UnwrapSDKContext(c) - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) - if err != nil { - return nil, err - } - var validators []string - - k.stakingKeeper.IterateDelegations( - ctx, delAdr, - func(_ int64, del stakingtypes.DelegationI) (stop bool) { - validators = append(validators, del.GetValidatorAddr().String()) - return false - }, - ) - - return &types.QueryDelegatorValidatorsResponse{Validators: validators}, nil -} - -// DelegatorWithdrawAddress queries Query/delegatorWithdrawAddress -func (k Querier) DelegatorWithdrawAddress(c context.Context, req *types.QueryDelegatorWithdrawAddressRequest) (*types.QueryDelegatorWithdrawAddressResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - if req.DelegatorAddress == "" { - return nil, status.Error(codes.InvalidArgument, "empty delegator address") - } - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) - if err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(c) - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, delAdr) - - return &types.QueryDelegatorWithdrawAddressResponse{WithdrawAddress: withdrawAddr.String()}, nil -} - -// CommunityPool queries the community pool coins -func (k Querier) CommunityPool(c context.Context, req *types.QueryCommunityPoolRequest) (*types.QueryCommunityPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - pool := k.GetFeePoolCommunityCoins(ctx) - - return &types.QueryCommunityPoolResponse{Pool: pool}, nil -} diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go deleted file mode 100644 index 8c2fd4de2..000000000 --- a/x/distribution/keeper/hooks.go +++ /dev/null @@ -1,133 +0,0 @@ -package keeper - -import ( - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// Wrapper struct -type Hooks struct { - k Keeper -} - -var _ stakingtypes.StakingHooks = Hooks{} - -// Create new distribution hooks -func (k Keeper) Hooks() Hooks { - return Hooks{k} -} - -// initialize validator distribution record -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error { - val := h.k.stakingKeeper.Validator(ctx, valAddr) - h.k.initializeValidator(ctx, val) - return nil -} - -// AfterValidatorRemoved performs clean up after a validator is removed -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { - // fetch outstanding - outstanding := h.k.GetValidatorOutstandingRewardsCoins(ctx, valAddr) - - // force-withdraw commission - commission := h.k.GetValidatorAccumulatedCommission(ctx, valAddr).Commission - if !commission.IsZero() { - // subtract from outstanding - outstanding = outstanding.Sub(commission) - - // split into integral & remainder - coins, remainder := commission.TruncateDecimal() - - // remainder to community pool - feePool := h.k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(remainder...) - h.k.SetFeePool(ctx, feePool) - - // add to validator account - if !coins.IsZero() { - accAddr := sdk.AccAddress(valAddr) - withdrawAddr := h.k.GetDelegatorWithdrawAddr(ctx, accAddr) - - if err := h.k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, coins); err != nil { - return err - } - } - } - - // Add outstanding to community pool - // The validator is removed only after it has no more delegations. - // This operation sends only the remaining dust to the community pool. - feePool := h.k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(outstanding...) - h.k.SetFeePool(ctx, feePool) - - // delete outstanding - h.k.DeleteValidatorOutstandingRewards(ctx, valAddr) - - // remove commission record - h.k.DeleteValidatorAccumulatedCommission(ctx, valAddr) - - // clear slashes - h.k.DeleteValidatorSlashEvents(ctx, valAddr) - - // clear historical rewards - h.k.DeleteValidatorHistoricalRewards(ctx, valAddr) - - // clear current rewards - h.k.DeleteValidatorCurrentRewards(ctx, valAddr) - - return nil -} - -// increment period -func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - val := h.k.stakingKeeper.Validator(ctx, valAddr) - _ = h.k.IncrementValidatorPeriod(ctx, val) - return nil -} - -// withdraw delegation rewards (which also increments period) -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - val := h.k.stakingKeeper.Validator(ctx, valAddr) - del := h.k.stakingKeeper.Delegation(ctx, delAddr, valAddr) - - if _, err := h.k.withdrawDelegationRewards(ctx, val, del); err != nil { - return err - } - - return nil -} - -// create new delegation period record -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - h.k.initializeDelegation(ctx, valAddr, delAddr) - return nil -} - -// record the slash event -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { - h.k.updateValidatorSlashFraction(ctx, valAddr, fraction) - return nil -} - -func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { - return nil -} - -func (h Hooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { - return nil -} - -func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { - return nil -} - -func (h Hooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { - return nil -} - -func (h Hooks) AfterUnbondingInitiated(_ sdk.Context, _ uint64) error { - return nil -} diff --git a/x/distribution/keeper/invariants.go b/x/distribution/keeper/invariants.go deleted file mode 100644 index e4a134988..000000000 --- a/x/distribution/keeper/invariants.go +++ /dev/null @@ -1,160 +0,0 @@ -package keeper - -import ( - "fmt" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// register all distribution invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "nonnegative-outstanding", - NonNegativeOutstandingInvariant(k)) - ir.RegisterRoute(types.ModuleName, "can-withdraw", - CanWithdrawInvariant(k)) - ir.RegisterRoute(types.ModuleName, "reference-count", - ReferenceCountInvariant(k)) - ir.RegisterRoute(types.ModuleName, "module-account", - ModuleAccountInvariant(k)) -} - -// AllInvariants runs all invariants of the distribution module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - res, stop := CanWithdrawInvariant(k)(ctx) - if stop { - return res, stop - } - res, stop = NonNegativeOutstandingInvariant(k)(ctx) - if stop { - return res, stop - } - res, stop = ReferenceCountInvariant(k)(ctx) - if stop { - return res, stop - } - return ModuleAccountInvariant(k)(ctx) - } -} - -// NonNegativeOutstandingInvariant checks that outstanding unwithdrawn fees are never negative -func NonNegativeOutstandingInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - var msg string - var count int - var outstanding sdk.DecCoins - - k.IterateValidatorOutstandingRewards(ctx, func(addr sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) { - outstanding = rewards.GetRewards() - if outstanding.IsAnyNegative() { - count++ - msg += fmt.Sprintf("\t%v has negative outstanding coins: %v\n", addr, outstanding) - } - return false - }) - broken := count != 0 - - return sdk.FormatInvariant(types.ModuleName, "nonnegative outstanding", - fmt.Sprintf("found %d validators with negative outstanding rewards\n%s", count, msg)), broken - } -} - -// CanWithdrawInvariant checks that current rewards can be completely withdrawn -func CanWithdrawInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - // cache, we don't want to write changes - ctx, _ = ctx.CacheContext() - - var remaining sdk.DecCoins - - valDelegationAddrs := make(map[string][]sdk.AccAddress) - for _, del := range k.stakingKeeper.GetAllSDKDelegations(ctx) { - valAddr := del.GetValidatorAddr().String() - valDelegationAddrs[valAddr] = append(valDelegationAddrs[valAddr], del.GetDelegatorAddr()) - } - - // iterate over all validators - k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = k.WithdrawValidatorCommission(ctx, val.GetOperator()) - - delegationAddrs, ok := valDelegationAddrs[val.GetOperator().String()] - if ok { - for _, delAddr := range delegationAddrs { - if _, err := k.WithdrawDelegationRewards(ctx, delAddr, val.GetOperator()); err != nil { - panic(err) - } - } - } - - remaining = k.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - if len(remaining) > 0 && remaining[0].Amount.IsNegative() { - return true - } - - return false - }) - - broken := len(remaining) > 0 && remaining[0].Amount.IsNegative() - return sdk.FormatInvariant(types.ModuleName, "can withdraw", - fmt.Sprintf("remaining coins: %v\n", remaining)), broken - } -} - -// ReferenceCountInvariant checks that the number of historical rewards records is correct -func ReferenceCountInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - valCount := uint64(0) - k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valCount++ - return false - }) - dels := k.stakingKeeper.GetAllSDKDelegations(ctx) - slashCount := uint64(0) - k.IterateValidatorSlashEvents(ctx, - func(_ sdk.ValAddress, _ uint64, _ types.ValidatorSlashEvent) (stop bool) { - slashCount++ - return false - }) - - // one record per validator (last tracked period), one record per - // delegation (previous period), one record per slash (previous period) - expected := valCount + uint64(len(dels)) + slashCount - count := k.GetValidatorHistoricalReferenceCount(ctx) - broken := count != expected - - return sdk.FormatInvariant(types.ModuleName, "reference count", - fmt.Sprintf("expected historical reference count: %d = %v validators + %v delegations + %v slashes\n"+ - "total validator historical reference count: %d\n", - expected, valCount, len(dels), slashCount, count)), broken - } -} - -// ModuleAccountInvariant checks that the coins held by the distr ModuleAccount -// is consistent with the sum of validator outstanding rewards -func ModuleAccountInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - var expectedCoins sdk.DecCoins - k.IterateValidatorOutstandingRewards(ctx, func(_ sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) { - expectedCoins = expectedCoins.Add(rewards.Rewards...) - return false - }) - - communityPool := k.GetFeePoolCommunityCoins(ctx) - expectedInt, _ := expectedCoins.Add(communityPool...).TruncateDecimal() - - macc := k.GetDistributionAccount(ctx) - balances := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - broken := !balances.IsEqual(expectedInt) - return sdk.FormatInvariant( - types.ModuleName, "ModuleAccount coins", - fmt.Sprintf("\texpected ModuleAccount coins: %s\n"+ - "\tdistribution ModuleAccount coins: %s\n", - expectedInt, balances, - ), - ), broken - } -} diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go deleted file mode 100644 index c40375847..000000000 --- a/x/distribution/keeper/keeper.go +++ /dev/null @@ -1,166 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - - "x/distribution/types" - - storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// Keeper of the distribution store -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.BinaryCodec - authKeeper types.AccountKeeper - bankKeeper types.BankKeeper - stakingKeeper types.StakingKeeper - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority string - - feeCollectorName string // name of the FeeCollector ModuleAccount -} - -// NewKeeper creates a new distribution Keeper instance -func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, - ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, - feeCollectorName string, authority string, -) Keeper { - // ensure distribution module account is set - if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - - return Keeper{ - storeKey: key, - cdc: cdc, - authKeeper: ak, - bankKeeper: bk, - stakingKeeper: sk, - feeCollectorName: feeCollectorName, - authority: authority, - } -} - -// GetAuthority returns the x/distribution module's authority. -func (k Keeper) GetAuthority() string { - return k.authority -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) -} - -// SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal -func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error { - if k.bankKeeper.BlockedAddr(withdrawAddr) { - return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", withdrawAddr) - } - - if !k.GetWithdrawAddrEnabled(ctx) { - return types.ErrSetWithdrawAddrDisabled - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSetWithdrawAddress, - sdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawAddr.String()), - ), - ) - - k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) - return nil -} - -// withdraw rewards from a delegation -func (k Keeper) WithdrawDelegationRewards(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (sdk.Coins, error) { - val := k.stakingKeeper.Validator(ctx, valAddr) - if val == nil { - return nil, types.ErrNoValidatorDistInfo - } - - del := k.stakingKeeper.Delegation(ctx, delAddr, valAddr) - if del == nil { - return nil, types.ErrEmptyDelegationDistInfo - } - - // withdraw rewards - rewards, err := k.withdrawDelegationRewards(ctx, val, del) - if err != nil { - return nil, err - } - - // reinitialize the delegation - k.initializeDelegation(ctx, valAddr, delAddr) - return rewards, nil -} - -// withdraw validator commission -func (k Keeper) WithdrawValidatorCommission(ctx sdk.Context, valAddr sdk.ValAddress) (sdk.Coins, error) { - // fetch validator accumulated commission - accumCommission := k.GetValidatorAccumulatedCommission(ctx, valAddr) - if accumCommission.Commission.IsZero() { - return nil, types.ErrNoValidatorCommission - } - - commission, remainder := accumCommission.Commission.TruncateDecimal() - k.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: remainder}) // leave remainder to withdraw later - - // update outstanding - outstanding := k.GetValidatorOutstandingRewards(ctx, valAddr).Rewards - k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(sdk.NewDecCoinsFromCoins(commission...))}) - - if !commission.IsZero() { - accAddr := sdk.AccAddress(valAddr) - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, accAddr) - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, commission) - if err != nil { - return nil, err - } - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeWithdrawCommission, - sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()), - ), - ) - - return commission, nil -} - -// GetTotalRewards returns the total amount of fee distribution rewards held in the store -func (k Keeper) GetTotalRewards(ctx sdk.Context) (totalRewards sdk.DecCoins) { - k.IterateValidatorOutstandingRewards(ctx, - func(_ sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) { - totalRewards = totalRewards.Add(rewards.Rewards...) - return false - }, - ) - - return totalRewards -} - -// FundCommunityPool allows an account to directly fund the community fund pool. -// The amount is first added to the distribution module account and then directly -// added to the pool. An error is returned if the amount cannot be sent to the -// module account. -func (k Keeper) FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { - return err - } - - feePool := k.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) - k.SetFeePool(ctx, feePool) - - return nil -} diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go deleted file mode 100644 index 0cad386cd..000000000 --- a/x/distribution/keeper/keeper_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - "x/distribution" - "x/distribution/keeper" - distrtestutil "x/distribution/testutil" - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/testutil" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestSetWithdrawAddr(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - addrs := simtestutil.CreateIncrementalAccounts(2) - - delegatorAddr := addrs[0] - withdrawAddr := addrs[1] - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - bankKeeper.EXPECT().BlockedAddr(withdrawAddr).Return(false).AnyTimes() - bankKeeper.EXPECT().BlockedAddr(distrAcc.GetAddress()).Return(true).AnyTimes() - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - params := types.DefaultParams() - params.WithdrawAddrEnabled = false - require.NoError(t, distrKeeper.SetParams(ctx, params)) - - err := distrKeeper.SetWithdrawAddr(ctx, delegatorAddr, withdrawAddr) - require.NotNil(t, err) - - params.WithdrawAddrEnabled = true - require.NoError(t, distrKeeper.SetParams(ctx, params)) - - err = distrKeeper.SetWithdrawAddr(ctx, delegatorAddr, withdrawAddr) - require.Nil(t, err) - - require.Error(t, distrKeeper.SetWithdrawAddr(ctx, delegatorAddr, distrAcc.GetAddress())) -} - -func TestWithdrawValidatorCommission(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - addrs := simtestutil.CreateIncrementalAccounts(1) - - valAddr := sdk.ValAddress(addrs[0]) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - valCommission := sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), - } - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // set outstanding rewards - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission}) - - // set commission - distrKeeper.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: valCommission}) - - // withdraw commission - coins := sdk.NewCoins(sdk.NewCoin("mytoken", sdk.NewInt(1)), sdk.NewCoin("stake", sdk.NewInt(1))) - // if SendCoinsFromModuleToAccount is called, we know that the withdraw was successful - bankKeeper.EXPECT().SendCoinsFromModuleToAccount(gomock.Any(), "distribution", addrs[0], coins).Return(nil) - - _, err := distrKeeper.WithdrawValidatorCommission(ctx, valAddr) - require.NoError(t, err) - - // check remainder - remainder := distrKeeper.GetValidatorAccumulatedCommission(ctx, valAddr).Commission - require.Equal(t, sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(1).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(1).Quo(math.LegacyNewDec(2))), - }, remainder) - - require.True(t, true) -} - -func TestGetTotalRewards(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - addrs := simtestutil.CreateIncrementalAccounts(2) - - valAddr0 := sdk.ValAddress(addrs[0]) - valAddr1 := sdk.ValAddress(addrs[1]) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - valCommission := sdk.DecCoins{ - sdk.NewDecCoinFromDec("mytoken", math.LegacyNewDec(5).Quo(math.LegacyNewDec(4))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(3).Quo(math.LegacyNewDec(2))), - } - - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddr0, types.ValidatorOutstandingRewards{Rewards: valCommission}) - distrKeeper.SetValidatorOutstandingRewards(ctx, valAddr1, types.ValidatorOutstandingRewards{Rewards: valCommission}) - - expectedRewards := valCommission.MulDec(math.LegacyNewDec(2)) - totalRewards := distrKeeper.GetTotalRewards(ctx) - - require.Equal(t, expectedRewards, totalRewards) -} - -func TestFundCommunityPool(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now()}) - addrs := simtestutil.CreateIncrementalAccounts(1) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // reset fee pool - distrKeeper.SetFeePool(ctx, types.InitialFeePool()) - - initPool := distrKeeper.GetFeePool(ctx) - require.Empty(t, initPool.CommunityPool) - - amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), addrs[0], "distribution", amount).Return(nil) - err := distrKeeper.FundCommunityPool(ctx, amount, addrs[0]) - require.Nil(t, err) - - require.Equal(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), distrKeeper.GetFeePool(ctx).CommunityPool) -} diff --git a/x/distribution/keeper/migrations.go b/x/distribution/keeper/migrations.go index dd1e9a255..f5a4520d6 100644 --- a/x/distribution/keeper/migrations.go +++ b/x/distribution/keeper/migrations.go @@ -1,9 +1,9 @@ package keeper import ( - "x/distribution/exported" - v2 "x/distribution/migrations/v2" - v3 "x/distribution/migrations/v3" + "github.com/cosmos/cosmos-sdk/x/distribution/exported" + v2 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" + v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/distribution/keeper/msg_server.go b/x/distribution/keeper/msg_server.go deleted file mode 100644 index 56b1f485b..000000000 --- a/x/distribution/keeper/msg_server.go +++ /dev/null @@ -1,161 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/armon/go-metrics" - - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" -) - -type msgServer struct { - Keeper -} - -var _ types.MsgServer = msgServer{} - -// NewMsgServerImpl returns an implementation of the distribution MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -func (k msgServer) SetWithdrawAddress(goCtx context.Context, msg *types.MsgSetWithdrawAddress) (*types.MsgSetWithdrawAddressResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } - withdrawAddress, err := sdk.AccAddressFromBech32(msg.WithdrawAddress) - if err != nil { - return nil, err - } - err = k.SetWithdrawAddr(ctx, delegatorAddress, withdrawAddress) - if err != nil { - return nil, err - } - - return &types.MsgSetWithdrawAddressResponse{}, nil -} - -func (k msgServer) WithdrawDelegatorReward(goCtx context.Context, msg *types.MsgWithdrawDelegatorReward) (*types.MsgWithdrawDelegatorRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - return nil, err - } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } - amount, err := k.WithdrawDelegationRewards(ctx, delegatorAddress, valAddr) - if err != nil { - return nil, err - } - - defer func() { - for _, a := range amount { - if a.Amount.IsInt64() { - telemetry.SetGaugeWithLabels( - []string{"tx", "msg", "withdraw_reward"}, - float32(a.Amount.Int64()), - []metrics.Label{telemetry.NewLabel("denom", a.Denom)}, - ) - } - } - }() - - return &types.MsgWithdrawDelegatorRewardResponse{Amount: amount}, nil -} - -func (k msgServer) WithdrawValidatorCommission(goCtx context.Context, msg *types.MsgWithdrawValidatorCommission) (*types.MsgWithdrawValidatorCommissionResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - return nil, err - } - amount, err := k.Keeper.WithdrawValidatorCommission(ctx, valAddr) - if err != nil { - return nil, err - } - - defer func() { - for _, a := range amount { - if a.Amount.IsInt64() { - telemetry.SetGaugeWithLabels( - []string{"tx", "msg", "withdraw_commission"}, - float32(a.Amount.Int64()), - []metrics.Label{telemetry.NewLabel("denom", a.Denom)}, - ) - } - } - }() - - return &types.MsgWithdrawValidatorCommissionResponse{Amount: amount}, nil -} - -func (k msgServer) FundCommunityPool(goCtx context.Context, msg *types.MsgFundCommunityPool) (*types.MsgFundCommunityPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositer, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, depositer); err != nil { - return nil, err - } - - return &types.MsgFundCommunityPoolResponse{}, nil -} - -func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) - } - - if (!req.Params.BaseProposerReward.IsNil() && !req.Params.BaseProposerReward.IsZero()) || //nolint:staticcheck - (!req.Params.BonusProposerReward.IsNil() && !req.Params.BonusProposerReward.IsZero()) { //nolint:staticcheck - return nil, errors.Wrapf(errors.ErrInvalidRequest, "cannot update base or bonus proposer reward because these are deprecated fields") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - if err := k.SetParams(ctx, req.Params); err != nil { - return nil, err - } - - return &types.MsgUpdateParamsResponse{}, nil -} - -func (k msgServer) CommunityPoolSpend(goCtx context.Context, req *types.MsgCommunityPoolSpend) (*types.MsgCommunityPoolSpendResponse, error) { - if k.authority != req.Authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - recipient, err := sdk.AccAddressFromBech32(req.Recipient) - if err != nil { - return nil, err - } - - if k.bankKeeper.BlockedAddr(recipient) { - return nil, errors.Wrapf(errors.ErrUnauthorized, "%s is not allowed to receive external funds", req.Recipient) - } - - if err := k.DistributeFromFeePool(ctx, req.Amount, recipient); err != nil { - return nil, err - } - - logger := k.Logger(ctx) - logger.Info("transferred from the community pool to recipient", "amount", req.Amount.String(), "recipient", req.Recipient) - - return &types.MsgCommunityPoolSpendResponse{}, nil -} diff --git a/x/distribution/keeper/params.go b/x/distribution/keeper/params.go deleted file mode 100644 index d13c59f8d..000000000 --- a/x/distribution/keeper/params.go +++ /dev/null @@ -1,48 +0,0 @@ -package keeper - -import ( - "cosmossdk.io/math" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// GetParams returns the total set of distribution parameters. -func (k Keeper) GetParams(clientCtx sdk.Context) (params types.Params) { - store := clientCtx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - - k.cdc.MustUnmarshal(bz, ¶ms) - return params -} - -// SetParams sets the distribution parameters to the param space. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error { - if err := params.ValidateBasic(); err != nil { - return err - } - - store := ctx.KVStore(k.storeKey) - bz, err := k.cdc.Marshal(¶ms) - if err != nil { - return err - } - store.Set(types.ParamsKey, bz) - - return nil -} - -// GetCommunityTax returns the current distribution community tax. -func (k Keeper) GetCommunityTax(ctx sdk.Context) math.LegacyDec { - return k.GetParams(ctx).CommunityTax -} - -// GetWithdrawAddrEnabled returns the current distribution withdraw address -// enabled parameter. -func (k Keeper) GetWithdrawAddrEnabled(ctx sdk.Context) (enabled bool) { - return k.GetParams(ctx).WithdrawAddrEnabled -} diff --git a/x/distribution/keeper/params_test.go b/x/distribution/keeper/params_test.go deleted file mode 100644 index baeb31b6f..000000000 --- a/x/distribution/keeper/params_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper_test - -import ( - "testing" - - "x/distribution" - "x/distribution/keeper" - distrtestutil "x/distribution/testutil" - "x/distribution/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" -) - -func TestParams(t *testing.T) { - ctrl := gomock.NewController(t) - key := sdk.NewKVStoreKey(types.StoreKey) - testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1}) - - bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) - stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) - accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) - - accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - - distrKeeper := keeper.NewKeeper( - encCfg.Codec, - key, - accountKeeper, - bankKeeper, - stakingKeeper, - "fee_collector", - authtypes.NewModuleAddress("gov").String(), - ) - - // default params - communityTax := sdk.NewDecWithPrec(2, 2) // 2% - withdrawAddrEnabled := true - - testCases := []struct { - name string - input types.Params - expErr bool - expErrMsg string - }{ - { - name: "community tax > 1", - input: types.Params{ - CommunityTax: sdk.NewDecWithPrec(2, 0), - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: true, - expErrMsg: "community tax should be non-negative and less than one", - }, - { - name: "negative community tax", - input: types.Params{ - CommunityTax: sdk.NewDecWithPrec(-2, 1), - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: true, - expErrMsg: "community tax should be non-negative and less than one", - }, - { - name: "base proposer reward > 1", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.NewDecWithPrec(1, 2), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - expErrMsg: "base proposer rewards should not be taken into account", - }, - { - name: "bonus proposer reward > 1", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.NewDecWithPrec(1, 2), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - expErrMsg: "bonus proposer rewards should not be taken into account", - }, - { - name: "all good", - input: types.Params{ - CommunityTax: communityTax, - BaseProposerReward: sdk.ZeroDec(), - BonusProposerReward: sdk.ZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, - }, - expErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - expected := distrKeeper.GetParams(ctx) - err := distrKeeper.SetParams(ctx, tc.input) - - if tc.expErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expErrMsg) - } else { - expected = tc.input - require.NoError(t, err) - } - - params := distrKeeper.GetParams(ctx) - require.Equal(t, expected, params) - }) - } -} diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go deleted file mode 100644 index 5d62101e2..000000000 --- a/x/distribution/keeper/store.go +++ /dev/null @@ -1,386 +0,0 @@ -package keeper - -import ( - gogotypes "github.com/cosmos/gogoproto/types" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// get the delegator withdraw address, defaulting to the delegator address -func (k Keeper) GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress) sdk.AccAddress { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetDelegatorWithdrawAddrKey(delAddr)) - if b == nil { - return delAddr - } - return sdk.AccAddress(b) -} - -// set the delegator withdraw address -func (k Keeper) SetDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetDelegatorWithdrawAddrKey(delAddr), withdrawAddr.Bytes()) -} - -// delete a delegator withdraw addr -func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetDelegatorWithdrawAddrKey(delAddr)) -} - -// iterate over delegator withdraw addrs -func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.DelegatorWithdrawAddrPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - addr := sdk.AccAddress(iter.Value()) - del := types.GetDelegatorWithdrawInfoAddress(iter.Key()) - if handler(del, addr) { - break - } - } -} - -// get the global fee pool distribution info -func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.FeePoolKey) - if b == nil { - panic("Stored fee pool should not have been nil") - } - k.cdc.MustUnmarshal(b, &feePool) - return -} - -// set the global fee pool distribution info -func (k Keeper) SetFeePool(ctx sdk.Context, feePool types.FeePool) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&feePool) - store.Set(types.FeePoolKey, b) -} - -// GetPreviousProposerConsAddr returns the proposer consensus address for the -// current block. -func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) sdk.ConsAddress { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ProposerKey) - if bz == nil { - panic("previous proposer not set") - } - - addrValue := gogotypes.BytesValue{} - k.cdc.MustUnmarshal(bz, &addrValue) - return addrValue.GetValue() -} - -// set the proposer public key for this block -func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&gogotypes.BytesValue{Value: consAddr}) - store.Set(types.ProposerKey, bz) -} - -// get the starting info associated with a delegator -func (k Keeper) GetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) (period types.DelegatorStartingInfo) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetDelegatorStartingInfoKey(val, del)) - k.cdc.MustUnmarshal(b, &period) - return -} - -// set the starting info associated with a delegator -func (k Keeper) SetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress, period types.DelegatorStartingInfo) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&period) - store.Set(types.GetDelegatorStartingInfoKey(val, del), b) -} - -// check existence of the starting info associated with a delegator -func (k Keeper) HasDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetDelegatorStartingInfoKey(val, del)) -} - -// delete the starting info associated with a delegator -func (k Keeper) DeleteDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetDelegatorStartingInfoKey(val, del)) -} - -// iterate over delegator starting infos -func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.DelegatorStartingInfoPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var info types.DelegatorStartingInfo - k.cdc.MustUnmarshal(iter.Value(), &info) - val, del := types.GetDelegatorStartingInfoAddresses(iter.Key()) - if handler(val, del, info) { - break - } - } -} - -// get historical rewards for a particular period -func (k Keeper) GetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64) (rewards types.ValidatorHistoricalRewards) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetValidatorHistoricalRewardsKey(val, period)) - k.cdc.MustUnmarshal(b, &rewards) - return -} - -// set historical rewards for a particular period -func (k Keeper) SetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&rewards) - store.Set(types.GetValidatorHistoricalRewardsKey(val, period), b) -} - -// iterate over historical rewards -func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var rewards types.ValidatorHistoricalRewards - k.cdc.MustUnmarshal(iter.Value(), &rewards) - addr, period := types.GetValidatorHistoricalRewardsAddressPeriod(iter.Key()) - if handler(addr, period, rewards) { - break - } - } -} - -// delete a historical reward -func (k Keeper) DeleteValidatorHistoricalReward(ctx sdk.Context, val sdk.ValAddress, period uint64) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetValidatorHistoricalRewardsKey(val, period)) -} - -// delete historical rewards for a validator -func (k Keeper) DeleteValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.GetValidatorHistoricalRewardsPrefix(val)) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} - -// delete all historical rewards -func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} - -// historical reference count (used for testcases) -func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uint64) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var rewards types.ValidatorHistoricalRewards - k.cdc.MustUnmarshal(iter.Value(), &rewards) - count += uint64(rewards.ReferenceCount) - } - return -} - -// get current rewards for a validator -func (k Keeper) GetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorCurrentRewards) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetValidatorCurrentRewardsKey(val)) - k.cdc.MustUnmarshal(b, &rewards) - return -} - -// set current rewards for a validator -func (k Keeper) SetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorCurrentRewards) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&rewards) - store.Set(types.GetValidatorCurrentRewardsKey(val), b) -} - -// delete current rewards for a validator -func (k Keeper) DeleteValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetValidatorCurrentRewardsKey(val)) -} - -// iterate over current rewards -func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorCurrentRewardsPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var rewards types.ValidatorCurrentRewards - k.cdc.MustUnmarshal(iter.Value(), &rewards) - addr := types.GetValidatorCurrentRewardsAddress(iter.Key()) - if handler(addr, rewards) { - break - } - } -} - -// get accumulated commission for a validator -func (k Keeper) GetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) (commission types.ValidatorAccumulatedCommission) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetValidatorAccumulatedCommissionKey(val)) - if b == nil { - return types.ValidatorAccumulatedCommission{} - } - k.cdc.MustUnmarshal(b, &commission) - return -} - -// set accumulated commission for a validator -func (k Keeper) SetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) { - var bz []byte - - store := ctx.KVStore(k.storeKey) - if commission.Commission.IsZero() { - bz = k.cdc.MustMarshal(&types.ValidatorAccumulatedCommission{}) - } else { - bz = k.cdc.MustMarshal(&commission) - } - - store.Set(types.GetValidatorAccumulatedCommissionKey(val), bz) -} - -// delete accumulated commission for a validator -func (k Keeper) DeleteValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetValidatorAccumulatedCommissionKey(val)) -} - -// iterate over accumulated commissions -func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler func(val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorAccumulatedCommissionPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var commission types.ValidatorAccumulatedCommission - k.cdc.MustUnmarshal(iter.Value(), &commission) - addr := types.GetValidatorAccumulatedCommissionAddress(iter.Key()) - if handler(addr, commission) { - break - } - } -} - -// get validator outstanding rewards -func (k Keeper) GetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorOutstandingRewards) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.GetValidatorOutstandingRewardsKey(val)) - k.cdc.MustUnmarshal(bz, &rewards) - return -} - -// set validator outstanding rewards -func (k Keeper) SetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&rewards) - store.Set(types.GetValidatorOutstandingRewardsKey(val), b) -} - -// delete validator outstanding rewards -func (k Keeper) DeleteValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) { - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetValidatorOutstandingRewardsKey(val)) -} - -// iterate validator outstanding rewards -func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorOutstandingRewardsPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - rewards := types.ValidatorOutstandingRewards{} - k.cdc.MustUnmarshal(iter.Value(), &rewards) - addr := types.GetValidatorOutstandingRewardsAddress(iter.Key()) - if handler(addr, rewards) { - break - } - } -} - -// get slash event for height -func (k Keeper) GetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, height, period uint64) (event types.ValidatorSlashEvent, found bool) { - store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetValidatorSlashEventKey(val, height, period)) - if b == nil { - return types.ValidatorSlashEvent{}, false - } - k.cdc.MustUnmarshal(b, &event) - return event, true -} - -// set slash event for height -func (k Keeper) SetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, height, period uint64, event types.ValidatorSlashEvent) { - store := ctx.KVStore(k.storeKey) - b := k.cdc.MustMarshal(&event) - store.Set(types.GetValidatorSlashEventKey(val, height, period), b) -} - -// iterate over slash events between heights, inclusive -func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValAddress, startingHeight uint64, endingHeight uint64, - handler func(height uint64, event types.ValidatorSlashEvent) (stop bool), -) { - store := ctx.KVStore(k.storeKey) - iter := store.Iterator( - types.GetValidatorSlashEventKeyPrefix(val, startingHeight), - types.GetValidatorSlashEventKeyPrefix(val, endingHeight+1), - ) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var event types.ValidatorSlashEvent - k.cdc.MustUnmarshal(iter.Value(), &event) - _, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) - if handler(height, event) { - break - } - } -} - -// iterate over all slash events -func (k Keeper) IterateValidatorSlashEvents(ctx sdk.Context, handler func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var event types.ValidatorSlashEvent - k.cdc.MustUnmarshal(iter.Value(), &event) - val, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) - if handler(val, height, event) { - break - } - } -} - -// delete slash events for a particular validator -func (k Keeper) DeleteValidatorSlashEvents(ctx sdk.Context, val sdk.ValAddress) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.GetValidatorSlashEventPrefix(val)) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} - -// delete all slash events -func (k Keeper) DeleteAllValidatorSlashEvents(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go deleted file mode 100644 index effbe40d2..000000000 --- a/x/distribution/keeper/validator.go +++ /dev/null @@ -1,109 +0,0 @@ -package keeper - -import ( - "fmt" - - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "x/distribution/types" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// initialize rewards for a new validator -func (k Keeper) initializeValidator(ctx sdk.Context, val stakingtypes.ValidatorI) { - // set initial historical rewards (period 0) with reference count of 1 - k.SetValidatorHistoricalRewards(ctx, val.GetOperator(), 0, types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) - - // set current rewards (starting at period 1) - k.SetValidatorCurrentRewards(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) - - // set accumulated commission - k.SetValidatorAccumulatedCommission(ctx, val.GetOperator(), types.InitialValidatorAccumulatedCommission()) - - // set outstanding rewards - k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), types.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) -} - -// increment validator period, returning the period just ended -func (k Keeper) IncrementValidatorPeriod(ctx sdk.Context, val stakingtypes.ValidatorI) uint64 { - // fetch current rewards - rewards := k.GetValidatorCurrentRewards(ctx, val.GetOperator()) - - // calculate current ratio - var current sdk.DecCoins - if val.GetTokens().IsZero() { - - // can't calculate ratio for zero-token validators - // ergo we instead add to the community pool - feePool := k.GetFeePool(ctx) - outstanding := k.GetValidatorOutstandingRewards(ctx, val.GetOperator()) - feePool.CommunityPool = feePool.CommunityPool.Add(rewards.Rewards...) - outstanding.Rewards = outstanding.GetRewards().Sub(rewards.Rewards) - k.SetFeePool(ctx, feePool) - k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), outstanding) - - current = sdk.DecCoins{} - } else { - // note: necessary to truncate so we don't allow withdrawing more rewards than owed - current = rewards.Rewards.QuoDecTruncate(sdk.NewDecFromInt(val.GetTokens())) - } - - // fetch historical rewards for last period - historical := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), rewards.Period-1).CumulativeRewardRatio - - // decrement reference count - k.decrementReferenceCount(ctx, val.GetOperator(), rewards.Period-1) - - // set new historical rewards with reference count of 1 - k.SetValidatorHistoricalRewards(ctx, val.GetOperator(), rewards.Period, types.NewValidatorHistoricalRewards(historical.Add(current...), 1)) - - // set current rewards, incrementing period by 1 - k.SetValidatorCurrentRewards(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, rewards.Period+1)) - - return rewards.Period -} - -// increment the reference count for a historical rewards value -func (k Keeper) incrementReferenceCount(ctx sdk.Context, valAddr sdk.ValAddress, period uint64) { - historical := k.GetValidatorHistoricalRewards(ctx, valAddr, period) - if historical.ReferenceCount > 2 { - panic("reference count should never exceed 2") - } - historical.ReferenceCount++ - k.SetValidatorHistoricalRewards(ctx, valAddr, period, historical) -} - -// decrement the reference count for a historical rewards value, and delete if zero references remain -func (k Keeper) decrementReferenceCount(ctx sdk.Context, valAddr sdk.ValAddress, period uint64) { - historical := k.GetValidatorHistoricalRewards(ctx, valAddr, period) - if historical.ReferenceCount == 0 { - panic("cannot set negative reference count") - } - historical.ReferenceCount-- - if historical.ReferenceCount == 0 { - k.DeleteValidatorHistoricalReward(ctx, valAddr, period) - } else { - k.SetValidatorHistoricalRewards(ctx, valAddr, period, historical) - } -} - -func (k Keeper) updateValidatorSlashFraction(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { - if fraction.GT(math.LegacyOneDec()) || fraction.IsNegative() { - panic(fmt.Sprintf("fraction must be >=0 and <=1, current fraction: %v", fraction)) - } - - val := k.stakingKeeper.Validator(ctx, valAddr) - - // increment current period - newPeriod := k.IncrementValidatorPeriod(ctx, val) - - // increment reference count on period we need to track - k.incrementReferenceCount(ctx, valAddr, newPeriod) - - slashEvent := types.NewValidatorSlashEvent(newPeriod, fraction) - height := uint64(ctx.BlockHeight()) - - k.SetValidatorSlashEvent(ctx, valAddr, height, newPeriod, slashEvent) -} diff --git a/x/distribution/migrations/v1/types.go b/x/distribution/migrations/v1/types.go deleted file mode 100644 index 987a1fc29..000000000 --- a/x/distribution/migrations/v1/types.go +++ /dev/null @@ -1,185 +0,0 @@ -package legacy - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -const ( - // ModuleName is the module name constant used in many places - ModuleName = "distribution" - - // StoreKey is the store key string for distribution - StoreKey = ModuleName - - // RouterKey is the message route for distribution - RouterKey = ModuleName - - // QuerierRoute is the querier route for distribution - QuerierRoute = ModuleName -) - -// Keys for distribution store -// Items are stored with the following key: values -// -// - 0x00: FeePol -// -// - 0x01: sdk.ConsAddress -// -// - 0x02: ValidatorOutstandingRewards -// -// - 0x03: sdk.AccAddress -// -// - 0x04: DelegatorStartingInfo -// -// - 0x05: ValidatorHistoricalRewards -// -// - 0x06: ValidatorCurrentRewards -// -// - 0x07: ValidatorCurrentRewards -// -// - 0x08: ValidatorSlashEvent -var ( - FeePoolKey = []byte{0x00} // key for global distribution state - ProposerKey = []byte{0x01} // key for the proposer operator address - ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards - - DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address - DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info - ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake - ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards - ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission - ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction -) - -// gets an address from a validator's outstanding rewards key -func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ValAddress(addr) -} - -// gets an address from a delegator's withdraw info key -func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.AccAddress(addr) -} - -// gets the addresses from a delegator starting info key -func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = sdk.ValAddress(addr) - addr = key[1+v1auth.AddrLen:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - delAddr = sdk.AccAddress(addr) - return -} - -// gets the address & period from a validator's historical rewards key -func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = sdk.ValAddress(addr) - b := key[1+v1auth.AddrLen:] - kv.AssertKeyLength(addr, 8) - period = binary.LittleEndian.Uint64(b) - return -} - -// gets the address from a validator's current rewards key -func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ValAddress(addr) -} - -// gets the address from a validator's accumulated commission key -func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { - kv.AssertKeyAtLeastLength(key, 2) - addr := key[1:] - kv.AssertKeyLength(addr, v1auth.AddrLen) - return sdk.ValAddress(addr) -} - -// gets the height from a validator's slash event key -func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { - kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen) - addr := key[1 : 1+v1auth.AddrLen] - kv.AssertKeyLength(addr, v1auth.AddrLen) - valAddr = sdk.ValAddress(addr) - startB := 1 + v1auth.AddrLen - kv.AssertKeyAtLeastLength(key, startB+9) - b := key[startB : startB+8] // the next 8 bytes represent the height - height = binary.BigEndian.Uint64(b) - return -} - -// gets the outstanding rewards key for a validator -func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { - return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) -} - -// gets the key for a delegator's withdraw addr -func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { - return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) -} - -// gets the key for a delegator's starting info -func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) -} - -// gets the prefix key for a validator's historical rewards -func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { - return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...) -} - -// gets the key for a validator's historical rewards -func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, k) - return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) -} - -// gets the key for a validator's current rewards -func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { - return append(ValidatorCurrentRewardsPrefix, v.Bytes()...) -} - -// gets the key for a validator's current commission -func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { - return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...) -} - -// gets the prefix key for a validator's slash fractions -func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { - return append(ValidatorSlashEventPrefix, v.Bytes()...) -} - -// gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height) -func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { - heightBz := make([]byte, 8) - binary.BigEndian.PutUint64(heightBz, height) - return append( - ValidatorSlashEventPrefix, - append(v.Bytes(), heightBz...)..., - ) -} - -// gets the key for a validator's slash fraction -func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte { - periodBz := make([]byte, 8) - binary.BigEndian.PutUint64(periodBz, period) - prefix := GetValidatorSlashEventKeyPrefix(v, height) - return append(prefix, periodBz...) -} diff --git a/x/distribution/migrations/v2/helpers.go b/x/distribution/migrations/v2/helpers.go deleted file mode 100644 index 0a726225f..000000000 --- a/x/distribution/migrations/v2/helpers.go +++ /dev/null @@ -1,71 +0,0 @@ -package v2 - -import ( - "cosmossdk.io/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" -) - -// MigratePrefixAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_bytes -// into format: -// prefix_bytes | address_len (1 byte) | address_bytes -func MigratePrefixAddress(store sdk.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := oldStoreIter.Key() - newStoreKey := prefixBz - newStoreKey = append(newStoreKey, address.MustLengthPrefix(addr)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigratePrefixAddressBytes is a helper function that migrates all keys of format: -// prefix_bytes | address_bytes | arbitrary_bytes -// into format: -// prefix_bytes | address_len (1 byte) | address_bytes | arbitrary_bytes -func MigratePrefixAddressBytes(store sdk.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr := oldStoreIter.Key()[:v1auth.AddrLen] - endBz := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr)...), endBz...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// MigratePrefixAddressAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_1_bytes | address_2_bytes -// into format: -// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes -func MigratePrefixAddressAddress(store sdk.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr1 := oldStoreIter.Key()[:v1auth.AddrLen] - addr2 := oldStoreIter.Key()[v1auth.AddrLen:] - newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} diff --git a/x/distribution/migrations/v2/store.go b/x/distribution/migrations/v2/store.go deleted file mode 100644 index 4b13a8fb6..000000000 --- a/x/distribution/migrations/v2/store.go +++ /dev/null @@ -1,25 +0,0 @@ -package v2 - -import ( - v1 "x/distribution/migrations/v1" - - storetypes "cosmossdk.io/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MigrateStore performs in-place store migrations from v0.40 to v0.43. The -// migration includes: -// -// - Change addresses to be length-prefixed. -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey) error { - store := ctx.KVStore(storeKey) - MigratePrefixAddress(store, v1.ValidatorOutstandingRewardsPrefix) - MigratePrefixAddress(store, v1.DelegatorWithdrawAddrPrefix) - MigratePrefixAddressAddress(store, v1.DelegatorStartingInfoPrefix) - MigratePrefixAddressBytes(store, v1.ValidatorHistoricalRewardsPrefix) - MigratePrefixAddress(store, v1.ValidatorCurrentRewardsPrefix) - MigratePrefixAddress(store, v1.ValidatorAccumulatedCommissionPrefix) - MigratePrefixAddressBytes(store, v1.ValidatorSlashEventPrefix) - - return nil -} diff --git a/x/distribution/migrations/v2/store_test.go b/x/distribution/migrations/v2/store_test.go deleted file mode 100644 index 6b956fe0c..000000000 --- a/x/distribution/migrations/v2/store_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package v2_test - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/require" - - v1 "x/distribution/migrations/v1" - v2 "x/distribution/migrations/v2" - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestStoreMigration(t *testing.T) { - distributionKey := sdk.NewKVStoreKey("distribution") - ctx := testutil.DefaultContext(distributionKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(distributionKey) - - _, _, addr1 := testdata.KeyTestPubAddr() - valAddr := sdk.ValAddress(addr1) - _, _, addr2 := testdata.KeyTestPubAddr() - // Use dummy value for all keys. - value := []byte("foo") - - testCases := []struct { - name string - oldKey []byte - newKey []byte - }{ - { - "FeePoolKey", - v1.FeePoolKey, - types.FeePoolKey, - }, - { - "ProposerKey", - v1.ProposerKey, - types.ProposerKey, - }, - { - "ValidatorOutstandingRewards", - v1.GetValidatorOutstandingRewardsKey(valAddr), - types.GetValidatorOutstandingRewardsKey(valAddr), - }, - { - "DelegatorWithdrawAddr", - v1.GetDelegatorWithdrawAddrKey(addr2), - types.GetDelegatorWithdrawAddrKey(addr2), - }, - { - "DelegatorStartingInfo", - v1.GetDelegatorStartingInfoKey(valAddr, addr2), - types.GetDelegatorStartingInfoKey(valAddr, addr2), - }, - { - "ValidatorHistoricalRewards", - v1.GetValidatorHistoricalRewardsKey(valAddr, 6), - types.GetValidatorHistoricalRewardsKey(valAddr, 6), - }, - { - "ValidatorCurrentRewards", - v1.GetValidatorCurrentRewardsKey(valAddr), - types.GetValidatorCurrentRewardsKey(valAddr), - }, - { - "ValidatorAccumulatedCommission", - v1.GetValidatorAccumulatedCommissionKey(valAddr), - types.GetValidatorAccumulatedCommissionKey(valAddr), - }, - { - "ValidatorSlashEvent", - v1.GetValidatorSlashEventKey(valAddr, 6, 8), - types.GetValidatorSlashEventKey(valAddr, 6, 8), - }, - } - - // Set all the old keys to the store - for _, tc := range testCases { - store.Set(tc.oldKey, value) - } - - // Run migrations. - err := v2.MigrateStore(ctx, distributionKey) - require.NoError(t, err) - - // Make sure the new keys are set and old keys are deleted. - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - if !bytes.Equal(tc.oldKey, tc.newKey) { - require.Nil(t, store.Get(tc.oldKey)) - } - require.Equal(t, value, store.Get(tc.newKey)) - }) - } -} diff --git a/x/distribution/migrations/v3/json.go b/x/distribution/migrations/v3/json.go deleted file mode 100644 index 44e866cb4..000000000 --- a/x/distribution/migrations/v3/json.go +++ /dev/null @@ -1,19 +0,0 @@ -package v3 - -import ( - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MigrateJSON accepts exported v2 (v0.46) x/distribution genesis state and migrates it to -// v3 (v0.47) x/distribution genesis state. The migration includes: -// -// Reset of the deprecated rewards to zero. -func MigrateJSON(oldState *types.GenesisState) *types.GenesisState { - // reset deprecated rewards to zero - oldState.Params.BaseProposerReward = sdk.ZeroDec() - oldState.Params.BonusProposerReward = sdk.ZeroDec() - - return oldState -} diff --git a/x/distribution/migrations/v3/json_test.go b/x/distribution/migrations/v3/json_test.go deleted file mode 100644 index 36a5e0443..000000000 --- a/x/distribution/migrations/v3/json_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package v3_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "x/distribution" - v3 "x/distribution/migrations/v3" - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" -) - -func TestMigrateJSON(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) - clientCtx := client.Context{}. - WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithTxConfig(encodingConfig.TxConfig). - WithCodec(encodingConfig.Codec) - - distrGenState := types.DefaultGenesisState() - - oldDistrState := distrGenState - oldDistrState.Params.BaseProposerReward = sdk.NewDecWithPrec(1, 2) - oldDistrState.Params.BonusProposerReward = sdk.NewDecWithPrec(4, 2) - - migrated := v3.MigrateJSON(oldDistrState) - require.Equal(t, migrated, distrGenState) - - bz, err := clientCtx.Codec.MarshalJSON(migrated) - require.NoError(t, err) - - // Indent the JSON bz correctly. - var jsonObj map[string]interface{} - err = json.Unmarshal(bz, &jsonObj) - require.NoError(t, err) - indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") - require.NoError(t, err) - - expected := `{ - "delegator_starting_infos": [], - "delegator_withdraw_infos": [], - "fee_pool": { - "community_pool": [] - }, - "outstanding_rewards": [], - "params": { - "base_proposer_reward": "0.000000000000000000", - "bonus_proposer_reward": "0.000000000000000000", - "community_tax": "0.020000000000000000", - "withdraw_addr_enabled": true - }, - "previous_proposer": "", - "validator_accumulated_commissions": [], - "validator_current_rewards": [], - "validator_historical_rewards": [], - "validator_slash_events": [] -}` - - require.Equal(t, expected, string(indentedBz)) -} diff --git a/x/distribution/migrations/v3/migrate.go b/x/distribution/migrations/v3/migrate.go index 34d741695..db9ffbf02 100644 --- a/x/distribution/migrations/v3/migrate.go +++ b/x/distribution/migrations/v3/migrate.go @@ -1,8 +1,9 @@ package v3 import ( - "x/distribution/exported" - "x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + + "github.com/cosmos/cosmos-sdk/x/distribution/exported" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/distribution/migrations/v3/migrate_test.go b/x/distribution/migrations/v3/migrate_test.go index e3b88848d..159387d42 100644 --- a/x/distribution/migrations/v3/migrate_test.go +++ b/x/distribution/migrations/v3/migrate_test.go @@ -5,10 +5,11 @@ import ( "github.com/stretchr/testify/require" - "x/distribution" - "x/distribution/exported" - v3 "x/distribution/migrations/v3" - "x/distribution/types" + v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/exported" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/distribution/module.go b/x/distribution/module.go index e767764aa..664527928 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -13,11 +13,11 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" - "github.com/ODIN-PROTOCOL/odin-core/x/distribution/client/cli" - "github.com/ODIN-PROTOCOL/odin-core/x/distribution/exported" - "github.com/ODIN-PROTOCOL/odin-core/x/distribution/keeper" - "github.com/ODIN-PROTOCOL/odin-core/x/distribution/simulation" - "github.com/ODIN-PROTOCOL/odin-core/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/distribution/exported" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + "github.com/cosmos/cosmos-sdk/x/distribution/types" sdkclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/distribution/simulation/decoder.go b/x/distribution/simulation/decoder.go deleted file mode 100644 index 0da8ac6c7..000000000 --- a/x/distribution/simulation/decoder.go +++ /dev/null @@ -1,71 +0,0 @@ -package simulation - -import ( - "bytes" - "fmt" - - "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" -) - -// NewDecodeStore returns a decoder function closure that unmarshals the KVPair's -// Value to the corresponding distribution type. -func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { - return func(kvA, kvB kv.Pair) string { - switch { - case bytes.Equal(kvA.Key[:1], types.FeePoolKey): - var feePoolA, feePoolB types.FeePool - cdc.MustUnmarshal(kvA.Value, &feePoolA) - cdc.MustUnmarshal(kvB.Value, &feePoolB) - return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - - case bytes.Equal(kvA.Key[:1], types.ProposerKey): - return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], types.ValidatorOutstandingRewardsPrefix): - var rewardsA, rewardsB types.ValidatorOutstandingRewards - cdc.MustUnmarshal(kvA.Value, &rewardsA) - cdc.MustUnmarshal(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], types.DelegatorWithdrawAddrPrefix): - return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], types.DelegatorStartingInfoPrefix): - var infoA, infoB types.DelegatorStartingInfo - cdc.MustUnmarshal(kvA.Value, &infoA) - cdc.MustUnmarshal(kvB.Value, &infoB) - return fmt.Sprintf("%v\n%v", infoA, infoB) - - case bytes.Equal(kvA.Key[:1], types.ValidatorHistoricalRewardsPrefix): - var rewardsA, rewardsB types.ValidatorHistoricalRewards - cdc.MustUnmarshal(kvA.Value, &rewardsA) - cdc.MustUnmarshal(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], types.ValidatorCurrentRewardsPrefix): - var rewardsA, rewardsB types.ValidatorCurrentRewards - cdc.MustUnmarshal(kvA.Value, &rewardsA) - cdc.MustUnmarshal(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], types.ValidatorAccumulatedCommissionPrefix): - var commissionA, commissionB types.ValidatorAccumulatedCommission - cdc.MustUnmarshal(kvA.Value, &commissionA) - cdc.MustUnmarshal(kvB.Value, &commissionB) - return fmt.Sprintf("%v\n%v", commissionA, commissionB) - - case bytes.Equal(kvA.Key[:1], types.ValidatorSlashEventPrefix): - var eventA, eventB types.ValidatorSlashEvent - cdc.MustUnmarshal(kvA.Value, &eventA) - cdc.MustUnmarshal(kvB.Value, &eventB) - return fmt.Sprintf("%v\n%v", eventA, eventB) - - default: - panic(fmt.Sprintf("invalid distribution key prefix %X", kvA.Key[:1])) - } - } -} diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go deleted file mode 100644 index 183fb71d8..000000000 --- a/x/distribution/simulation/decoder_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package simulation_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "x/distribution/simulation" - "x/distribution/testutil" - "x/distribution/types" - - "cosmossdk.io/depinject" - "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" -) - -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) -) - -func TestDecodeDistributionStore(t *testing.T) { - var cdc codec.Codec - err := depinject.Inject(testutil.AppConfig, &cdc) - require.NoError(t, err) - - dec := simulation.NewDecodeStore(cdc) - - decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} - feePool := types.InitialFeePool() - feePool.CommunityPool = decCoins - info := types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200) - outstanding := types.ValidatorOutstandingRewards{Rewards: decCoins} - commission := types.ValidatorAccumulatedCommission{Commission: decCoins} - historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 100) - currentRewards := types.NewValidatorCurrentRewards(decCoins, 5) - slashEvent := types.NewValidatorSlashEvent(10, math.LegacyOneDec()) - - kvPairs := kv.Pairs{ - Pairs: []kv.Pair{ - {Key: types.FeePoolKey, Value: cdc.MustMarshal(&feePool)}, - {Key: types.ProposerKey, Value: consAddr1.Bytes()}, - {Key: types.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshal(&outstanding)}, - {Key: types.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, - {Key: types.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshal(&info)}, - {Key: types.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshal(&historicalRewards)}, - {Key: types.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshal(¤tRewards)}, - {Key: types.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshal(&commission)}, - {Key: types.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshal(&slashEvent)}, - {Key: []byte{0x99}, Value: []byte{0x99}}, - }, - } - - tests := []struct { - name string - expectedLog string - }{ - {"FeePool", fmt.Sprintf("%v\n%v", feePool, feePool)}, - {"Proposer", fmt.Sprintf("%v\n%v", consAddr1, consAddr1)}, - {"ValidatorOutstandingRewards", fmt.Sprintf("%v\n%v", outstanding, outstanding)}, - {"DelegatorWithdrawAddr", fmt.Sprintf("%v\n%v", delAddr1, delAddr1)}, - {"DelegatorStartingInfo", fmt.Sprintf("%v\n%v", info, info)}, - {"ValidatorHistoricalRewards", fmt.Sprintf("%v\n%v", historicalRewards, historicalRewards)}, - {"ValidatorCurrentRewards", fmt.Sprintf("%v\n%v", currentRewards, currentRewards)}, - {"ValidatorAccumulatedCommission", fmt.Sprintf("%v\n%v", commission, commission)}, - {"ValidatorSlashEvent", fmt.Sprintf("%v\n%v", slashEvent, slashEvent)}, - {"other", ""}, - } - for i, tt := range tests { - i, tt := i, tt - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, dec(kvPairs.Pairs[i], kvPairs.Pairs[i]), tt.name) - } - }) - } -} diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go deleted file mode 100644 index 663b2c9da..000000000 --- a/x/distribution/simulation/genesis.go +++ /dev/null @@ -1,61 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - "math/rand" - - "x/distribution/types" - - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" -) - -// Simulation parameter constants -const ( - CommunityTax = "community_tax" - WithdrawEnabled = "withdraw_enabled" -) - -// GenCommunityTax randomized CommunityTax -func GenCommunityTax(r *rand.Rand) math.LegacyDec { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) -} - -// GenWithdrawEnabled returns a randomized WithdrawEnabled parameter. -func GenWithdrawEnabled(r *rand.Rand) bool { - return r.Int63n(101) <= 95 // 95% chance of withdraws being enabled -} - -// RandomizedGenState generates a random GenesisState for distribution -func RandomizedGenState(simState *module.SimulationState) { - var communityTax sdk.Dec - simState.AppParams.GetOrGenerate( - simState.Cdc, CommunityTax, &communityTax, simState.Rand, - func(r *rand.Rand) { communityTax = GenCommunityTax(r) }, - ) - - var withdrawEnabled bool - simState.AppParams.GetOrGenerate( - simState.Cdc, WithdrawEnabled, &withdrawEnabled, simState.Rand, - func(r *rand.Rand) { withdrawEnabled = GenWithdrawEnabled(r) }, - ) - - distrGenesis := types.GenesisState{ - FeePool: types.InitialFeePool(), - Params: types.Params{ - CommunityTax: communityTax, - WithdrawAddrEnabled: withdrawEnabled, - }, - } - - bz, err := json.MarshalIndent(&distrGenesis, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", bz) - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&distrGenesis) -} diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go deleted file mode 100644 index 08778fd4b..000000000 --- a/x/distribution/simulation/genesis_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package simulation_test - -import ( - "encoding/json" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "x/distribution/simulation" - "x/distribution/types" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" -) - -// TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. -// Abonormal scenarios are not tested here. -func TestRandomizedGenState(t *testing.T) { - interfaceRegistry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - s := rand.NewSource(1) - r := rand.New(s) - - simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), - } - - simulation.RandomizedGenState(&simState) - - var distrGenesis types.GenesisState - simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &distrGenesis) - - dec1, _ := sdk.NewDecFromStr("0.210000000000000000") - - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BaseProposerReward) //nolint:staticcheck - require.Equal(t, sdk.ZeroDec(), distrGenesis.Params.BonusProposerReward) //nolint:staticcheck - require.Equal(t, dec1, distrGenesis.Params.CommunityTax) - require.Equal(t, true, distrGenesis.Params.WithdrawAddrEnabled) - require.Len(t, distrGenesis.DelegatorStartingInfos, 0) - require.Len(t, distrGenesis.DelegatorWithdrawInfos, 0) - require.Len(t, distrGenesis.ValidatorSlashEvents, 0) -} - -// TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. -func TestRandomizedGenState1(t *testing.T) { - interfaceRegistry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - - s := rand.NewSource(1) - r := rand.New(s) - - // all these tests will panic - tests := []struct { - simState module.SimulationState - panicMsg string - }{ - { // panic => reason: incomplete initialization of the simState - module.SimulationState{}, "invalid memory address or nil pointer dereference"}, - { // panic => reason: incomplete initialization of the simState - module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - }, "assignment to entry in nil map"}, - } - - for _, tt := range tests { - require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) - } -} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 4f825ac13..db9576ac5 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -4,8 +4,8 @@ import ( "fmt" "math/rand" - "x/distribution/keeper" - "x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go deleted file mode 100644 index 63abfd92e..000000000 --- a/x/distribution/simulation/operations_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package simulation_test - -import ( - "math/rand" - "testing" - - "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/suite" - - "x/distribution/keeper" - "x/distribution/simulation" - "x/distribution/types" - distrtypes "x/distribution/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// TestWeightedOperations tests the weights of the operations. -func (suite *SimTestSuite) TestWeightedOperations() { - appParams := make(simtypes.AppParams) - - weightesOps := simulation.WeightedOperations(appParams, suite.cdc, suite.accountKeeper, - suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) - - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accs := suite.getTestingAccounts(r, 3) - - expected := []struct { - weight int - opMsgRoute string - opMsgName string - }{ - {simulation.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress}, - {simulation.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward}, - {simulation.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission}, - {simulation.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool}, - } - - for i, w := range weightesOps { - operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "") - suite.Require().NoError(err) - - // the following checks are very much dependent from the ordering of the output given - // by WeightedOperations. if the ordering in WeightedOperations changes some tests - // will fail - suite.Require().Equal(expected[i].weight, w.Weight(), "weight should be the same") - suite.Require().Equal(expected[i].opMsgRoute, operationMsg.Route, "route should be the same") - suite.Require().Equal(expected[i].opMsgName, operationMsg.Name, "operation Msg name should be the same") - } -} - -// TestSimulateMsgSetWithdrawAddress tests the normal scenario of a valid message of type TypeMsgSetWithdrawAddress. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() { - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgSetWithdrawAddress(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().NoError(err) - - var msg types.MsgSetWithdrawAddress - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().True(operationMsg.OK) - suite.Require().Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress) - suite.Require().Equal("cosmos1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7u4x9a0", msg.WithdrawAddress) - suite.Require().Equal(types.TypeMsgSetWithdrawAddress, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -// TestSimulateMsgWithdrawDelegatorReward tests the normal scenario of a valid message -// of type TypeMsgWithdrawDelegatorReward. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { - // setup 3 accounts - s := rand.NewSource(4) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // setup accounts[0] as validator - validator0 := suite.getTestingValidator0(accounts) - - // setup delegation - delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) - validator0, issuedShares := validator0.AddTokensFromDel(delTokens) - delegator := accounts[1] - delegation := stakingtypes.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares) - suite.stakingKeeper.SetDelegation(suite.ctx, delegation) - suite.distrKeeper.SetDelegatorStartingInfo(suite.ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)) - - suite.setupValidatorRewards(validator0.GetOperator()) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgWithdrawDelegatorReward(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().NoError(err) - - var msg types.MsgWithdrawDelegatorReward - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().True(operationMsg.OK) - suite.Require().Equal("cosmosvaloper1l4s054098kk9hmr5753c6k3m2kw65h686d3mhr", msg.ValidatorAddress) - suite.Require().Equal("cosmos1d6u7zhjwmsucs678d7qn95uqajd4ucl9jcjt26", msg.DelegatorAddress) - suite.Require().Equal(types.TypeMsgWithdrawDelegatorReward, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -// TestSimulateMsgWithdrawValidatorCommission tests the normal scenario of a valid message -// of type TypeMsgWithdrawValidatorCommission. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgWithdrawValidatorCommission() { - suite.testSimulateMsgWithdrawValidatorCommission("atoken") - suite.testSimulateMsgWithdrawValidatorCommission("tokenxxx") -} - -// all the checks in this function should not fail if we change the tokenName -func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName string) { - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // setup accounts[0] as validator - validator0 := suite.getTestingValidator0(accounts) - - // set module account coins - distrAcc := suite.distrKeeper.GetDistributionAccount(suite.ctx) - suite.Require().NoError(banktestutil.FundModuleAccount(suite.bankKeeper, suite.ctx, distrAcc.GetName(), sdk.NewCoins( - sdk.NewCoin(tokenName, sdk.NewInt(10)), - sdk.NewCoin("stake", sdk.NewInt(5)), - ))) - suite.accountKeeper.SetModuleAccount(suite.ctx, distrAcc) - - // set outstanding rewards - valCommission := sdk.NewDecCoins( - sdk.NewDecCoinFromDec(tokenName, math.LegacyNewDec(5).Quo(math.LegacyNewDec(2))), - sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(1).Quo(math.LegacyNewDec(1))), - ) - - suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission}) - suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission}) - - // setup validator accumulated commission - suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, validator0.GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission}) - suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission}) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgWithdrawValidatorCommission(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - if !operationMsg.OK { - suite.Require().Equal("could not find account", operationMsg.Comment) - } else { - suite.Require().NoError(err) - - var msg types.MsgWithdrawValidatorCommission - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().True(operationMsg.OK) - suite.Require().Equal("cosmosvaloper1tnh2q55v8wyygtt9srz5safamzdengsn9dsd7z", msg.ValidatorAddress) - suite.Require().Equal(types.TypeMsgWithdrawValidatorCommission, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) - } -} - -// TestSimulateMsgFundCommunityPool tests the normal scenario of a valid message of type TypeMsgFundCommunityPool. -// Abonormal scenarios, where the message is created by an errors, are not tested here. -func (suite *SimTestSuite) TestSimulateMsgFundCommunityPool() { - // setup 3 accounts - s := rand.NewSource(1) - r := rand.New(s) - accounts := suite.getTestingAccounts(r, 3) - - // begin a new block - suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) - - // execute operation - op := simulation.SimulateMsgFundCommunityPool(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) - operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") - suite.Require().NoError(err) - - var msg types.MsgFundCommunityPool - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) - - suite.Require().True(operationMsg.OK) - suite.Require().Equal("4896096stake", msg.Amount.String()) - suite.Require().Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.Depositor) - suite.Require().Equal(types.TypeMsgFundCommunityPool, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) - suite.Require().Len(futureOperations, 0) -} - -type SimTestSuite struct { - suite.Suite - - ctx sdk.Context - app *runtime.App - genesisVals []stakingtypes.Validator - - txConfig client.TxConfig - cdc codec.Codec - stakingKeeper *stakingkeeper.Keeper - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - distrKeeper keeper.Keeper -} - -func (suite *SimTestSuite) SetupTest() { - var ( - appBuilder *runtime.AppBuilder - err error - ) - suite.app, err = simtestutil.Setup(configurator.NewAppConfig( - configurator.AuthModule(), - configurator.ParamsModule(), - configurator.BankModule(), - configurator.StakingModule(), - configurator.TxModule(), - configurator.ConsensusModule(), - configurator.DistributionModule(), - ), &suite.accountKeeper, - &suite.bankKeeper, - &suite.cdc, - &appBuilder, - &suite.stakingKeeper, - &suite.distrKeeper, - &suite.txConfig, - ) - - suite.NoError(err) - - suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) - - genesisVals := suite.stakingKeeper.GetAllValidators(suite.ctx) - suite.Require().Len(genesisVals, 1) - suite.genesisVals = genesisVals -} - -func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { - accounts := simtypes.RandomAccounts(r, n) - - initAmt := suite.stakingKeeper.TokensFromConsensusPower(suite.ctx, 200) - initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt)) - - // add coins to the accounts - for _, account := range accounts { - acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address) - suite.accountKeeper.SetAccount(suite.ctx, acc) - suite.Require().NoError(banktestutil.FundAccount(suite.bankKeeper, suite.ctx, account.Address, initCoins)) - } - - return accounts -} - -func (suite *SimTestSuite) getTestingValidator0(accounts []simtypes.Account) stakingtypes.Validator { - commission0 := stakingtypes.NewCommission(math.LegacyZeroDec(), math.LegacyOneDec(), math.LegacyOneDec()) - return suite.getTestingValidator(accounts, commission0, 0) -} - -func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, commission stakingtypes.Commission, n int) stakingtypes.Validator { - require := suite.Require() - account := accounts[n] - valPubKey := account.PubKey - valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) - validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes. - Description{}) - require.NoError(err) - validator, err = validator.SetInitialCommission(commission) - require.NoError(err) - validator.DelegatorShares = math.LegacyNewDec(100) - validator.Tokens = sdk.NewInt(1000000) - - suite.stakingKeeper.SetValidator(suite.ctx, validator) - - return validator -} - -func (suite *SimTestSuite) setupValidatorRewards(valAddress sdk.ValAddress) { - decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} - historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) - suite.distrKeeper.SetValidatorHistoricalRewards(suite.ctx, valAddress, 2, historicalRewards) - // setup current revards - currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) - suite.distrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards) -} - -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go deleted file mode 100644 index 7a9f32101..000000000 --- a/x/distribution/simulation/proposals.go +++ /dev/null @@ -1,45 +0,0 @@ -package simulation - -import ( - "math/rand" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// Simulation operation weights constants -const ( - DefaultWeightMsgUpdateParams int = 50 - - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec -) - -// ProposalMsgs defines the module weighted proposals' contents -func ProposalMsgs() []simtypes.WeightedProposalMsg { - return []simtypes.WeightedProposalMsg{ - simulation.NewWeightedProposalMsg( - OpWeightMsgUpdateParams, - DefaultWeightMsgUpdateParams, - SimulateMsgUpdateParams, - ), - } -} - -// SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { - // use the default gov module account address as authority - var authority sdk.AccAddress = address.Module("gov") - - params := types.DefaultParams() - params.CommunityTax = simtypes.RandomDecAmount(r, sdk.NewDec(1)) - params.WithdrawAddrEnabled = r.Intn(2) == 0 - - return &types.MsgUpdateParams{ - Authority: authority.String(), - Params: params, - } -} diff --git a/x/distribution/simulation/proposals_test.go b/x/distribution/simulation/proposals_test.go deleted file mode 100644 index aa708104f..000000000 --- a/x/distribution/simulation/proposals_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package simulation_test - -import ( - "math/rand" - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "gotest.tools/v3/assert" - - "x/distribution/simulation" - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" -) - -func TestProposalMsgs(t *testing.T) { - // initialize parameters - s := rand.NewSource(1) - r := rand.New(s) - - ctx := sdk.NewContext(nil, tmproto.Header{}, true, nil) - accounts := simtypes.RandomAccounts(r, 3) - - // execute ProposalMsgs function - weightedProposalMsgs := simulation.ProposalMsgs() - assert.Assert(t, len(weightedProposalMsgs) == 1) - - w0 := weightedProposalMsgs[0] - - // tests w0 interface: - assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) - assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - - msg := w0.MsgSimulatorFn()(r, ctx, accounts) - msgUpdateParams, ok := msg.(*types.MsgUpdateParams) - assert.Assert(t, ok) - - assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.DeepEqual(t, sdk.NewDec(0), msgUpdateParams.Params.CommunityTax) - assert.Equal(t, true, msgUpdateParams.Params.WithdrawAddrEnabled) -} diff --git a/x/distribution/testutil/app_config.go b/x/distribution/testutil/app_config.go deleted file mode 100644 index b1a8394d1..000000000 --- a/x/distribution/testutil/app_config.go +++ /dev/null @@ -1,123 +0,0 @@ -package testutil - -import ( - _ "x/distribution" - - _ "github.com/cosmos/cosmos-sdk/x/auth" - _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" - _ "github.com/cosmos/cosmos-sdk/x/bank" - _ "github.com/cosmos/cosmos-sdk/x/consensus" - _ "github.com/cosmos/cosmos-sdk/x/genutil" - _ "github.com/cosmos/cosmos-sdk/x/mint" - _ "github.com/cosmos/cosmos-sdk/x/params" - _ "github.com/cosmos/cosmos-sdk/x/staking" - - distrtypes "x/distribution/types" - - "cosmossdk.io/core/appconfig" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1" - appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" - authmodulev1 "cosmossdk.io/api/cosmos/auth/module/v1" - bankmodulev1 "cosmossdk.io/api/cosmos/bank/module/v1" - consensusmodulev1 "cosmossdk.io/api/cosmos/consensus/module/v1" - distrmodulev1 "cosmossdk.io/api/cosmos/distribution/module/v1" - genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1" - mintmodulev1 "cosmossdk.io/api/cosmos/mint/module/v1" - paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1" - stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1" - txconfigv1 "cosmossdk.io/api/cosmos/tx/config/v1" -) - -var AppConfig = appconfig.Compose(&appv1alpha1.Config{ - Modules: []*appv1alpha1.ModuleConfig{ - { - Name: "runtime", - Config: appconfig.WrapAny(&runtimev1alpha1.Module{ - AppName: "DistrApp", - BeginBlockers: []string{ - minttypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - consensustypes.ModuleName, - }, - EndBlockers: []string{ - stakingtypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - minttypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - consensustypes.ModuleName, - }, - InitGenesis: []string{ - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - minttypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - consensustypes.ModuleName, - }, - }), - }, - { - Name: authtypes.ModuleName, - Config: appconfig.WrapAny(&authmodulev1.Module{ - Bech32Prefix: "cosmos", - ModuleAccountPermissions: []*authmodulev1.ModuleAccountPermission{ - {Account: authtypes.FeeCollectorName}, - {Account: distrtypes.ModuleName}, - {Account: minttypes.ModuleName, Permissions: []string{authtypes.Minter}}, - {Account: stakingtypes.BondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}}, - {Account: stakingtypes.NotBondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}}, - }, - }), - }, - { - Name: banktypes.ModuleName, - Config: appconfig.WrapAny(&bankmodulev1.Module{}), - }, - { - Name: stakingtypes.ModuleName, - Config: appconfig.WrapAny(&stakingmodulev1.Module{}), - }, - { - Name: paramstypes.ModuleName, - Config: appconfig.WrapAny(¶msmodulev1.Module{}), - }, - { - Name: consensustypes.ModuleName, - Config: appconfig.WrapAny(&consensusmodulev1.Module{}), - }, - { - Name: "tx", - Config: appconfig.WrapAny(&txconfigv1.Config{}), - }, - { - Name: genutiltypes.ModuleName, - Config: appconfig.WrapAny(&genutilmodulev1.Module{}), - }, - { - Name: distrtypes.ModuleName, - Config: appconfig.WrapAny(&distrmodulev1.Module{}), - }, - { - Name: minttypes.ModuleName, - Config: appconfig.WrapAny(&mintmodulev1.Module{}), - }, - }, -}) diff --git a/x/distribution/testutil/expected_keepers_mocks.go b/x/distribution/testutil/expected_keepers_mocks.go deleted file mode 100644 index 585d2cb57..000000000 --- a/x/distribution/testutil/expected_keepers_mocks.go +++ /dev/null @@ -1,376 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: x/distribution/types/expected_keepers.go - -// Package testutil is a generated GoMock package. -package testutil - -import ( - reflect "reflect" - - types "github.com/cosmos/cosmos-sdk/types" - types0 "github.com/cosmos/cosmos-sdk/x/auth/types" - types1 "github.com/cosmos/cosmos-sdk/x/staking/types" - gomock "github.com/golang/mock/gomock" -) - -// MockAccountKeeper is a mock of AccountKeeper interface. -type MockAccountKeeper struct { - ctrl *gomock.Controller - recorder *MockAccountKeeperMockRecorder -} - -// MockAccountKeeperMockRecorder is the mock recorder for MockAccountKeeper. -type MockAccountKeeperMockRecorder struct { - mock *MockAccountKeeper -} - -// NewMockAccountKeeper creates a new mock instance. -func NewMockAccountKeeper(ctrl *gomock.Controller) *MockAccountKeeper { - mock := &MockAccountKeeper{ctrl: ctrl} - mock.recorder = &MockAccountKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { - return m.recorder -} - -// GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccount", ctx, addr) - ret0, _ := ret[0].(types0.AccountI) - return ret0 -} - -// GetAccount indicates an expected call of GetAccount. -func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) -} - -// GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, name string) types0.ModuleAccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAccount", ctx, name) - ret0, _ := ret[0].(types0.ModuleAccountI) - return ret0 -} - -// GetModuleAccount indicates an expected call of GetModuleAccount. -func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, name interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccount), ctx, name) -} - -// GetModuleAddress mocks base method. -func (m *MockAccountKeeper) GetModuleAddress(name string) types.AccAddress { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetModuleAddress", name) - ret0, _ := ret[0].(types.AccAddress) - return ret0 -} - -// GetModuleAddress indicates an expected call of GetModuleAddress. -func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), name) -} - -// SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types0.ModuleAccountI) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) -} - -// SetModuleAccount indicates an expected call of SetModuleAccount. -func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), arg0, arg1) -} - -// MockBankKeeper is a mock of BankKeeper interface. -type MockBankKeeper struct { - ctrl *gomock.Controller - recorder *MockBankKeeperMockRecorder -} - -// MockBankKeeperMockRecorder is the mock recorder for MockBankKeeper. -type MockBankKeeperMockRecorder struct { - mock *MockBankKeeper -} - -// NewMockBankKeeper creates a new mock instance. -func NewMockBankKeeper(ctrl *gomock.Controller) *MockBankKeeper { - mock := &MockBankKeeper{ctrl: ctrl} - mock.recorder = &MockBankKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBankKeeper) EXPECT() *MockBankKeeperMockRecorder { - return m.recorder -} - -// BlockedAddr mocks base method. -func (m *MockBankKeeper) BlockedAddr(addr types.AccAddress) bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BlockedAddr", addr) - ret0, _ := ret[0].(bool) - return ret0 -} - -// BlockedAddr indicates an expected call of BlockedAddr. -func (mr *MockBankKeeperMockRecorder) BlockedAddr(addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockedAddr", reflect.TypeOf((*MockBankKeeper)(nil).BlockedAddr), addr) -} - -// GetAllBalances mocks base method. -func (m *MockBankKeeper) GetAllBalances(ctx types.Context, addr types.AccAddress) types.Coins { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllBalances", ctx, addr) - ret0, _ := ret[0].(types.Coins) - return ret0 -} - -// GetAllBalances indicates an expected call of GetAllBalances. -func (mr *MockBankKeeperMockRecorder) GetAllBalances(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllBalances", reflect.TypeOf((*MockBankKeeper)(nil).GetAllBalances), ctx, addr) -} - -// SendCoinsFromAccountToModule mocks base method. -func (m *MockBankKeeper) SendCoinsFromAccountToModule(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCoinsFromAccountToModule", ctx, senderAddr, recipientModule, amt) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCoinsFromAccountToModule indicates an expected call of SendCoinsFromAccountToModule. -func (mr *MockBankKeeperMockRecorder) SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, amt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromAccountToModule", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromAccountToModule), ctx, senderAddr, recipientModule, amt) -} - -// SendCoinsFromModuleToAccount mocks base method. -func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCoinsFromModuleToAccount indicates an expected call of SendCoinsFromModuleToAccount. -func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromModuleToAccount", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromModuleToAccount), ctx, senderModule, recipientAddr, amt) -} - -// SendCoinsFromModuleToModule mocks base method. -func (m *MockBankKeeper) SendCoinsFromModuleToModule(ctx types.Context, senderModule, recipientModule string, amt types.Coins) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCoinsFromModuleToModule", ctx, senderModule, recipientModule, amt) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCoinsFromModuleToModule indicates an expected call of SendCoinsFromModuleToModule. -func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToModule(ctx, senderModule, recipientModule, amt interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromModuleToModule", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromModuleToModule), ctx, senderModule, recipientModule, amt) -} - -// SpendableCoins mocks base method. -func (m *MockBankKeeper) SpendableCoins(ctx types.Context, addr types.AccAddress) types.Coins { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SpendableCoins", ctx, addr) - ret0, _ := ret[0].(types.Coins) - return ret0 -} - -// SpendableCoins indicates an expected call of SpendableCoins. -func (mr *MockBankKeeperMockRecorder) SpendableCoins(ctx, addr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpendableCoins", reflect.TypeOf((*MockBankKeeper)(nil).SpendableCoins), ctx, addr) -} - -// MockStakingKeeper is a mock of StakingKeeper interface. -type MockStakingKeeper struct { - ctrl *gomock.Controller - recorder *MockStakingKeeperMockRecorder -} - -// MockStakingKeeperMockRecorder is the mock recorder for MockStakingKeeper. -type MockStakingKeeperMockRecorder struct { - mock *MockStakingKeeper -} - -// NewMockStakingKeeper creates a new mock instance. -func NewMockStakingKeeper(ctrl *gomock.Controller) *MockStakingKeeper { - mock := &MockStakingKeeper{ctrl: ctrl} - mock.recorder = &MockStakingKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { - return m.recorder -} - -// Delegation mocks base method. -func (m *MockStakingKeeper) Delegation(arg0 types.Context, arg1 types.AccAddress, arg2 types.ValAddress) types1.DelegationI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delegation", arg0, arg1, arg2) - ret0, _ := ret[0].(types1.DelegationI) - return ret0 -} - -// Delegation indicates an expected call of Delegation. -func (mr *MockStakingKeeperMockRecorder) Delegation(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delegation", reflect.TypeOf((*MockStakingKeeper)(nil).Delegation), arg0, arg1, arg2) -} - -// GetAllDelegatorDelegations mocks base method. -func (m *MockStakingKeeper) GetAllDelegatorDelegations(ctx types.Context, delegator types.AccAddress) []types1.Delegation { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllDelegatorDelegations", ctx, delegator) - ret0, _ := ret[0].([]types1.Delegation) - return ret0 -} - -// GetAllDelegatorDelegations indicates an expected call of GetAllDelegatorDelegations. -func (mr *MockStakingKeeperMockRecorder) GetAllDelegatorDelegations(ctx, delegator interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllDelegatorDelegations", reflect.TypeOf((*MockStakingKeeper)(nil).GetAllDelegatorDelegations), ctx, delegator) -} - -// GetAllSDKDelegations mocks base method. -func (m *MockStakingKeeper) GetAllSDKDelegations(ctx types.Context) []types1.Delegation { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllSDKDelegations", ctx) - ret0, _ := ret[0].([]types1.Delegation) - return ret0 -} - -// GetAllSDKDelegations indicates an expected call of GetAllSDKDelegations. -func (mr *MockStakingKeeperMockRecorder) GetAllSDKDelegations(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllSDKDelegations", reflect.TypeOf((*MockStakingKeeper)(nil).GetAllSDKDelegations), ctx) -} - -// GetAllValidators mocks base method. -func (m *MockStakingKeeper) GetAllValidators(ctx types.Context) []types1.Validator { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllValidators", ctx) - ret0, _ := ret[0].([]types1.Validator) - return ret0 -} - -// GetAllValidators indicates an expected call of GetAllValidators. -func (mr *MockStakingKeeperMockRecorder) GetAllValidators(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllValidators", reflect.TypeOf((*MockStakingKeeper)(nil).GetAllValidators), ctx) -} - -// IterateDelegations mocks base method. -func (m *MockStakingKeeper) IterateDelegations(ctx types.Context, delegator types.AccAddress, fn func(int64, types1.DelegationI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateDelegations", ctx, delegator, fn) -} - -// IterateDelegations indicates an expected call of IterateDelegations. -func (mr *MockStakingKeeperMockRecorder) IterateDelegations(ctx, delegator, fn interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateDelegations", reflect.TypeOf((*MockStakingKeeper)(nil).IterateDelegations), ctx, delegator, fn) -} - -// IterateValidators mocks base method. -func (m *MockStakingKeeper) IterateValidators(arg0 types.Context, arg1 func(int64, types1.ValidatorI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateValidators", arg0, arg1) -} - -// IterateValidators indicates an expected call of IterateValidators. -func (mr *MockStakingKeeperMockRecorder) IterateValidators(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateValidators", reflect.TypeOf((*MockStakingKeeper)(nil).IterateValidators), arg0, arg1) -} - -// Validator mocks base method. -func (m *MockStakingKeeper) Validator(arg0 types.Context, arg1 types.ValAddress) types1.ValidatorI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Validator", arg0, arg1) - ret0, _ := ret[0].(types1.ValidatorI) - return ret0 -} - -// Validator indicates an expected call of Validator. -func (mr *MockStakingKeeperMockRecorder) Validator(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Validator", reflect.TypeOf((*MockStakingKeeper)(nil).Validator), arg0, arg1) -} - -// ValidatorByConsAddr mocks base method. -func (m *MockStakingKeeper) ValidatorByConsAddr(arg0 types.Context, arg1 types.ConsAddress) types1.ValidatorI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidatorByConsAddr", arg0, arg1) - ret0, _ := ret[0].(types1.ValidatorI) - return ret0 -} - -// ValidatorByConsAddr indicates an expected call of ValidatorByConsAddr. -func (mr *MockStakingKeeperMockRecorder) ValidatorByConsAddr(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidatorByConsAddr", reflect.TypeOf((*MockStakingKeeper)(nil).ValidatorByConsAddr), arg0, arg1) -} - -// MockStakingHooks is a mock of StakingHooks interface. -type MockStakingHooks struct { - ctrl *gomock.Controller - recorder *MockStakingHooksMockRecorder -} - -// MockStakingHooksMockRecorder is the mock recorder for MockStakingHooks. -type MockStakingHooksMockRecorder struct { - mock *MockStakingHooks -} - -// NewMockStakingHooks creates a new mock instance. -func NewMockStakingHooks(ctrl *gomock.Controller) *MockStakingHooks { - mock := &MockStakingHooks{ctrl: ctrl} - mock.recorder = &MockStakingHooksMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStakingHooks) EXPECT() *MockStakingHooksMockRecorder { - return m.recorder -} - -// AfterDelegationModified mocks base method. -func (m *MockStakingHooks) AfterDelegationModified(ctx types.Context, delAddr types.AccAddress, valAddr types.ValAddress) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AfterDelegationModified", ctx, delAddr, valAddr) -} - -// AfterDelegationModified indicates an expected call of AfterDelegationModified. -func (mr *MockStakingHooksMockRecorder) AfterDelegationModified(ctx, delAddr, valAddr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterDelegationModified", reflect.TypeOf((*MockStakingHooks)(nil).AfterDelegationModified), ctx, delAddr, valAddr) -} - -// AfterValidatorCreated mocks base method. -func (m *MockStakingHooks) AfterValidatorCreated(ctx types.Context, valAddr types.ValAddress) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AfterValidatorCreated", ctx, valAddr) -} - -// AfterValidatorCreated indicates an expected call of AfterValidatorCreated. -func (mr *MockStakingHooksMockRecorder) AfterValidatorCreated(ctx, valAddr interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterValidatorCreated", reflect.TypeOf((*MockStakingHooks)(nil).AfterValidatorCreated), ctx, valAddr) -} diff --git a/x/distribution/testutil/staking_helper.go b/x/distribution/testutil/staking_helper.go deleted file mode 100644 index 8235b68eb..000000000 --- a/x/distribution/testutil/staking_helper.go +++ /dev/null @@ -1,129 +0,0 @@ -package testutil - -import ( - "fmt" - - "x/distribution/keeper" - - "cosmossdk.io/math" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func CreateValidator(pk cryptotypes.PubKey, stake math.Int) (stakingtypes.Validator, error) { - valConsAddr := sdk.GetConsAddress(pk) - val, err := stakingtypes.NewValidator(sdk.ValAddress(valConsAddr), pk, stakingtypes.Description{}) - val.Tokens = stake - val.DelegatorShares = math.LegacyNewDecFromInt(val.Tokens) - return val, err -} - -func CallCreateValidatorHooks(ctx sdk.Context, k keeper.Keeper, addr sdk.AccAddress, valAddr sdk.ValAddress) error { - err := k.Hooks().AfterValidatorCreated(ctx, valAddr) - if err != nil { - return err - } - - err = k.Hooks().BeforeDelegationCreated(ctx, addr, valAddr) - if err != nil { - return err - } - - err = k.Hooks().AfterDelegationModified(ctx, addr, valAddr) - if err != nil { - return err - } - - return nil -} - -// SlashValidator copies what x/staking Slash does. It should be used for testing only. -// And it must be updated whenever the original function is updated. -// The passed validator will get its tokens updated. -func SlashValidator( - ctx sdk.Context, - consAddr sdk.ConsAddress, - infractionHeight int64, - power int64, - slashFactor sdk.Dec, - validator *stakingtypes.Validator, - distrKeeper *keeper.Keeper, -) math.Int { - if slashFactor.IsNegative() { - panic(fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor)) - } - - // call the before-modification hook - err := distrKeeper.Hooks().BeforeValidatorModified(ctx, validator.GetOperator()) - if err != nil { - panic(err) - } - - // we simplify this part, as we won't be able to test redelegations or - // unbonding delegations - if infractionHeight != ctx.BlockHeight() { - // if a new test lands here we might need to update this function to handle redelegations and unbonding - // or just make it an integration test. - panic("we can't test any other case here") - } - - slashAmountDec := sdk.NewDecFromInt(validator.Tokens).Mul(sdk.NewDecWithPrec(5, 1)) - slashAmount := slashAmountDec.TruncateInt() - - // cannot decrease balance below zero - tokensToBurn := sdk.MinInt(slashAmount, validator.Tokens) - tokensToBurn = sdk.MaxInt(tokensToBurn, math.ZeroInt()) // defensive. - - // we need to calculate the *effective* slash fraction for distribution - if validator.Tokens.IsPositive() { - effectiveFraction := sdk.NewDecFromInt(tokensToBurn).QuoRoundUp(sdk.NewDecFromInt(validator.Tokens)) - // possible if power has changed - if effectiveFraction.GT(math.LegacyOneDec()) { - effectiveFraction = math.LegacyOneDec() - } - // call the before-slashed hook - distrKeeper.Hooks().BeforeValidatorSlashed(ctx, validator.GetOperator(), effectiveFraction) - } - // Deduct from validator's bonded tokens and update the validator. - // Burn the slashed tokens from the pool account and decrease the total supply. - validator.Tokens = validator.Tokens.Sub(tokensToBurn) - - return tokensToBurn -} - -// Delegate imitate what x/staking Delegate does. It should be used for testing only. -// If a delegation is passed we are simulating an update to a previous delegation, -// if it's nil then we simulate a new delegation. -func Delegate( - ctx sdk.Context, - distrKeeper keeper.Keeper, - delegator sdk.AccAddress, - validator *stakingtypes.Validator, - amount math.Int, - delegation *stakingtypes.Delegation, -) ( - newShares sdk.Dec, - updatedDel stakingtypes.Delegation, - err error, -) { - if delegation != nil { - err = distrKeeper.Hooks().BeforeDelegationSharesModified(ctx, delegator, validator.GetOperator()) - } else { - err = distrKeeper.Hooks().BeforeDelegationCreated(ctx, delegator, validator.GetOperator()) - del := stakingtypes.NewDelegation(delegator, validator.GetOperator(), math.LegacyZeroDec()) - delegation = &del - } - - if err != nil { - return math.LegacyZeroDec(), stakingtypes.Delegation{}, err - } - - // Add tokens from delegation to validator - updateVal, newShares := validator.AddTokensFromDel(amount) - *validator = updateVal - - delegation.Shares = delegation.Shares.Add(newShares) - - return newShares, *delegation, nil -} diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go deleted file mode 100644 index 9d5118a93..000000000 --- a/x/distribution/types/codec.go +++ /dev/null @@ -1,64 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - groupcodec "github.com/cosmos/cosmos-sdk/x/group/codec" -) - -// RegisterLegacyAminoCodec registers the necessary x/distribution interfaces -// and concrete types on the provided LegacyAmino codec. These types are used -// for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgWithdrawDelegatorReward{}, "cosmos-sdk/MsgWithdrawDelegationReward") - legacy.RegisterAminoMsg(cdc, &MsgWithdrawValidatorCommission{}, "cosmos-sdk/MsgWithdrawValCommission") - legacy.RegisterAminoMsg(cdc, &MsgSetWithdrawAddress{}, "cosmos-sdk/MsgModifyWithdrawAddress") - legacy.RegisterAminoMsg(cdc, &MsgFundCommunityPool{}, "cosmos-sdk/MsgFundCommunityPool") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "cosmos-sdk/distribution/MsgUpdateParams") - legacy.RegisterAminoMsg(cdc, &MsgCommunityPoolSpend{}, "cosmos-sdk/distr/MsgCommunityPoolSpend") - - cdc.RegisterConcrete(Params{}, "cosmos-sdk/x/distribution/Params", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations( - (*sdk.Msg)(nil), - &MsgWithdrawDelegatorReward{}, - &MsgWithdrawValidatorCommission{}, - &MsgSetWithdrawAddress{}, - &MsgFundCommunityPool{}, - &MsgUpdateParams{}, - &MsgCommunityPoolSpend{}, - ) - - registry.RegisterImplementations( - (*govtypes.Content)(nil), - &CommunityPoolSpendProposal{}) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - sdk.RegisterLegacyAminoCodec(amino) - - // Register all Amino interfaces and concrete types on the authz and gov Amino codec - // so that this can later be used to properly serialize MsgGrant and MsgExec - // instances. - RegisterLegacyAminoCodec(authzcodec.Amino) - RegisterLegacyAminoCodec(govcodec.Amino) - RegisterLegacyAminoCodec(groupcodec.Amino) -} diff --git a/x/distribution/types/common_test.go b/x/distribution/types/common_test.go deleted file mode 100644 index 4e6ef6b01..000000000 --- a/x/distribution/types/common_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// nolint:deadcode,unused,varcheck -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delPk2 = ed25519.GenPrivKey().PubKey() - delPk3 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - delAddr2 = sdk.AccAddress(delPk2.Address()) - delAddr3 = sdk.AccAddress(delPk3.Address()) - emptyDelAddr sdk.AccAddress - - valPk1 = ed25519.GenPrivKey().PubKey() - valPk2 = ed25519.GenPrivKey().PubKey() - valPk3 = ed25519.GenPrivKey().PubKey() - valAddr1 = sdk.ValAddress(valPk1.Address()) - valAddr2 = sdk.ValAddress(valPk2.Address()) - valAddr3 = sdk.ValAddress(valPk3.Address()) - emptyValAddr sdk.ValAddress - - emptyPubkey cryptotypes.PubKey -) diff --git a/x/distribution/types/delegator.go b/x/distribution/types/delegator.go deleted file mode 100644 index 850878660..000000000 --- a/x/distribution/types/delegator.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// create a new DelegatorStartingInfo -func NewDelegatorStartingInfo(previousPeriod uint64, stake sdk.Dec, height uint64) DelegatorStartingInfo { - return DelegatorStartingInfo{ - PreviousPeriod: previousPeriod, - Stake: stake, - Height: height, - } -} diff --git a/x/distribution/types/distribution.pb.go b/x/distribution/types/distribution.pb.go deleted file mode 100644 index 03ce9ef5f..000000000 --- a/x/distribution/types/distribution.pb.go +++ /dev/null @@ -1,3346 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/distribution/v1beta1/distribution.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/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 - -// Params defines the set of params for the distribution module. -type Params struct { - CommunityTax github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=community_tax,json=communityTax,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"community_tax"` - // Deprecated: The base_proposer_reward field is deprecated and is no longer used - // in the x/distribution module's reward mechanism. - BaseProposerReward github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=base_proposer_reward,json=baseProposerReward,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_proposer_reward"` // Deprecated: Do not use. - // Deprecated: The bonus_proposer_reward field is deprecated and is no longer used - // in the x/distribution module's reward mechanism. - BonusProposerReward github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=bonus_proposer_reward,json=bonusProposerReward,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"bonus_proposer_reward"` // Deprecated: Do not use. - WithdrawAddrEnabled bool `protobuf:"varint,4,opt,name=withdraw_addr_enabled,json=withdrawAddrEnabled,proto3" json:"withdraw_addr_enabled,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetWithdrawAddrEnabled() bool { - if m != nil { - return m.WithdrawAddrEnabled - } - return false -} - -// ValidatorHistoricalRewards represents historical rewards for a validator. -// Height is implicit within the store key. -// Cumulative reward ratio is the sum from the zeroeth period -// until this period of rewards / tokens, per the spec. -// The reference count indicates the number of objects -// which might need to reference this historical entry at any point. -// ReferenceCount = -// -// number of outstanding delegations which ended the associated period (and -// might need to read that record) -// + number of slashes which ended the associated period (and might need to -// read that record) -// + one per validator for the zeroeth period, set on initialization -type ValidatorHistoricalRewards struct { - CumulativeRewardRatio github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=cumulative_reward_ratio,json=cumulativeRewardRatio,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"cumulative_reward_ratio"` - ReferenceCount uint32 `protobuf:"varint,2,opt,name=reference_count,json=referenceCount,proto3" json:"reference_count,omitempty"` -} - -func (m *ValidatorHistoricalRewards) Reset() { *m = ValidatorHistoricalRewards{} } -func (m *ValidatorHistoricalRewards) String() string { return proto.CompactTextString(m) } -func (*ValidatorHistoricalRewards) ProtoMessage() {} -func (*ValidatorHistoricalRewards) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{1} -} -func (m *ValidatorHistoricalRewards) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorHistoricalRewards) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorHistoricalRewards.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 *ValidatorHistoricalRewards) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorHistoricalRewards.Merge(m, src) -} -func (m *ValidatorHistoricalRewards) XXX_Size() int { - return m.Size() -} -func (m *ValidatorHistoricalRewards) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorHistoricalRewards.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorHistoricalRewards proto.InternalMessageInfo - -func (m *ValidatorHistoricalRewards) GetCumulativeRewardRatio() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.CumulativeRewardRatio - } - return nil -} - -func (m *ValidatorHistoricalRewards) GetReferenceCount() uint32 { - if m != nil { - return m.ReferenceCount - } - return 0 -} - -// ValidatorCurrentRewards represents current rewards and current -// period for a validator kept as a running counter and incremented -// each block as long as the validator's tokens remain constant. -type ValidatorCurrentRewards struct { - Rewards github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=rewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"rewards"` - Period uint64 `protobuf:"varint,2,opt,name=period,proto3" json:"period,omitempty"` -} - -func (m *ValidatorCurrentRewards) Reset() { *m = ValidatorCurrentRewards{} } -func (m *ValidatorCurrentRewards) String() string { return proto.CompactTextString(m) } -func (*ValidatorCurrentRewards) ProtoMessage() {} -func (*ValidatorCurrentRewards) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{2} -} -func (m *ValidatorCurrentRewards) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorCurrentRewards) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorCurrentRewards.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 *ValidatorCurrentRewards) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorCurrentRewards.Merge(m, src) -} -func (m *ValidatorCurrentRewards) XXX_Size() int { - return m.Size() -} -func (m *ValidatorCurrentRewards) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorCurrentRewards.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorCurrentRewards proto.InternalMessageInfo - -func (m *ValidatorCurrentRewards) GetRewards() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Rewards - } - return nil -} - -func (m *ValidatorCurrentRewards) GetPeriod() uint64 { - if m != nil { - return m.Period - } - return 0 -} - -// ValidatorAccumulatedCommission represents accumulated commission -// for a validator kept as a running counter, can be withdrawn at any time. -type ValidatorAccumulatedCommission struct { - Commission github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=commission,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"commission"` -} - -func (m *ValidatorAccumulatedCommission) Reset() { *m = ValidatorAccumulatedCommission{} } -func (m *ValidatorAccumulatedCommission) String() string { return proto.CompactTextString(m) } -func (*ValidatorAccumulatedCommission) ProtoMessage() {} -func (*ValidatorAccumulatedCommission) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{3} -} -func (m *ValidatorAccumulatedCommission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorAccumulatedCommission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorAccumulatedCommission.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 *ValidatorAccumulatedCommission) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorAccumulatedCommission.Merge(m, src) -} -func (m *ValidatorAccumulatedCommission) XXX_Size() int { - return m.Size() -} -func (m *ValidatorAccumulatedCommission) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorAccumulatedCommission.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorAccumulatedCommission proto.InternalMessageInfo - -func (m *ValidatorAccumulatedCommission) GetCommission() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Commission - } - return nil -} - -// ValidatorOutstandingRewards represents outstanding (un-withdrawn) rewards -// for a validator inexpensive to track, allows simple sanity checks. -type ValidatorOutstandingRewards struct { - Rewards github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=rewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"rewards"` -} - -func (m *ValidatorOutstandingRewards) Reset() { *m = ValidatorOutstandingRewards{} } -func (m *ValidatorOutstandingRewards) String() string { return proto.CompactTextString(m) } -func (*ValidatorOutstandingRewards) ProtoMessage() {} -func (*ValidatorOutstandingRewards) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{4} -} -func (m *ValidatorOutstandingRewards) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorOutstandingRewards) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorOutstandingRewards.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 *ValidatorOutstandingRewards) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorOutstandingRewards.Merge(m, src) -} -func (m *ValidatorOutstandingRewards) XXX_Size() int { - return m.Size() -} -func (m *ValidatorOutstandingRewards) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorOutstandingRewards.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorOutstandingRewards proto.InternalMessageInfo - -func (m *ValidatorOutstandingRewards) GetRewards() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Rewards - } - return nil -} - -// ValidatorSlashEvent represents a validator slash event. -// Height is implicit within the store key. -// This is needed to calculate appropriate amount of staking tokens -// for delegations which are withdrawn after a slash has occurred. -type ValidatorSlashEvent struct { - ValidatorPeriod uint64 `protobuf:"varint,1,opt,name=validator_period,json=validatorPeriod,proto3" json:"validator_period,omitempty"` - Fraction github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=fraction,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"fraction"` -} - -func (m *ValidatorSlashEvent) Reset() { *m = ValidatorSlashEvent{} } -func (m *ValidatorSlashEvent) String() string { return proto.CompactTextString(m) } -func (*ValidatorSlashEvent) ProtoMessage() {} -func (*ValidatorSlashEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{5} -} -func (m *ValidatorSlashEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorSlashEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorSlashEvent.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 *ValidatorSlashEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorSlashEvent.Merge(m, src) -} -func (m *ValidatorSlashEvent) XXX_Size() int { - return m.Size() -} -func (m *ValidatorSlashEvent) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorSlashEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorSlashEvent proto.InternalMessageInfo - -func (m *ValidatorSlashEvent) GetValidatorPeriod() uint64 { - if m != nil { - return m.ValidatorPeriod - } - return 0 -} - -// ValidatorSlashEvents is a collection of ValidatorSlashEvent messages. -type ValidatorSlashEvents struct { - ValidatorSlashEvents []ValidatorSlashEvent `protobuf:"bytes,1,rep,name=validator_slash_events,json=validatorSlashEvents,proto3" json:"validator_slash_events"` -} - -func (m *ValidatorSlashEvents) Reset() { *m = ValidatorSlashEvents{} } -func (*ValidatorSlashEvents) ProtoMessage() {} -func (*ValidatorSlashEvents) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{6} -} -func (m *ValidatorSlashEvents) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorSlashEvents) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorSlashEvents.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 *ValidatorSlashEvents) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorSlashEvents.Merge(m, src) -} -func (m *ValidatorSlashEvents) XXX_Size() int { - return m.Size() -} -func (m *ValidatorSlashEvents) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorSlashEvents.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorSlashEvents proto.InternalMessageInfo - -func (m *ValidatorSlashEvents) GetValidatorSlashEvents() []ValidatorSlashEvent { - if m != nil { - return m.ValidatorSlashEvents - } - return nil -} - -// FeePool is the global fee pool for distribution. -type FeePool struct { - CommunityPool github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=community_pool,json=communityPool,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"community_pool"` -} - -func (m *FeePool) Reset() { *m = FeePool{} } -func (m *FeePool) String() string { return proto.CompactTextString(m) } -func (*FeePool) ProtoMessage() {} -func (*FeePool) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{7} -} -func (m *FeePool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *FeePool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_FeePool.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 *FeePool) XXX_Merge(src proto.Message) { - xxx_messageInfo_FeePool.Merge(m, src) -} -func (m *FeePool) XXX_Size() int { - return m.Size() -} -func (m *FeePool) XXX_DiscardUnknown() { - xxx_messageInfo_FeePool.DiscardUnknown(m) -} - -var xxx_messageInfo_FeePool proto.InternalMessageInfo - -func (m *FeePool) GetCommunityPool() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.CommunityPool - } - return nil -} - -// CommunityPoolSpendProposal details a proposal for use of community funds, -// together with how many coins are proposed to be spent, and to which -// recipient account. -// -// Deprecated: Do not use. As of the Cosmos SDK release v0.47.x, there is no -// longer a need for an explicit CommunityPoolSpendProposal. To spend community -// pool funds, a simple MsgCommunityPoolSpend can be invoked from the x/gov -// module via a v1 governance proposal. -// -// Deprecated: Do not use. -type CommunityPoolSpendProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Recipient string `protobuf:"bytes,3,opt,name=recipient,proto3" json:"recipient,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *CommunityPoolSpendProposal) Reset() { *m = CommunityPoolSpendProposal{} } -func (*CommunityPoolSpendProposal) ProtoMessage() {} -func (*CommunityPoolSpendProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{8} -} -func (m *CommunityPoolSpendProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolSpendProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolSpendProposal.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 *CommunityPoolSpendProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolSpendProposal.Merge(m, src) -} -func (m *CommunityPoolSpendProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolSpendProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolSpendProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolSpendProposal proto.InternalMessageInfo - -// DelegatorStartingInfo represents the starting info for a delegator reward -// period. It tracks the previous validator period, the delegation's amount of -// staking token, and the creation height (to check later on if any slashes have -// occurred). NOTE: Even though validators are slashed to whole staking tokens, -// the delegators within the validator may be left with less than a full token, -// thus sdk.Dec is used. -type DelegatorStartingInfo struct { - PreviousPeriod uint64 `protobuf:"varint,1,opt,name=previous_period,json=previousPeriod,proto3" json:"previous_period,omitempty"` - Stake github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=stake,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"stake"` - Height uint64 `protobuf:"varint,3,opt,name=height,proto3" json:"creation_height"` -} - -func (m *DelegatorStartingInfo) Reset() { *m = DelegatorStartingInfo{} } -func (m *DelegatorStartingInfo) String() string { return proto.CompactTextString(m) } -func (*DelegatorStartingInfo) ProtoMessage() {} -func (*DelegatorStartingInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{9} -} -func (m *DelegatorStartingInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegatorStartingInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegatorStartingInfo.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 *DelegatorStartingInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegatorStartingInfo.Merge(m, src) -} -func (m *DelegatorStartingInfo) XXX_Size() int { - return m.Size() -} -func (m *DelegatorStartingInfo) XXX_DiscardUnknown() { - xxx_messageInfo_DelegatorStartingInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegatorStartingInfo proto.InternalMessageInfo - -func (m *DelegatorStartingInfo) GetPreviousPeriod() uint64 { - if m != nil { - return m.PreviousPeriod - } - return 0 -} - -func (m *DelegatorStartingInfo) GetHeight() uint64 { - if m != nil { - return m.Height - } - return 0 -} - -// DelegationDelegatorReward represents the properties -// of a delegator's delegation reward. -type DelegationDelegatorReward struct { - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - Reward github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,2,rep,name=reward,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"reward"` -} - -func (m *DelegationDelegatorReward) Reset() { *m = DelegationDelegatorReward{} } -func (m *DelegationDelegatorReward) String() string { return proto.CompactTextString(m) } -func (*DelegationDelegatorReward) ProtoMessage() {} -func (*DelegationDelegatorReward) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{10} -} -func (m *DelegationDelegatorReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegationDelegatorReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegationDelegatorReward.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 *DelegationDelegatorReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegationDelegatorReward.Merge(m, src) -} -func (m *DelegationDelegatorReward) XXX_Size() int { - return m.Size() -} -func (m *DelegationDelegatorReward) XXX_DiscardUnknown() { - xxx_messageInfo_DelegationDelegatorReward.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegationDelegatorReward proto.InternalMessageInfo - -// CommunityPoolSpendProposalWithDeposit defines a CommunityPoolSpendProposal -// with a deposit -type CommunityPoolSpendProposalWithDeposit struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Recipient string `protobuf:"bytes,3,opt,name=recipient,proto3" json:"recipient,omitempty"` - Amount string `protobuf:"bytes,4,opt,name=amount,proto3" json:"amount,omitempty"` - Deposit string `protobuf:"bytes,5,opt,name=deposit,proto3" json:"deposit,omitempty"` -} - -func (m *CommunityPoolSpendProposalWithDeposit) Reset() { *m = CommunityPoolSpendProposalWithDeposit{} } -func (m *CommunityPoolSpendProposalWithDeposit) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolSpendProposalWithDeposit) ProtoMessage() {} -func (*CommunityPoolSpendProposalWithDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_cd78a31ea281a992, []int{11} -} -func (m *CommunityPoolSpendProposalWithDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolSpendProposalWithDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolSpendProposalWithDeposit.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 *CommunityPoolSpendProposalWithDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolSpendProposalWithDeposit.Merge(m, src) -} -func (m *CommunityPoolSpendProposalWithDeposit) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolSpendProposalWithDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolSpendProposalWithDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolSpendProposalWithDeposit proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "cosmos.distribution.v1beta1.Params") - proto.RegisterType((*ValidatorHistoricalRewards)(nil), "cosmos.distribution.v1beta1.ValidatorHistoricalRewards") - proto.RegisterType((*ValidatorCurrentRewards)(nil), "cosmos.distribution.v1beta1.ValidatorCurrentRewards") - proto.RegisterType((*ValidatorAccumulatedCommission)(nil), "cosmos.distribution.v1beta1.ValidatorAccumulatedCommission") - proto.RegisterType((*ValidatorOutstandingRewards)(nil), "cosmos.distribution.v1beta1.ValidatorOutstandingRewards") - proto.RegisterType((*ValidatorSlashEvent)(nil), "cosmos.distribution.v1beta1.ValidatorSlashEvent") - proto.RegisterType((*ValidatorSlashEvents)(nil), "cosmos.distribution.v1beta1.ValidatorSlashEvents") - proto.RegisterType((*FeePool)(nil), "cosmos.distribution.v1beta1.FeePool") - proto.RegisterType((*CommunityPoolSpendProposal)(nil), "cosmos.distribution.v1beta1.CommunityPoolSpendProposal") - proto.RegisterType((*DelegatorStartingInfo)(nil), "cosmos.distribution.v1beta1.DelegatorStartingInfo") - proto.RegisterType((*DelegationDelegatorReward)(nil), "cosmos.distribution.v1beta1.DelegationDelegatorReward") - proto.RegisterType((*CommunityPoolSpendProposalWithDeposit)(nil), "cosmos.distribution.v1beta1.CommunityPoolSpendProposalWithDeposit") -} - -func init() { - proto.RegisterFile("cosmos/distribution/v1beta1/distribution.proto", fileDescriptor_cd78a31ea281a992) -} - -var fileDescriptor_cd78a31ea281a992 = []byte{ - // 992 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x56, 0x4f, 0x6f, 0x1b, 0x45, - 0x14, 0xf7, 0x34, 0x8e, 0x93, 0x4c, 0x69, 0x42, 0x27, 0x4e, 0xea, 0xb8, 0x95, 0x6d, 0xad, 0x44, - 0x49, 0x43, 0x63, 0x93, 0x22, 0x24, 0x64, 0x21, 0xa4, 0xd8, 0x0e, 0x82, 0x53, 0xa3, 0x0d, 0x02, - 0xc4, 0x65, 0x35, 0xde, 0x9d, 0xd8, 0xa3, 0xee, 0xce, 0x2c, 0x33, 0x63, 0x27, 0x3d, 0x70, 0xaf, - 0x7a, 0x00, 0x8e, 0x15, 0xa7, 0x08, 0x2e, 0x15, 0xa7, 0x1c, 0xf2, 0x21, 0x2a, 0x4e, 0x55, 0x0f, - 0x80, 0x2a, 0x14, 0x50, 0x72, 0x08, 0xe2, 0x53, 0xa0, 0xd9, 0x19, 0xaf, 0x9d, 0x10, 0xa2, 0x4a, - 0xad, 0xd5, 0x4b, 0xe2, 0x79, 0x6f, 0xf7, 0xfd, 0xfe, 0xcc, 0x9b, 0x37, 0x0b, 0xab, 0x3e, 0x97, - 0x11, 0x97, 0xb5, 0x80, 0x4a, 0x25, 0x68, 0xbb, 0xa7, 0x28, 0x67, 0xb5, 0xfe, 0x5a, 0x9b, 0x28, - 0xbc, 0x76, 0x2a, 0x58, 0x8d, 0x05, 0x57, 0x1c, 0x5d, 0x37, 0xcf, 0x57, 0x4f, 0xa5, 0xec, 0xf3, - 0xc5, 0x7c, 0x87, 0x77, 0x78, 0xf2, 0x5c, 0x4d, 0xff, 0x32, 0xaf, 0x14, 0x4b, 0x16, 0xa2, 0x8d, - 0x25, 0x49, 0x4b, 0xfb, 0x9c, 0xda, 0x92, 0xc5, 0x25, 0x93, 0xf7, 0xcc, 0x8b, 0xb6, 0xbe, 0x49, - 0x5d, 0xc5, 0x11, 0x65, 0xbc, 0x96, 0xfc, 0x35, 0x21, 0x67, 0x7f, 0x02, 0xe6, 0x36, 0xb1, 0xc0, - 0x91, 0x44, 0x18, 0x5e, 0xf1, 0x79, 0x14, 0xf5, 0x18, 0x55, 0xf7, 0x3d, 0x85, 0x77, 0x0b, 0xa0, - 0x02, 0x96, 0x67, 0x1a, 0x1f, 0x3e, 0x39, 0x2c, 0x67, 0x9e, 0x1f, 0x96, 0x6f, 0x76, 0xa8, 0xea, - 0xf6, 0xda, 0x55, 0x9f, 0x47, 0xb6, 0xaa, 0xfd, 0xb7, 0x2a, 0x83, 0x7b, 0x35, 0x75, 0x3f, 0x26, - 0xb2, 0xda, 0x22, 0xfe, 0xb3, 0x83, 0x55, 0x68, 0x41, 0x5b, 0xc4, 0x77, 0xdf, 0x48, 0x4b, 0x7e, - 0x86, 0x77, 0x51, 0x0c, 0xf3, 0x9a, 0xb6, 0xe6, 0x16, 0x73, 0x49, 0x84, 0x27, 0xc8, 0x0e, 0x16, - 0x41, 0xe1, 0x52, 0x82, 0xf4, 0xd1, 0xcb, 0x20, 0x15, 0x80, 0x8b, 0x74, 0xed, 0x4d, 0x5b, 0xda, - 0x4d, 0x2a, 0x23, 0x01, 0x17, 0xda, 0x9c, 0xf5, 0xe4, 0x7f, 0x20, 0x27, 0x5e, 0x09, 0xe4, 0x7c, - 0x52, 0xfc, 0x0c, 0xe6, 0x1d, 0xb8, 0xb0, 0x43, 0x55, 0x37, 0x10, 0x78, 0xc7, 0xc3, 0x41, 0x20, - 0x3c, 0xc2, 0x70, 0x3b, 0x24, 0x41, 0x21, 0x5b, 0x01, 0xcb, 0xd3, 0xee, 0xfc, 0x20, 0xb9, 0x1e, - 0x04, 0x62, 0xc3, 0xa4, 0xea, 0xb7, 0x1e, 0xed, 0x95, 0x33, 0x0f, 0x4f, 0xf6, 0x57, 0x2a, 0x23, - 0xb8, 0xbb, 0xa7, 0xfb, 0xc8, 0xec, 0x93, 0xf3, 0x2b, 0x80, 0xc5, 0xcf, 0x71, 0x48, 0x03, 0xac, - 0xb8, 0xf8, 0x84, 0x4a, 0xc5, 0x05, 0xf5, 0x71, 0x68, 0xc0, 0x25, 0xfa, 0x16, 0xc0, 0x6b, 0x7e, - 0x2f, 0xea, 0x85, 0x58, 0xd1, 0x3e, 0xb1, 0x72, 0x3d, 0x81, 0x15, 0xe5, 0x05, 0x50, 0x99, 0x58, - 0xbe, 0x7c, 0xe7, 0x86, 0xed, 0xd2, 0xaa, 0xf6, 0x6b, 0xd0, 0x6d, 0x5a, 0x50, 0x93, 0x53, 0xd6, - 0xf8, 0x40, 0x5b, 0xf2, 0xf3, 0x9f, 0xe5, 0x77, 0x5e, 0xcc, 0x12, 0xfd, 0x8e, 0x7c, 0x7c, 0xb2, - 0xbf, 0x02, 0xdc, 0x85, 0x21, 0xac, 0x21, 0xe3, 0x6a, 0x50, 0xf4, 0x36, 0x9c, 0x13, 0x64, 0x9b, - 0x08, 0xc2, 0x7c, 0xe2, 0xf9, 0xbc, 0xc7, 0x54, 0xb2, 0xdf, 0x57, 0xdc, 0xd9, 0x34, 0xdc, 0xd4, - 0x51, 0xe7, 0x27, 0x00, 0xaf, 0xa5, 0xc2, 0x9a, 0x3d, 0x21, 0x08, 0x53, 0x03, 0x55, 0x31, 0x9c, - 0x32, 0x4a, 0xe4, 0x98, 0x45, 0x0c, 0x60, 0xd0, 0x22, 0xcc, 0xc5, 0x44, 0x50, 0x6e, 0xba, 0x33, - 0xeb, 0xda, 0x95, 0xf3, 0x08, 0xc0, 0x52, 0xca, 0x72, 0xdd, 0xb7, 0x9a, 0x49, 0xd0, 0xe4, 0x51, - 0x44, 0xa5, 0xa4, 0x9c, 0xa1, 0x3e, 0x84, 0x7e, 0xba, 0x1a, 0x33, 0xdf, 0x11, 0x24, 0xe7, 0x3b, - 0x00, 0xaf, 0xa7, 0xd4, 0xee, 0xf6, 0x94, 0x54, 0x98, 0x05, 0x94, 0x75, 0x5e, 0x9b, 0x89, 0xce, - 0x0f, 0x00, 0xce, 0xa7, 0x8c, 0xb6, 0x42, 0x2c, 0xbb, 0x1b, 0x7d, 0xc2, 0x14, 0xba, 0x05, 0xdf, - 0xec, 0x0f, 0xc2, 0x9e, 0xb5, 0x19, 0x24, 0x36, 0xcf, 0xa5, 0xf1, 0xcd, 0x24, 0x8c, 0xbe, 0x84, - 0xd3, 0xdb, 0x02, 0xfb, 0xfa, 0x04, 0xd8, 0x39, 0xf1, 0x72, 0x13, 0x29, 0xad, 0xa6, 0xed, 0xca, - 0x9f, 0x43, 0x4e, 0xa2, 0xaf, 0xe1, 0xe2, 0x90, 0x9d, 0xd4, 0x09, 0x8f, 0x24, 0x19, 0x6b, 0xdb, - 0xbb, 0xd5, 0x0b, 0xc6, 0x76, 0xf5, 0x9c, 0x92, 0x8d, 0x19, 0x4d, 0xd9, 0x78, 0x93, 0xef, 0x9f, - 0x03, 0x59, 0xcf, 0xea, 0xf3, 0xef, 0x3c, 0x00, 0x70, 0xea, 0x63, 0x42, 0x36, 0x39, 0x0f, 0xd1, - 0x37, 0x70, 0x76, 0x38, 0x8e, 0x63, 0xce, 0xc3, 0x31, 0xef, 0xd9, 0x70, 0xf8, 0x6b, 0x78, 0xe7, - 0xe1, 0x25, 0x58, 0x6c, 0x8e, 0x46, 0xb6, 0x62, 0xc2, 0x02, 0x33, 0xe9, 0x70, 0x88, 0xf2, 0x70, - 0x52, 0x51, 0x15, 0x12, 0x73, 0x49, 0xb8, 0x66, 0x81, 0x2a, 0xf0, 0x72, 0x40, 0xa4, 0x2f, 0x68, - 0x3c, 0xdc, 0x2e, 0x77, 0x34, 0x84, 0x6e, 0xc0, 0x19, 0x41, 0x7c, 0x1a, 0x53, 0xc2, 0x94, 0x99, - 0xc1, 0xee, 0x30, 0x80, 0xba, 0x30, 0x87, 0xa3, 0x64, 0x42, 0x64, 0x13, 0xad, 0x4b, 0xe7, 0x6a, - 0x4d, 0x84, 0xbe, 0x6f, 0x85, 0x2e, 0xbf, 0x80, 0xd0, 0x11, 0x95, 0xb6, 0x7e, 0xfd, 0xf6, 0x83, - 0xbd, 0x72, 0x46, 0x7b, 0xfe, 0xf7, 0x5e, 0x39, 0xf3, 0xcb, 0xc1, 0x6a, 0xd1, 0x02, 0x75, 0x78, - 0x7f, 0x04, 0x87, 0x29, 0x4d, 0x13, 0x38, 0xcf, 0x01, 0x5c, 0x68, 0x91, 0x90, 0x74, 0x92, 0x6d, - 0x53, 0x58, 0x28, 0xca, 0x3a, 0x9f, 0xb2, 0xed, 0x64, 0xb8, 0xc5, 0x82, 0xf4, 0x29, 0xd7, 0x57, - 0xcc, 0x68, 0x1f, 0xcf, 0x0e, 0xc2, 0xb6, 0x8d, 0x5d, 0x38, 0x29, 0x15, 0xbe, 0x47, 0x5e, 0x49, - 0x0f, 0x9b, 0x52, 0xa8, 0x05, 0x73, 0x5d, 0x42, 0x3b, 0x5d, 0xe3, 0x64, 0xb6, 0x71, 0xfb, 0x9f, - 0xc3, 0xf2, 0x9c, 0x2f, 0x88, 0x1e, 0xbb, 0xcc, 0x33, 0xa9, 0x1f, 0x4f, 0xf6, 0x57, 0xce, 0xc6, - 0xac, 0x15, 0x66, 0xe1, 0xfc, 0x01, 0xe0, 0x92, 0x15, 0x47, 0x39, 0x4b, 0x65, 0xda, 0xcb, 0x6c, - 0x03, 0x5e, 0x1d, 0x9e, 0x05, 0x7d, 0x9b, 0x11, 0x29, 0xed, 0x97, 0x41, 0xe1, 0xd9, 0xc1, 0x6a, - 0xde, 0xb2, 0x5a, 0x37, 0x99, 0x2d, 0x25, 0xf4, 0xbc, 0x19, 0x1e, 0x6e, 0x1b, 0x47, 0x0c, 0xe6, - 0xd2, 0xbb, 0x7e, 0x9c, 0x5d, 0x6c, 0x51, 0xea, 0xd3, 0x76, 0x7f, 0x81, 0xf3, 0x1b, 0x80, 0x6f, - 0xfd, 0x7f, 0x23, 0x7f, 0x41, 0x55, 0xb7, 0x45, 0x62, 0x2e, 0xa9, 0x1a, 0x53, 0x4f, 0x2f, 0x8e, - 0xf4, 0xb4, 0x4e, 0xd9, 0x15, 0x2a, 0xc0, 0xa9, 0xc0, 0x00, 0x17, 0x26, 0x93, 0xc4, 0x60, 0x59, - 0xbf, 0x39, 0xe0, 0x7e, 0x71, 0x5f, 0x36, 0xee, 0x3e, 0x3e, 0x2a, 0x81, 0x27, 0x47, 0x25, 0xf0, - 0xf4, 0xa8, 0x04, 0xfe, 0x3a, 0x2a, 0x81, 0xef, 0x8f, 0x4b, 0x99, 0xa7, 0xc7, 0xa5, 0xcc, 0xef, - 0xc7, 0xa5, 0xcc, 0x57, 0x6b, 0x17, 0x7a, 0x77, 0xe6, 0xd3, 0x22, 0xb1, 0xb2, 0x9d, 0x4b, 0xbe, - 0x09, 0xdf, 0xfb, 0x37, 0x00, 0x00, 0xff, 0xff, 0xb9, 0x9e, 0xb6, 0x03, 0xc6, 0x0a, 0x00, 0x00, -} - -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.CommunityTax.Equal(that1.CommunityTax) { - return false - } - if !this.BaseProposerReward.Equal(that1.BaseProposerReward) { - return false - } - if !this.BonusProposerReward.Equal(that1.BonusProposerReward) { - return false - } - if this.WithdrawAddrEnabled != that1.WithdrawAddrEnabled { - return false - } - return true -} -func (this *ValidatorHistoricalRewards) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorHistoricalRewards) - if !ok { - that2, ok := that.(ValidatorHistoricalRewards) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.CumulativeRewardRatio) != len(that1.CumulativeRewardRatio) { - return false - } - for i := range this.CumulativeRewardRatio { - if !this.CumulativeRewardRatio[i].Equal(&that1.CumulativeRewardRatio[i]) { - return false - } - } - if this.ReferenceCount != that1.ReferenceCount { - return false - } - return true -} -func (this *ValidatorCurrentRewards) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorCurrentRewards) - if !ok { - that2, ok := that.(ValidatorCurrentRewards) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Rewards) != len(that1.Rewards) { - return false - } - for i := range this.Rewards { - if !this.Rewards[i].Equal(&that1.Rewards[i]) { - return false - } - } - if this.Period != that1.Period { - return false - } - return true -} -func (this *ValidatorAccumulatedCommission) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorAccumulatedCommission) - if !ok { - that2, ok := that.(ValidatorAccumulatedCommission) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Commission) != len(that1.Commission) { - return false - } - for i := range this.Commission { - if !this.Commission[i].Equal(&that1.Commission[i]) { - return false - } - } - return true -} -func (this *ValidatorOutstandingRewards) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorOutstandingRewards) - if !ok { - that2, ok := that.(ValidatorOutstandingRewards) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Rewards) != len(that1.Rewards) { - return false - } - for i := range this.Rewards { - if !this.Rewards[i].Equal(&that1.Rewards[i]) { - return false - } - } - return true -} -func (this *ValidatorSlashEvent) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorSlashEvent) - if !ok { - that2, ok := that.(ValidatorSlashEvent) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.ValidatorPeriod != that1.ValidatorPeriod { - return false - } - if !this.Fraction.Equal(that1.Fraction) { - return false - } - return true -} -func (this *ValidatorSlashEvents) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ValidatorSlashEvents) - if !ok { - that2, ok := that.(ValidatorSlashEvents) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.ValidatorSlashEvents) != len(that1.ValidatorSlashEvents) { - return false - } - for i := range this.ValidatorSlashEvents { - if !this.ValidatorSlashEvents[i].Equal(&that1.ValidatorSlashEvents[i]) { - return false - } - } - return true -} -func (this *FeePool) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*FeePool) - if !ok { - that2, ok := that.(FeePool) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.CommunityPool) != len(that1.CommunityPool) { - return false - } - for i := range this.CommunityPool { - if !this.CommunityPool[i].Equal(&that1.CommunityPool[i]) { - return false - } - } - return true -} -func (this *DelegatorStartingInfo) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*DelegatorStartingInfo) - if !ok { - that2, ok := that.(DelegatorStartingInfo) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.PreviousPeriod != that1.PreviousPeriod { - return false - } - if !this.Stake.Equal(that1.Stake) { - return false - } - if this.Height != that1.Height { - return false - } - return true -} -func (this *DelegationDelegatorReward) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*DelegationDelegatorReward) - if !ok { - that2, ok := that.(DelegationDelegatorReward) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.ValidatorAddress != that1.ValidatorAddress { - return false - } - if len(this.Reward) != len(that1.Reward) { - return false - } - for i := range this.Reward { - if !this.Reward[i].Equal(&that1.Reward[i]) { - return false - } - } - return true -} -func (this *CommunityPoolSpendProposalWithDeposit) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CommunityPoolSpendProposalWithDeposit) - if !ok { - that2, ok := that.(CommunityPoolSpendProposalWithDeposit) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Recipient != that1.Recipient { - return false - } - if this.Amount != that1.Amount { - return false - } - if this.Deposit != that1.Deposit { - return false - } - return true -} -func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.WithdrawAddrEnabled { - i-- - if m.WithdrawAddrEnabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - { - size := m.BonusProposerReward.Size() - i -= size - if _, err := m.BonusProposerReward.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.BaseProposerReward.Size() - i -= size - if _, err := m.BaseProposerReward.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.CommunityTax.Size() - i -= size - if _, err := m.CommunityTax.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *ValidatorHistoricalRewards) 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 *ValidatorHistoricalRewards) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorHistoricalRewards) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.ReferenceCount != 0 { - i = encodeVarintDistribution(dAtA, i, uint64(m.ReferenceCount)) - i-- - dAtA[i] = 0x10 - } - if len(m.CumulativeRewardRatio) > 0 { - for iNdEx := len(m.CumulativeRewardRatio) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CumulativeRewardRatio[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ValidatorCurrentRewards) 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 *ValidatorCurrentRewards) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorCurrentRewards) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Period != 0 { - i = encodeVarintDistribution(dAtA, i, uint64(m.Period)) - i-- - dAtA[i] = 0x10 - } - if len(m.Rewards) > 0 { - for iNdEx := len(m.Rewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Rewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ValidatorAccumulatedCommission) 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 *ValidatorAccumulatedCommission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorAccumulatedCommission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Commission) > 0 { - for iNdEx := len(m.Commission) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Commission[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ValidatorOutstandingRewards) 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 *ValidatorOutstandingRewards) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorOutstandingRewards) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Rewards) > 0 { - for iNdEx := len(m.Rewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Rewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ValidatorSlashEvent) 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 *ValidatorSlashEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorSlashEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Fraction.Size() - i -= size - if _, err := m.Fraction.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.ValidatorPeriod != 0 { - i = encodeVarintDistribution(dAtA, i, uint64(m.ValidatorPeriod)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *ValidatorSlashEvents) 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 *ValidatorSlashEvents) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorSlashEvents) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorSlashEvents) > 0 { - for iNdEx := len(m.ValidatorSlashEvents) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ValidatorSlashEvents[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *FeePool) 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 *FeePool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *FeePool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CommunityPool) > 0 { - for iNdEx := len(m.CommunityPool) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CommunityPool[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolSpendProposal) 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 *CommunityPoolSpendProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolSpendProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Recipient) > 0 { - i -= len(m.Recipient) - copy(dAtA[i:], m.Recipient) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Recipient))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *DelegatorStartingInfo) 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 *DelegatorStartingInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegatorStartingInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Height != 0 { - i = encodeVarintDistribution(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x18 - } - { - size := m.Stake.Size() - i -= size - if _, err := m.Stake.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.PreviousPeriod != 0 { - i = encodeVarintDistribution(dAtA, i, uint64(m.PreviousPeriod)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *DelegationDelegatorReward) 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 *DelegationDelegatorReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegationDelegatorReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Reward) > 0 { - for iNdEx := len(m.Reward) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Reward[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDistribution(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolSpendProposalWithDeposit) 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 *CommunityPoolSpendProposalWithDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolSpendProposalWithDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - i -= len(m.Deposit) - copy(dAtA[i:], m.Deposit) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Deposit))) - i-- - dAtA[i] = 0x2a - } - if len(m.Amount) > 0 { - i -= len(m.Amount) - copy(dAtA[i:], m.Amount) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Amount))) - i-- - dAtA[i] = 0x22 - } - if len(m.Recipient) > 0 { - i -= len(m.Recipient) - copy(dAtA[i:], m.Recipient) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Recipient))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintDistribution(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintDistribution(dAtA []byte, offset int, v uint64) int { - offset -= sovDistribution(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.CommunityTax.Size() - n += 1 + l + sovDistribution(uint64(l)) - l = m.BaseProposerReward.Size() - n += 1 + l + sovDistribution(uint64(l)) - l = m.BonusProposerReward.Size() - n += 1 + l + sovDistribution(uint64(l)) - if m.WithdrawAddrEnabled { - n += 2 - } - return n -} - -func (m *ValidatorHistoricalRewards) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CumulativeRewardRatio) > 0 { - for _, e := range m.CumulativeRewardRatio { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - if m.ReferenceCount != 0 { - n += 1 + sovDistribution(uint64(m.ReferenceCount)) - } - return n -} - -func (m *ValidatorCurrentRewards) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Rewards) > 0 { - for _, e := range m.Rewards { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - if m.Period != 0 { - n += 1 + sovDistribution(uint64(m.Period)) - } - return n -} - -func (m *ValidatorAccumulatedCommission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Commission) > 0 { - for _, e := range m.Commission { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *ValidatorOutstandingRewards) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Rewards) > 0 { - for _, e := range m.Rewards { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *ValidatorSlashEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ValidatorPeriod != 0 { - n += 1 + sovDistribution(uint64(m.ValidatorPeriod)) - } - l = m.Fraction.Size() - n += 1 + l + sovDistribution(uint64(l)) - return n -} - -func (m *ValidatorSlashEvents) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.ValidatorSlashEvents) > 0 { - for _, e := range m.ValidatorSlashEvents { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *FeePool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CommunityPool) > 0 { - for _, e := range m.CommunityPool { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolSpendProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Recipient) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *DelegatorStartingInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PreviousPeriod != 0 { - n += 1 + sovDistribution(uint64(m.PreviousPeriod)) - } - l = m.Stake.Size() - n += 1 + l + sovDistribution(uint64(l)) - if m.Height != 0 { - n += 1 + sovDistribution(uint64(m.Height)) - } - return n -} - -func (m *DelegationDelegatorReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - if len(m.Reward) > 0 { - for _, e := range m.Reward { - l = e.Size() - n += 1 + l + sovDistribution(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolSpendProposalWithDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Recipient) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Amount) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - l = len(m.Deposit) - if l > 0 { - n += 1 + l + sovDistribution(uint64(l)) - } - return n -} - -func sovDistribution(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozDistribution(x uint64) (n int) { - return sovDistribution(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) 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 ErrIntOverflowDistribution - } - 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: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CommunityTax", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CommunityTax.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseProposerReward", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseProposerReward.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BonusProposerReward", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BonusProposerReward.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field WithdrawAddrEnabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.WithdrawAddrEnabled = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorHistoricalRewards) 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 ErrIntOverflowDistribution - } - 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: ValidatorHistoricalRewards: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorHistoricalRewards: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CumulativeRewardRatio", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CumulativeRewardRatio = append(m.CumulativeRewardRatio, types.DecCoin{}) - if err := m.CumulativeRewardRatio[len(m.CumulativeRewardRatio)-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 ReferenceCount", wireType) - } - m.ReferenceCount = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ReferenceCount |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorCurrentRewards) 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 ErrIntOverflowDistribution - } - 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: ValidatorCurrentRewards: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorCurrentRewards: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Rewards = append(m.Rewards, types.DecCoin{}) - if err := m.Rewards[len(m.Rewards)-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 Period", wireType) - } - m.Period = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Period |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorAccumulatedCommission) 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 ErrIntOverflowDistribution - } - 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: ValidatorAccumulatedCommission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorAccumulatedCommission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Commission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Commission = append(m.Commission, types.DecCoin{}) - if err := m.Commission[len(m.Commission)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorOutstandingRewards) 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 ErrIntOverflowDistribution - } - 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: ValidatorOutstandingRewards: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorOutstandingRewards: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Rewards = append(m.Rewards, types.DecCoin{}) - if err := m.Rewards[len(m.Rewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorSlashEvent) 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 ErrIntOverflowDistribution - } - 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: ValidatorSlashEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorSlashEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorPeriod", wireType) - } - m.ValidatorPeriod = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ValidatorPeriod |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fraction", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Fraction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorSlashEvents) 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 ErrIntOverflowDistribution - } - 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: ValidatorSlashEvents: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorSlashEvents: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSlashEvents", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorSlashEvents = append(m.ValidatorSlashEvents, ValidatorSlashEvent{}) - if err := m.ValidatorSlashEvents[len(m.ValidatorSlashEvents)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *FeePool) 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 ErrIntOverflowDistribution - } - 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: FeePool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: FeePool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CommunityPool", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CommunityPool = append(m.CommunityPool, types.DecCoin{}) - if err := m.CommunityPool[len(m.CommunityPool)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolSpendProposal) 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 ErrIntOverflowDistribution - } - 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: CommunityPoolSpendProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolSpendProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Recipient = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DelegatorStartingInfo) 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 ErrIntOverflowDistribution - } - 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: DelegatorStartingInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegatorStartingInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousPeriod", wireType) - } - m.PreviousPeriod = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PreviousPeriod |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Stake", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Stake.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DelegationDelegatorReward) 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 ErrIntOverflowDistribution - } - 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: DelegationDelegatorReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegationDelegatorReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reward", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Reward = append(m.Reward, types.DecCoin{}) - if err := m.Reward[len(m.Reward)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolSpendProposalWithDeposit) 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 ErrIntOverflowDistribution - } - 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: CommunityPoolSpendProposalWithDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolSpendProposalWithDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Recipient = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDistribution - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDistribution - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDistribution - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDistribution(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDistribution - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipDistribution(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, ErrIntOverflowDistribution - } - 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, ErrIntOverflowDistribution - } - 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, ErrIntOverflowDistribution - } - 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, ErrInvalidLengthDistribution - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupDistribution - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthDistribution - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthDistribution = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowDistribution = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupDistribution = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/distribution/types/errors.go b/x/distribution/types/errors.go deleted file mode 100644 index 147cfd320..000000000 --- a/x/distribution/types/errors.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// x/distribution module sentinel errors -var ( - ErrEmptyDelegatorAddr = sdkerrors.Register(ModuleName, 2, "delegator address is empty") - ErrEmptyWithdrawAddr = sdkerrors.Register(ModuleName, 3, "withdraw address is empty") - ErrEmptyValidatorAddr = sdkerrors.Register(ModuleName, 4, "validator address is empty") - ErrEmptyDelegationDistInfo = sdkerrors.Register(ModuleName, 5, "no delegation distribution info") - ErrNoValidatorDistInfo = sdkerrors.Register(ModuleName, 6, "no validator distribution info") - ErrNoValidatorCommission = sdkerrors.Register(ModuleName, 7, "no validator commission to withdraw") - ErrSetWithdrawAddrDisabled = sdkerrors.Register(ModuleName, 8, "set withdraw address disabled") - ErrBadDistribution = sdkerrors.Register(ModuleName, 9, "community pool does not have sufficient coins to distribute") - ErrInvalidProposalAmount = sdkerrors.Register(ModuleName, 10, "invalid community pool spend proposal amount") - ErrEmptyProposalRecipient = sdkerrors.Register(ModuleName, 11, "invalid community pool spend proposal recipient") - ErrNoValidatorExists = sdkerrors.Register(ModuleName, 12, "validator does not exist") - ErrNoDelegationExists = sdkerrors.Register(ModuleName, 13, "delegation does not exist") -) diff --git a/x/distribution/types/events.go b/x/distribution/types/events.go deleted file mode 100644 index e0ea70691..000000000 --- a/x/distribution/types/events.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// distribution module event types -const ( - EventTypeSetWithdrawAddress = "set_withdraw_address" - EventTypeRewards = "rewards" - EventTypeCommission = "commission" - EventTypeWithdrawRewards = "withdraw_rewards" - EventTypeWithdrawCommission = "withdraw_commission" - EventTypeProposerReward = "proposer_reward" - - AttributeKeyWithdrawAddress = "withdraw_address" - AttributeKeyValidator = "validator" - AttributeKeyDelegator = "delegator" -) diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go deleted file mode 100644 index 94cea333a..000000000 --- a/x/distribution/types/expected_keepers.go +++ /dev/null @@ -1,58 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI - - // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, types.ModuleAccountI) -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - - BlockedAddr(addr sdk.AccAddress) bool -} - -// StakingKeeper expected staking keeper (noalias) -type StakingKeeper interface { - // iterate through validators by operator address, execute func for each validator - IterateValidators(sdk.Context, - func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - - Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address - ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address - - // Delegation allows for getting a particular delegation for a given validator - // and delegator outside the scope of the staking module. - Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) stakingtypes.DelegationI - - IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress, - fn func(index int64, delegation stakingtypes.DelegationI) (stop bool)) - - GetAllSDKDelegations(ctx sdk.Context) []stakingtypes.Delegation - GetAllValidators(ctx sdk.Context) (validators []stakingtypes.Validator) - GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []stakingtypes.Delegation -} - -// StakingHooks event hooks for staking validator object (noalias) -type StakingHooks interface { - AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) // Must be called when a validator is created - AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) -} diff --git a/x/distribution/types/fee_pool.go b/x/distribution/types/fee_pool.go deleted file mode 100644 index 645afd401..000000000 --- a/x/distribution/types/fee_pool.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// zero fee pool -func InitialFeePool() FeePool { - return FeePool{ - CommunityPool: sdk.DecCoins{}, - } -} - -// ValidateGenesis validates the fee pool for a genesis state -func (f FeePool) ValidateGenesis() error { - if f.CommunityPool.IsAnyNegative() { - return fmt.Errorf("negative CommunityPool in distribution fee pool, is %v", - f.CommunityPool) - } - - return nil -} diff --git a/x/distribution/types/fee_pool_test.go b/x/distribution/types/fee_pool_test.go deleted file mode 100644 index 48ef3c848..000000000 --- a/x/distribution/types/fee_pool_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package types_test - -import ( - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestValidateGenesis(t *testing.T) { - fp := types.InitialFeePool() - require.Nil(t, fp.ValidateGenesis()) - - fp2 := types.FeePool{CommunityPool: sdk.DecCoins{{Denom: "stake", Amount: math.LegacyNewDec(-1)}}} - require.NotNil(t, fp2.ValidateGenesis()) -} diff --git a/x/distribution/types/genesis.go b/x/distribution/types/genesis.go deleted file mode 100644 index 9ceb0737a..000000000 --- a/x/distribution/types/genesis.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -//nolint:interfacer -func NewGenesisState( - params Params, fp FeePool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, - acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord, - cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, slashes []ValidatorSlashEventRecord, -) *GenesisState { - return &GenesisState{ - Params: params, - FeePool: fp, - DelegatorWithdrawInfos: dwis, - PreviousProposer: pp.String(), - OutstandingRewards: r, - ValidatorAccumulatedCommissions: acc, - ValidatorHistoricalRewards: historical, - ValidatorCurrentRewards: cur, - DelegatorStartingInfos: dels, - ValidatorSlashEvents: slashes, - } -} - -// get raw genesis raw message for testing -func DefaultGenesisState() *GenesisState { - return &GenesisState{ - FeePool: InitialFeePool(), - Params: DefaultParams(), - DelegatorWithdrawInfos: []DelegatorWithdrawInfo{}, - PreviousProposer: "", - OutstandingRewards: []ValidatorOutstandingRewardsRecord{}, - ValidatorAccumulatedCommissions: []ValidatorAccumulatedCommissionRecord{}, - ValidatorHistoricalRewards: []ValidatorHistoricalRewardsRecord{}, - ValidatorCurrentRewards: []ValidatorCurrentRewardsRecord{}, - DelegatorStartingInfos: []DelegatorStartingInfoRecord{}, - ValidatorSlashEvents: []ValidatorSlashEventRecord{}, - } -} - -// ValidateGenesis validates the genesis state of distribution genesis input -func ValidateGenesis(gs *GenesisState) error { - if err := gs.Params.ValidateBasic(); err != nil { - return err - } - return gs.FeePool.ValidateGenesis() -} diff --git a/x/distribution/types/genesis.pb.go b/x/distribution/types/genesis.pb.go deleted file mode 100644 index a5a493326..000000000 --- a/x/distribution/types/genesis.pb.go +++ /dev/null @@ -1,2477 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/distribution/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/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 - -// DelegatorWithdrawInfo is the address for where distributions rewards are -// withdrawn to by default this struct is only used at genesis to feed in -// default withdraw addresses. -type DelegatorWithdrawInfo struct { - // delegator_address is the address of the delegator. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` - // withdraw_address is the address to withdraw the delegation rewards to. - WithdrawAddress string `protobuf:"bytes,2,opt,name=withdraw_address,json=withdrawAddress,proto3" json:"withdraw_address,omitempty"` -} - -func (m *DelegatorWithdrawInfo) Reset() { *m = DelegatorWithdrawInfo{} } -func (m *DelegatorWithdrawInfo) String() string { return proto.CompactTextString(m) } -func (*DelegatorWithdrawInfo) ProtoMessage() {} -func (*DelegatorWithdrawInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{0} -} -func (m *DelegatorWithdrawInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegatorWithdrawInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegatorWithdrawInfo.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 *DelegatorWithdrawInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegatorWithdrawInfo.Merge(m, src) -} -func (m *DelegatorWithdrawInfo) XXX_Size() int { - return m.Size() -} -func (m *DelegatorWithdrawInfo) XXX_DiscardUnknown() { - xxx_messageInfo_DelegatorWithdrawInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegatorWithdrawInfo proto.InternalMessageInfo - -// ValidatorOutstandingRewardsRecord is used for import/export via genesis json. -type ValidatorOutstandingRewardsRecord struct { - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // outstanding_rewards represents the outstanding rewards of a validator. - OutstandingRewards github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,2,rep,name=outstanding_rewards,json=outstandingRewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"outstanding_rewards"` -} - -func (m *ValidatorOutstandingRewardsRecord) Reset() { *m = ValidatorOutstandingRewardsRecord{} } -func (m *ValidatorOutstandingRewardsRecord) String() string { return proto.CompactTextString(m) } -func (*ValidatorOutstandingRewardsRecord) ProtoMessage() {} -func (*ValidatorOutstandingRewardsRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{1} -} -func (m *ValidatorOutstandingRewardsRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorOutstandingRewardsRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorOutstandingRewardsRecord.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 *ValidatorOutstandingRewardsRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorOutstandingRewardsRecord.Merge(m, src) -} -func (m *ValidatorOutstandingRewardsRecord) XXX_Size() int { - return m.Size() -} -func (m *ValidatorOutstandingRewardsRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorOutstandingRewardsRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorOutstandingRewardsRecord proto.InternalMessageInfo - -// ValidatorAccumulatedCommissionRecord is used for import / export via genesis -// json. -type ValidatorAccumulatedCommissionRecord struct { - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // accumulated is the accumulated commission of a validator. - Accumulated ValidatorAccumulatedCommission `protobuf:"bytes,2,opt,name=accumulated,proto3" json:"accumulated"` -} - -func (m *ValidatorAccumulatedCommissionRecord) Reset() { *m = ValidatorAccumulatedCommissionRecord{} } -func (m *ValidatorAccumulatedCommissionRecord) String() string { return proto.CompactTextString(m) } -func (*ValidatorAccumulatedCommissionRecord) ProtoMessage() {} -func (*ValidatorAccumulatedCommissionRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{2} -} -func (m *ValidatorAccumulatedCommissionRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorAccumulatedCommissionRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorAccumulatedCommissionRecord.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 *ValidatorAccumulatedCommissionRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorAccumulatedCommissionRecord.Merge(m, src) -} -func (m *ValidatorAccumulatedCommissionRecord) XXX_Size() int { - return m.Size() -} -func (m *ValidatorAccumulatedCommissionRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorAccumulatedCommissionRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorAccumulatedCommissionRecord proto.InternalMessageInfo - -// ValidatorHistoricalRewardsRecord is used for import / export via genesis -// json. -type ValidatorHistoricalRewardsRecord struct { - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // period defines the period the historical rewards apply to. - Period uint64 `protobuf:"varint,2,opt,name=period,proto3" json:"period,omitempty"` - // rewards defines the historical rewards of a validator. - Rewards ValidatorHistoricalRewards `protobuf:"bytes,3,opt,name=rewards,proto3" json:"rewards"` -} - -func (m *ValidatorHistoricalRewardsRecord) Reset() { *m = ValidatorHistoricalRewardsRecord{} } -func (m *ValidatorHistoricalRewardsRecord) String() string { return proto.CompactTextString(m) } -func (*ValidatorHistoricalRewardsRecord) ProtoMessage() {} -func (*ValidatorHistoricalRewardsRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{3} -} -func (m *ValidatorHistoricalRewardsRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorHistoricalRewardsRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorHistoricalRewardsRecord.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 *ValidatorHistoricalRewardsRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorHistoricalRewardsRecord.Merge(m, src) -} -func (m *ValidatorHistoricalRewardsRecord) XXX_Size() int { - return m.Size() -} -func (m *ValidatorHistoricalRewardsRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorHistoricalRewardsRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorHistoricalRewardsRecord proto.InternalMessageInfo - -// ValidatorCurrentRewardsRecord is used for import / export via genesis json. -type ValidatorCurrentRewardsRecord struct { - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // rewards defines the current rewards of a validator. - Rewards ValidatorCurrentRewards `protobuf:"bytes,2,opt,name=rewards,proto3" json:"rewards"` -} - -func (m *ValidatorCurrentRewardsRecord) Reset() { *m = ValidatorCurrentRewardsRecord{} } -func (m *ValidatorCurrentRewardsRecord) String() string { return proto.CompactTextString(m) } -func (*ValidatorCurrentRewardsRecord) ProtoMessage() {} -func (*ValidatorCurrentRewardsRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{4} -} -func (m *ValidatorCurrentRewardsRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorCurrentRewardsRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorCurrentRewardsRecord.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 *ValidatorCurrentRewardsRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorCurrentRewardsRecord.Merge(m, src) -} -func (m *ValidatorCurrentRewardsRecord) XXX_Size() int { - return m.Size() -} -func (m *ValidatorCurrentRewardsRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorCurrentRewardsRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorCurrentRewardsRecord proto.InternalMessageInfo - -// DelegatorStartingInfoRecord used for import / export via genesis json. -type DelegatorStartingInfoRecord struct { - // delegator_address is the address of the delegator. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // starting_info defines the starting info of a delegator. - StartingInfo DelegatorStartingInfo `protobuf:"bytes,3,opt,name=starting_info,json=startingInfo,proto3" json:"starting_info"` -} - -func (m *DelegatorStartingInfoRecord) Reset() { *m = DelegatorStartingInfoRecord{} } -func (m *DelegatorStartingInfoRecord) String() string { return proto.CompactTextString(m) } -func (*DelegatorStartingInfoRecord) ProtoMessage() {} -func (*DelegatorStartingInfoRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{5} -} -func (m *DelegatorStartingInfoRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegatorStartingInfoRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegatorStartingInfoRecord.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 *DelegatorStartingInfoRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegatorStartingInfoRecord.Merge(m, src) -} -func (m *DelegatorStartingInfoRecord) XXX_Size() int { - return m.Size() -} -func (m *DelegatorStartingInfoRecord) XXX_DiscardUnknown() { - xxx_messageInfo_DelegatorStartingInfoRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegatorStartingInfoRecord proto.InternalMessageInfo - -// ValidatorSlashEventRecord is used for import / export via genesis json. -type ValidatorSlashEventRecord struct { - // validator_address is the address of the validator. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // height defines the block height at which the slash event occurred. - Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` - // period is the period of the slash event. - Period uint64 `protobuf:"varint,3,opt,name=period,proto3" json:"period,omitempty"` - // validator_slash_event describes the slash event. - ValidatorSlashEvent ValidatorSlashEvent `protobuf:"bytes,4,opt,name=validator_slash_event,json=validatorSlashEvent,proto3" json:"validator_slash_event"` -} - -func (m *ValidatorSlashEventRecord) Reset() { *m = ValidatorSlashEventRecord{} } -func (m *ValidatorSlashEventRecord) String() string { return proto.CompactTextString(m) } -func (*ValidatorSlashEventRecord) ProtoMessage() {} -func (*ValidatorSlashEventRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_76eed0f9489db580, []int{6} -} -func (m *ValidatorSlashEventRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ValidatorSlashEventRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ValidatorSlashEventRecord.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 *ValidatorSlashEventRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidatorSlashEventRecord.Merge(m, src) -} -func (m *ValidatorSlashEventRecord) XXX_Size() int { - return m.Size() -} -func (m *ValidatorSlashEventRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ValidatorSlashEventRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidatorSlashEventRecord proto.InternalMessageInfo - -// GenesisState defines the distribution module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // fee_pool defines the fee pool at genesis. - FeePool FeePool `protobuf:"bytes,2,opt,name=fee_pool,json=feePool,proto3" json:"fee_pool"` - // fee_pool defines the delegator withdraw infos at genesis. - DelegatorWithdrawInfos []DelegatorWithdrawInfo `protobuf:"bytes,3,rep,name=delegator_withdraw_infos,json=delegatorWithdrawInfos,proto3" json:"delegator_withdraw_infos"` - // fee_pool defines the previous proposer at genesis. - PreviousProposer string `protobuf:"bytes,4,opt,name=previous_proposer,json=previousProposer,proto3" json:"previous_proposer,omitempty"` - // fee_pool defines the outstanding rewards of all validators at genesis. - OutstandingRewards []ValidatorOutstandingRewardsRecord `protobuf:"bytes,5,rep,name=outstanding_rewards,json=outstandingRewards,proto3" json:"outstanding_rewards"` - // fee_pool defines the accumulated commissions of all validators at genesis. - ValidatorAccumulatedCommissions []ValidatorAccumulatedCommissionRecord `protobuf:"bytes,6,rep,name=validator_accumulated_commissions,json=validatorAccumulatedCommissions,proto3" json:"validator_accumulated_commissions"` - // fee_pool defines the historical rewards of all validators at genesis. - ValidatorHistoricalRewards []ValidatorHistoricalRewardsRecord `protobuf:"bytes,7,rep,name=validator_historical_rewards,json=validatorHistoricalRewards,proto3" json:"validator_historical_rewards"` - // fee_pool defines the current rewards of all validators at genesis. - ValidatorCurrentRewards []ValidatorCurrentRewardsRecord `protobuf:"bytes,8,rep,name=validator_current_rewards,json=validatorCurrentRewards,proto3" json:"validator_current_rewards"` - // fee_pool defines the delegator starting infos at genesis. - DelegatorStartingInfos []DelegatorStartingInfoRecord `protobuf:"bytes,9,rep,name=delegator_starting_infos,json=delegatorStartingInfos,proto3" json:"delegator_starting_infos"` - // fee_pool defines the validator slash events at genesis. - ValidatorSlashEvents []ValidatorSlashEventRecord `protobuf:"bytes,10,rep,name=validator_slash_events,json=validatorSlashEvents,proto3" json:"validator_slash_events"` -} - -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_76eed0f9489db580, []int{7} -} -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 init() { - proto.RegisterType((*DelegatorWithdrawInfo)(nil), "cosmos.distribution.v1beta1.DelegatorWithdrawInfo") - proto.RegisterType((*ValidatorOutstandingRewardsRecord)(nil), "cosmos.distribution.v1beta1.ValidatorOutstandingRewardsRecord") - proto.RegisterType((*ValidatorAccumulatedCommissionRecord)(nil), "cosmos.distribution.v1beta1.ValidatorAccumulatedCommissionRecord") - proto.RegisterType((*ValidatorHistoricalRewardsRecord)(nil), "cosmos.distribution.v1beta1.ValidatorHistoricalRewardsRecord") - proto.RegisterType((*ValidatorCurrentRewardsRecord)(nil), "cosmos.distribution.v1beta1.ValidatorCurrentRewardsRecord") - proto.RegisterType((*DelegatorStartingInfoRecord)(nil), "cosmos.distribution.v1beta1.DelegatorStartingInfoRecord") - proto.RegisterType((*ValidatorSlashEventRecord)(nil), "cosmos.distribution.v1beta1.ValidatorSlashEventRecord") - proto.RegisterType((*GenesisState)(nil), "cosmos.distribution.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("cosmos/distribution/v1beta1/genesis.proto", fileDescriptor_76eed0f9489db580) -} - -var fileDescriptor_76eed0f9489db580 = []byte{ - // 921 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xcd, 0x6f, 0x1b, 0x45, - 0x14, 0xf7, 0x38, 0x25, 0x4d, 0xc6, 0x45, 0xb4, 0xdb, 0x34, 0x6c, 0xd2, 0xb2, 0x4e, 0x4b, 0x0f, - 0x05, 0xd4, 0x35, 0x31, 0x08, 0xaa, 0x22, 0x90, 0x62, 0xb7, 0xe5, 0xe3, 0xd2, 0xc8, 0x96, 0x40, - 0x20, 0x24, 0x6b, 0xbc, 0x3b, 0x5e, 0x8f, 0xb0, 0x77, 0xac, 0x99, 0xf1, 0x1a, 0x90, 0x38, 0x70, - 0x02, 0x21, 0x90, 0x38, 0xc2, 0xad, 0xc7, 0x0a, 0x09, 0x89, 0x03, 0x7f, 0x44, 0x25, 0x2e, 0x15, - 0x27, 0x4e, 0x7c, 0x38, 0x07, 0xe0, 0x9f, 0x40, 0x68, 0x67, 0x66, 0x77, 0xc7, 0xda, 0xed, 0xd6, - 0x69, 0x93, 0x4b, 0xe2, 0x9d, 0x79, 0x1f, 0xbf, 0xdf, 0x7b, 0x3f, 0xbd, 0x37, 0xf0, 0x39, 0x8f, - 0xf2, 0x31, 0xe5, 0x0d, 0x9f, 0x70, 0xc1, 0x48, 0x7f, 0x2a, 0x08, 0x0d, 0x1b, 0xd1, 0x6e, 0x1f, - 0x0b, 0xb4, 0xdb, 0x08, 0x70, 0x88, 0x39, 0xe1, 0xee, 0x84, 0x51, 0x41, 0xad, 0xf3, 0xca, 0xd4, - 0x35, 0x4d, 0x5d, 0x6d, 0xba, 0xbd, 0x11, 0xd0, 0x80, 0x4a, 0xbb, 0x46, 0xfc, 0x4b, 0xb9, 0x6c, - 0x3b, 0x3a, 0x7a, 0x1f, 0x71, 0x9c, 0x46, 0xf5, 0x28, 0x09, 0xf5, 0xbd, 0x5b, 0x96, 0x7d, 0x21, - 0x8f, 0xb2, 0xdf, 0x52, 0xf6, 0x3d, 0x95, 0x48, 0xe3, 0x51, 0x57, 0x67, 0xd0, 0x98, 0x84, 0xb4, - 0x21, 0xff, 0xaa, 0xa3, 0x4b, 0x3f, 0x02, 0x78, 0xee, 0x06, 0x1e, 0xe1, 0x00, 0x09, 0xca, 0xde, - 0x23, 0x62, 0xe8, 0x33, 0x34, 0x7b, 0x3b, 0x1c, 0x50, 0xeb, 0x26, 0x3c, 0xe3, 0x27, 0x17, 0x3d, - 0xe4, 0xfb, 0x0c, 0x73, 0x6e, 0x83, 0x1d, 0x70, 0x65, 0xbd, 0x65, 0xff, 0xfa, 0xf3, 0xd5, 0x0d, - 0x1d, 0x79, 0x4f, 0xdd, 0x74, 0x05, 0x23, 0x61, 0xd0, 0x39, 0x9d, 0xba, 0xe8, 0x73, 0xab, 0x0d, - 0x4f, 0xcf, 0x74, 0xd8, 0x34, 0x4a, 0xf5, 0x21, 0x51, 0x9e, 0x4a, 0x3c, 0xf4, 0xf1, 0xf5, 0xb5, - 0x2f, 0xef, 0xd4, 0x2b, 0xff, 0xdc, 0xa9, 0x57, 0x2e, 0xfd, 0x07, 0xe0, 0xc5, 0x77, 0xd1, 0x88, - 0xf8, 0x71, 0x8e, 0xdb, 0x53, 0xc1, 0x05, 0x0a, 0xfd, 0xd8, 0x07, 0xcf, 0x10, 0xf3, 0x79, 0x07, - 0x7b, 0x94, 0xf9, 0x31, 0xf6, 0x28, 0x31, 0x5a, 0x1e, 0x7b, 0xea, 0x92, 0x60, 0xff, 0x02, 0xc0, - 0xb3, 0x34, 0xcb, 0xd1, 0x63, 0x2a, 0x89, 0x5d, 0xdd, 0x59, 0xb9, 0x52, 0x6b, 0x5e, 0xd0, 0x9d, - 0x71, 0xe3, 0xce, 0x25, 0x4d, 0x76, 0x6f, 0x60, 0xaf, 0x4d, 0x49, 0xd8, 0xba, 0x76, 0xef, 0xf7, - 0x7a, 0xe5, 0x87, 0x3f, 0xea, 0x2f, 0x04, 0x44, 0x0c, 0xa7, 0x7d, 0xd7, 0xa3, 0x63, 0xdd, 0x0c, - 0xfd, 0xef, 0x2a, 0xf7, 0x3f, 0x6a, 0x88, 0x4f, 0x26, 0x98, 0x27, 0x3e, 0xfc, 0xee, 0xdf, 0x3f, - 0x3d, 0x0f, 0x3a, 0x16, 0xcd, 0xd1, 0x32, 0x0a, 0xf0, 0x17, 0x80, 0x97, 0xd3, 0x02, 0xec, 0x79, - 0xde, 0x74, 0x3c, 0x1d, 0x21, 0x81, 0xfd, 0x36, 0x1d, 0x8f, 0x09, 0xe7, 0x84, 0x86, 0x47, 0x5b, - 0x83, 0x21, 0xac, 0xa1, 0x2c, 0x8b, 0x6c, 0x5d, 0xad, 0xf9, 0x9a, 0x5b, 0xa2, 0x73, 0xb7, 0x1c, - 0x5e, 0x6b, 0x3d, 0xae, 0x8c, 0xa2, 0x6a, 0x86, 0x36, 0x38, 0xfe, 0x0b, 0xe0, 0x4e, 0x1a, 0xe4, - 0x2d, 0xc2, 0x05, 0x65, 0xc4, 0x43, 0xa3, 0x63, 0xe9, 0xf1, 0x26, 0x5c, 0x9d, 0x60, 0x46, 0xa8, - 0xa2, 0x76, 0xa2, 0xa3, 0xbf, 0xac, 0x0f, 0xe1, 0xc9, 0xa4, 0xdd, 0x2b, 0x92, 0xf3, 0xab, 0xcb, - 0x71, 0xce, 0xc1, 0x35, 0xf9, 0x26, 0x21, 0x0d, 0xae, 0xbf, 0x00, 0xf8, 0x4c, 0xea, 0xdc, 0x9e, - 0x32, 0x86, 0x43, 0x71, 0x2c, 0x44, 0xdf, 0xcf, 0x08, 0xa9, 0x26, 0xbe, 0xbc, 0x1c, 0xa1, 0x45, - 0x4c, 0x0f, 0x61, 0xf3, 0x7d, 0x15, 0x9e, 0x4f, 0xc7, 0x49, 0x57, 0x20, 0x26, 0x48, 0x18, 0xc4, - 0xe3, 0x24, 0xe3, 0x72, 0x14, 0x43, 0xa5, 0xb0, 0x24, 0xd5, 0x43, 0x97, 0xa4, 0x0f, 0x9f, 0xe4, - 0x1a, 0x63, 0x8f, 0x84, 0x03, 0xaa, 0x3b, 0xdd, 0x2c, 0x2d, 0x4c, 0x21, 0x3d, 0xb3, 0x2c, 0xa7, - 0xb8, 0x71, 0x61, 0xd4, 0xe6, 0x9b, 0x2a, 0xdc, 0x4a, 0xab, 0xda, 0x1d, 0x21, 0x3e, 0xbc, 0x19, - 0xc9, 0xc2, 0x1e, 0xb1, 0x9c, 0x87, 0x98, 0x04, 0x43, 0x91, 0xc8, 0x59, 0x7d, 0x19, 0x32, 0x5f, - 0x59, 0x90, 0x39, 0x85, 0xe7, 0xb2, 0xb4, 0x3c, 0x06, 0xd5, 0xc3, 0x31, 0x2a, 0xfb, 0x84, 0x2c, - 0xc5, 0x8b, 0xcb, 0x69, 0x24, 0x63, 0x63, 0x16, 0xe2, 0x6c, 0x94, 0xbf, 0x37, 0xea, 0xf1, 0xf5, - 0x3a, 0x3c, 0xf5, 0xa6, 0xda, 0x9e, 0x5d, 0x81, 0x04, 0xb6, 0x6e, 0xc1, 0xd5, 0x09, 0x62, 0x68, - 0xac, 0x78, 0xd7, 0x9a, 0xcf, 0x96, 0x26, 0xdf, 0x97, 0xa6, 0x66, 0x3e, 0xed, 0x6d, 0xbd, 0x03, - 0xd7, 0x06, 0x18, 0xf7, 0x26, 0x94, 0x8e, 0xb4, 0xd4, 0x2f, 0x97, 0x46, 0xba, 0x85, 0xf1, 0x3e, - 0xa5, 0xa3, 0x05, 0x69, 0x0f, 0xd4, 0x99, 0x35, 0x83, 0x76, 0x26, 0xd8, 0x74, 0x91, 0xc5, 0x62, - 0x89, 0xe7, 0xc2, 0xca, 0xf2, 0x6a, 0x31, 0x77, 0xab, 0x99, 0x69, 0xd3, 0x2f, 0xb2, 0x90, 0x12, - 0x9f, 0x30, 0x1c, 0x11, 0x3a, 0x95, 0xab, 0x7c, 0x42, 0x39, 0x66, 0xb2, 0x29, 0xa5, 0x7a, 0x48, - 0x5c, 0xf6, 0xb5, 0x87, 0xf5, 0x69, 0xf1, 0x06, 0x7b, 0x42, 0x42, 0x7f, 0x63, 0xb9, 0xee, 0x3e, - 0x68, 0xcd, 0x9a, 0x34, 0x0a, 0x96, 0x96, 0xf5, 0x1d, 0x80, 0x17, 0x0d, 0x4d, 0x67, 0xa3, 0xbe, - 0xe7, 0xa5, 0xdb, 0x80, 0xdb, 0xab, 0x12, 0xca, 0xde, 0x63, 0x6c, 0x94, 0x3c, 0x9a, 0x7a, 0x54, - 0xea, 0xc0, 0xad, 0xaf, 0x00, 0xbc, 0x90, 0x41, 0x1b, 0xa6, 0x33, 0x3b, 0x2d, 0xd0, 0x49, 0x89, - 0xea, 0xf5, 0x47, 0x9c, 0xf9, 0x79, 0x44, 0xdb, 0xd1, 0x03, 0x8d, 0xad, 0xcf, 0x01, 0xdc, 0xca, - 0xc0, 0x78, 0x6a, 0xde, 0xa6, 0x48, 0xd6, 0x24, 0x92, 0xeb, 0x8f, 0x32, 0xac, 0xf3, 0x30, 0x9e, - 0x8e, 0x8a, 0x2d, 0xad, 0xcf, 0x4c, 0x9d, 0x2f, 0x0c, 0x45, 0x6e, 0xaf, 0x4b, 0x04, 0xd7, 0x0e, - 0x3f, 0x15, 0xf3, 0xf9, 0x33, 0xb5, 0x9b, 0x76, 0xdc, 0x9a, 0xc1, 0xcd, 0xc2, 0x31, 0xc4, 0x6d, - 0x28, 0x93, 0xbf, 0x72, 0xd8, 0x39, 0x94, 0x4f, 0xbd, 0x51, 0x30, 0x8d, 0x8c, 0xd5, 0xd5, 0xba, - 0x7d, 0x77, 0xee, 0x80, 0x7b, 0x73, 0x07, 0xdc, 0x9f, 0x3b, 0xe0, 0xcf, 0xb9, 0x03, 0xbe, 0x3d, - 0x70, 0x2a, 0xf7, 0x0f, 0x9c, 0xca, 0x6f, 0x07, 0x4e, 0xe5, 0x83, 0xdd, 0xd2, 0x67, 0xdc, 0xc7, - 0x8b, 0xaf, 0x73, 0xf9, 0xaa, 0xeb, 0xaf, 0xca, 0x17, 0xf6, 0x4b, 0xff, 0x07, 0x00, 0x00, 0xff, - 0xff, 0x71, 0x88, 0x91, 0xf2, 0x3f, 0x0c, 0x00, 0x00, -} - -func (m *DelegatorWithdrawInfo) 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 *DelegatorWithdrawInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegatorWithdrawInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.WithdrawAddress) > 0 { - i -= len(m.WithdrawAddress) - copy(dAtA[i:], m.WithdrawAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.WithdrawAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ValidatorOutstandingRewardsRecord) 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 *ValidatorOutstandingRewardsRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorOutstandingRewardsRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.OutstandingRewards) > 0 { - for iNdEx := len(m.OutstandingRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.OutstandingRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ValidatorAccumulatedCommissionRecord) 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 *ValidatorAccumulatedCommissionRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorAccumulatedCommissionRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Accumulated.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ValidatorHistoricalRewardsRecord) 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 *ValidatorHistoricalRewardsRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorHistoricalRewardsRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Rewards.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.Period != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Period)) - i-- - dAtA[i] = 0x10 - } - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ValidatorCurrentRewardsRecord) 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 *ValidatorCurrentRewardsRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorCurrentRewardsRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Rewards.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *DelegatorStartingInfoRecord) 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 *DelegatorStartingInfoRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegatorStartingInfoRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.StartingInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ValidatorSlashEventRecord) 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 *ValidatorSlashEventRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ValidatorSlashEventRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ValidatorSlashEvent.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if m.Period != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Period)) - i-- - dAtA[i] = 0x18 - } - if m.Height != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x10 - } - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -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 len(m.ValidatorSlashEvents) > 0 { - for iNdEx := len(m.ValidatorSlashEvents) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ValidatorSlashEvents[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.DelegatorStartingInfos) > 0 { - for iNdEx := len(m.DelegatorStartingInfos) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorStartingInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.ValidatorCurrentRewards) > 0 { - for iNdEx := len(m.ValidatorCurrentRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ValidatorCurrentRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.ValidatorHistoricalRewards) > 0 { - for iNdEx := len(m.ValidatorHistoricalRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ValidatorHistoricalRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.ValidatorAccumulatedCommissions) > 0 { - for iNdEx := len(m.ValidatorAccumulatedCommissions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ValidatorAccumulatedCommissions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.OutstandingRewards) > 0 { - for iNdEx := len(m.OutstandingRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.OutstandingRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.PreviousProposer) > 0 { - i -= len(m.PreviousProposer) - copy(dAtA[i:], m.PreviousProposer) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.PreviousProposer))) - i-- - dAtA[i] = 0x22 - } - if len(m.DelegatorWithdrawInfos) > 0 { - for iNdEx := len(m.DelegatorWithdrawInfos) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorWithdrawInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.FeePool.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Params.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 *DelegatorWithdrawInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.WithdrawAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - return n -} - -func (m *ValidatorOutstandingRewardsRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.OutstandingRewards) > 0 { - for _, e := range m.OutstandingRewards { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *ValidatorAccumulatedCommissionRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.Accumulated.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *ValidatorHistoricalRewardsRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Period != 0 { - n += 1 + sovGenesis(uint64(m.Period)) - } - l = m.Rewards.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *ValidatorCurrentRewardsRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.Rewards.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *DelegatorStartingInfoRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.StartingInfo.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *ValidatorSlashEventRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Height != 0 { - n += 1 + sovGenesis(uint64(m.Height)) - } - if m.Period != 0 { - n += 1 + sovGenesis(uint64(m.Period)) - } - l = m.ValidatorSlashEvent.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.FeePool.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.DelegatorWithdrawInfos) > 0 { - for _, e := range m.DelegatorWithdrawInfos { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = len(m.PreviousProposer) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.OutstandingRewards) > 0 { - for _, e := range m.OutstandingRewards { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ValidatorAccumulatedCommissions) > 0 { - for _, e := range m.ValidatorAccumulatedCommissions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ValidatorHistoricalRewards) > 0 { - for _, e := range m.ValidatorHistoricalRewards { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ValidatorCurrentRewards) > 0 { - for _, e := range m.ValidatorCurrentRewards { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DelegatorStartingInfos) > 0 { - for _, e := range m.DelegatorStartingInfos { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ValidatorSlashEvents) > 0 { - for _, e := range m.ValidatorSlashEvents { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - 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 *DelegatorWithdrawInfo) 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: DelegatorWithdrawInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegatorWithdrawInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WithdrawAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WithdrawAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorOutstandingRewardsRecord) 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: ValidatorOutstandingRewardsRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorOutstandingRewardsRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OutstandingRewards", 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.OutstandingRewards = append(m.OutstandingRewards, types.DecCoin{}) - if err := m.OutstandingRewards[len(m.OutstandingRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorAccumulatedCommissionRecord) 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: ValidatorAccumulatedCommissionRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorAccumulatedCommissionRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accumulated", 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 - } - if err := m.Accumulated.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorHistoricalRewardsRecord) 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: ValidatorHistoricalRewardsRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorHistoricalRewardsRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Period", wireType) - } - m.Period = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Period |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", 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 - } - if err := m.Rewards.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorCurrentRewardsRecord) 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: ValidatorCurrentRewardsRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorCurrentRewardsRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", 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 - } - if err := m.Rewards.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DelegatorStartingInfoRecord) 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: DelegatorStartingInfoRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegatorStartingInfoRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StartingInfo", 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 - } - if err := m.StartingInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValidatorSlashEventRecord) 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: ValidatorSlashEventRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValidatorSlashEventRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Period", wireType) - } - m.Period = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Period |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSlashEvent", 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 - } - if err := m.ValidatorSlashEvent.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -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 Params", 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 - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeePool", 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 - } - if err := m.FeePool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorWithdrawInfos", 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.DelegatorWithdrawInfos = append(m.DelegatorWithdrawInfos, DelegatorWithdrawInfo{}) - if err := m.DelegatorWithdrawInfos[len(m.DelegatorWithdrawInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousProposer", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PreviousProposer = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OutstandingRewards", 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.OutstandingRewards = append(m.OutstandingRewards, ValidatorOutstandingRewardsRecord{}) - if err := m.OutstandingRewards[len(m.OutstandingRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAccumulatedCommissions", 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.ValidatorAccumulatedCommissions = append(m.ValidatorAccumulatedCommissions, ValidatorAccumulatedCommissionRecord{}) - if err := m.ValidatorAccumulatedCommissions[len(m.ValidatorAccumulatedCommissions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorHistoricalRewards", 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.ValidatorHistoricalRewards = append(m.ValidatorHistoricalRewards, ValidatorHistoricalRewardsRecord{}) - if err := m.ValidatorHistoricalRewards[len(m.ValidatorHistoricalRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorCurrentRewards", 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.ValidatorCurrentRewards = append(m.ValidatorCurrentRewards, ValidatorCurrentRewardsRecord{}) - if err := m.ValidatorCurrentRewards[len(m.ValidatorCurrentRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorStartingInfos", 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.DelegatorStartingInfos = append(m.DelegatorStartingInfos, DelegatorStartingInfoRecord{}) - if err := m.DelegatorStartingInfos[len(m.DelegatorStartingInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSlashEvents", 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.ValidatorSlashEvents = append(m.ValidatorSlashEvents, ValidatorSlashEventRecord{}) - if err := m.ValidatorSlashEvents[len(m.ValidatorSlashEvents)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (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/distribution/types/keys.go b/x/distribution/types/keys.go deleted file mode 100644 index 07fb3d6e2..000000000 --- a/x/distribution/types/keys.go +++ /dev/null @@ -1,216 +0,0 @@ -package types - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/kv" -) - -const ( - // ModuleName is the module name constant used in many places - ModuleName = "distribution" - - // StoreKey is the store key string for distribution - StoreKey = ModuleName - - // RouterKey is the message route for distribution - RouterKey = ModuleName -) - -// Keys for distribution store -// Items are stored with the following key: values -// -// - 0x00: FeePol -// -// - 0x01: sdk.ConsAddress -// -// - 0x02: ValidatorOutstandingRewards -// -// - 0x03: sdk.AccAddress -// -// - 0x04: DelegatorStartingInfo -// -// - 0x05: ValidatorHistoricalRewards -// -// - 0x06: ValidatorCurrentRewards -// -// - 0x07: ValidatorCurrentCommission -// -// - 0x08: ValidatorSlashEvent -// -// - 0x09: Params -var ( - FeePoolKey = []byte{0x00} // key for global distribution state - ProposerKey = []byte{0x01} // key for the proposer operator address - ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards - - DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address - DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info - ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake - ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards - ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission - ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction - - ParamsKey = []byte{0x09} // key for distribution module params -) - -// GetValidatorOutstandingRewardsAddress creates an address from a validator's outstanding rewards key. -func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - // key is in the format: - // 0x02 - - // Remove prefix and address length. - kv.AssertKeyAtLeastLength(key, 3) - addr := key[2:] - kv.AssertKeyLength(addr, int(key[1])) - - return sdk.ValAddress(addr) -} - -// GetDelegatorWithdrawInfoAddress creates an address from a delegator's withdraw info key. -func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { - // key is in the format: - // 0x03 - - // Remove prefix and address length. - kv.AssertKeyAtLeastLength(key, 3) - addr := key[2:] - kv.AssertKeyLength(addr, int(key[1])) - - return sdk.AccAddress(addr) -} - -// GetDelegatorStartingInfoAddresses creates the addresses from a delegator starting info key. -func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { - // key is in the format: - // 0x04 - kv.AssertKeyAtLeastLength(key, 2) - valAddrLen := int(key[1]) - kv.AssertKeyAtLeastLength(key, 3+valAddrLen) - valAddr = sdk.ValAddress(key[2 : 2+valAddrLen]) - delAddrLen := int(key[2+valAddrLen]) - kv.AssertKeyAtLeastLength(key, 4+valAddrLen) - delAddr = sdk.AccAddress(key[3+valAddrLen:]) - kv.AssertKeyLength(delAddr.Bytes(), delAddrLen) - - return -} - -// GetValidatorHistoricalRewardsAddressPeriod creates the address & period from a validator's historical rewards key. -func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { - // key is in the format: - // 0x05 - kv.AssertKeyAtLeastLength(key, 2) - valAddrLen := int(key[1]) - kv.AssertKeyAtLeastLength(key, 3+valAddrLen) - valAddr = sdk.ValAddress(key[2 : 2+valAddrLen]) - b := key[2+valAddrLen:] - kv.AssertKeyLength(b, 8) - period = binary.LittleEndian.Uint64(b) - return -} - -// GetValidatorCurrentRewardsAddress creates the address from a validator's current rewards key. -func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - // key is in the format: - // 0x06: ValidatorCurrentRewards - - // Remove prefix and address length. - kv.AssertKeyAtLeastLength(key, 3) - addr := key[2:] - kv.AssertKeyLength(addr, int(key[1])) - - return sdk.ValAddress(addr) -} - -// GetValidatorAccumulatedCommissionAddress creates the address from a validator's accumulated commission key. -func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { - // key is in the format: - // 0x07: ValidatorCurrentRewards - - // Remove prefix and address length. - kv.AssertKeyAtLeastLength(key, 3) - addr := key[2:] - kv.AssertKeyLength(addr, int(key[1])) - - return sdk.ValAddress(addr) -} - -// GetValidatorSlashEventAddressHeight creates the height from a validator's slash event key. -func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { - // key is in the format: - // 0x08: ValidatorSlashEvent - kv.AssertKeyAtLeastLength(key, 2) - valAddrLen := int(key[1]) - kv.AssertKeyAtLeastLength(key, 3+valAddrLen) - valAddr = key[2 : 2+valAddrLen] - startB := 2 + valAddrLen - kv.AssertKeyAtLeastLength(key, startB+9) - b := key[startB : startB+8] // the next 8 bytes represent the height - height = binary.BigEndian.Uint64(b) - return -} - -// GetValidatorOutstandingRewardsKey creates the outstanding rewards key for a validator. -func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { - return append(ValidatorOutstandingRewardsPrefix, address.MustLengthPrefix(valAddr.Bytes())...) -} - -// GetDelegatorWithdrawAddrKey creates the key for a delegator's withdraw addr. -func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { - return append(DelegatorWithdrawAddrPrefix, address.MustLengthPrefix(delAddr.Bytes())...) -} - -// GetDelegatorStartingInfoKey creates the key for a delegator's starting info. -func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, address.MustLengthPrefix(v.Bytes())...), address.MustLengthPrefix(d.Bytes())...) -} - -// GetValidatorHistoricalRewardsPrefix creates the prefix key for a validator's historical rewards. -func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { - return append(ValidatorHistoricalRewardsPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -// GetValidatorHistoricalRewardsKey creates the key for a validator's historical rewards. -func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, k) - return append(append(ValidatorHistoricalRewardsPrefix, address.MustLengthPrefix(v.Bytes())...), b...) -} - -// GetValidatorCurrentRewardsKey creates the key for a validator's current rewards. -func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { - return append(ValidatorCurrentRewardsPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -// GetValidatorAccumulatedCommissionKey creates the key for a validator's current commission. -func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { - return append(ValidatorAccumulatedCommissionPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -// GetValidatorSlashEventPrefix creates the prefix key for a validator's slash fractions. -func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { - return append(ValidatorSlashEventPrefix, address.MustLengthPrefix(v.Bytes())...) -} - -// GetValidatorSlashEventKeyPrefix creates the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height). -func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { - heightBz := make([]byte, 8) - binary.BigEndian.PutUint64(heightBz, height) - - return append( - ValidatorSlashEventPrefix, - append(address.MustLengthPrefix(v.Bytes()), heightBz...)..., - ) -} - -// GetValidatorSlashEventKey creates the key for a validator's slash fraction. -func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte { - periodBz := make([]byte, 8) - binary.BigEndian.PutUint64(periodBz, period) - prefix := GetValidatorSlashEventKeyPrefix(v, height) - - return append(prefix, periodBz...) -} diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go deleted file mode 100644 index ee1660db6..000000000 --- a/x/distribution/types/msg.go +++ /dev/null @@ -1,226 +0,0 @@ -package types - -import ( - "errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// distribution message types -const ( - TypeMsgSetWithdrawAddress = "set_withdraw_address" - TypeMsgWithdrawDelegatorReward = "withdraw_delegator_reward" - TypeMsgWithdrawValidatorCommission = "withdraw_validator_commission" - TypeMsgFundCommunityPool = "fund_community_pool" - TypeMsgUpdateParams = "update_params" - TypeMsgCommunityPoolSpend = "community_pool_spend" -) - -// Verify interface at compile time -var ( - _ sdk.Msg = (*MsgSetWithdrawAddress)(nil) - _ sdk.Msg = (*MsgWithdrawDelegatorReward)(nil) - _ sdk.Msg = (*MsgWithdrawValidatorCommission)(nil) - _ sdk.Msg = (*MsgUpdateParams)(nil) - _ sdk.Msg = (*MsgCommunityPoolSpend)(nil) -) - -func NewMsgSetWithdrawAddress(delAddr, withdrawAddr sdk.AccAddress) *MsgSetWithdrawAddress { - return &MsgSetWithdrawAddress{ - DelegatorAddress: delAddr.String(), - WithdrawAddress: withdrawAddr.String(), - } -} - -func (msg MsgSetWithdrawAddress) Route() string { return ModuleName } -func (msg MsgSetWithdrawAddress) Type() string { return TypeMsgSetWithdrawAddress } - -// Return address that must sign over msg.GetSignBytes() -func (msg MsgSetWithdrawAddress) GetSigners() []sdk.AccAddress { - delegator, _ := sdk.AccAddressFromBech32(msg.DelegatorAddress) - return []sdk.AccAddress{delegator} -} - -// get the bytes for the message signer to sign on -func (msg MsgSetWithdrawAddress) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// quick validity check -func (msg MsgSetWithdrawAddress) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.AccAddressFromBech32(msg.WithdrawAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid withdraw address: %s", err) - } - - return nil -} - -func NewMsgWithdrawDelegatorReward(delAddr sdk.AccAddress, valAddr sdk.ValAddress) *MsgWithdrawDelegatorReward { - return &MsgWithdrawDelegatorReward{ - DelegatorAddress: delAddr.String(), - ValidatorAddress: valAddr.String(), - } -} - -func (msg MsgWithdrawDelegatorReward) Route() string { return ModuleName } -func (msg MsgWithdrawDelegatorReward) Type() string { return TypeMsgWithdrawDelegatorReward } - -// Return address that must sign over msg.GetSignBytes() -func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { - delegator, _ := sdk.AccAddressFromBech32(msg.DelegatorAddress) - return []sdk.AccAddress{delegator} -} - -// get the bytes for the message signer to sign on -func (msg MsgWithdrawDelegatorReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// quick validity check -func (msg MsgWithdrawDelegatorReward) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.DelegatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid delegator address: %s", err) - } - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - return nil -} - -func NewMsgWithdrawValidatorCommission(valAddr sdk.ValAddress) *MsgWithdrawValidatorCommission { - return &MsgWithdrawValidatorCommission{ - ValidatorAddress: valAddr.String(), - } -} - -func (msg MsgWithdrawValidatorCommission) Route() string { return ModuleName } -func (msg MsgWithdrawValidatorCommission) Type() string { return TypeMsgWithdrawValidatorCommission } - -// Return address that must sign over msg.GetSignBytes() -func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { - valAddr, _ := sdk.ValAddressFromBech32(msg.ValidatorAddress) - return []sdk.AccAddress{sdk.AccAddress(valAddr)} -} - -// get the bytes for the message signer to sign on -func (msg MsgWithdrawValidatorCommission) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// quick validity check -func (msg MsgWithdrawValidatorCommission) ValidateBasic() error { - if _, err := sdk.ValAddressFromBech32(msg.ValidatorAddress); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid validator address: %s", err) - } - return nil -} - -// NewMsgFundCommunityPool returns a new MsgFundCommunityPool with a sender and -// a funding amount. -func NewMsgFundCommunityPool(amount sdk.Coins, depositor sdk.AccAddress) *MsgFundCommunityPool { - return &MsgFundCommunityPool{ - Amount: amount, - Depositor: depositor.String(), - } -} - -// Route returns the MsgFundCommunityPool message route. -func (msg MsgFundCommunityPool) Route() string { return ModuleName } - -// Type returns the MsgFundCommunityPool message type. -func (msg MsgFundCommunityPool) Type() string { return TypeMsgFundCommunityPool } - -// GetSigners returns the signer addresses that are expected to sign the result -// of GetSignBytes. -func (msg MsgFundCommunityPool) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// GetSignBytes returns the raw bytes for a MsgFundCommunityPool message that -// the expected signer needs to sign. -func (msg MsgFundCommunityPool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// ValidateBasic performs basic MsgFundCommunityPool message validation. -func (msg MsgFundCommunityPool) ValidateBasic() error { - if !msg.Amount.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) - } - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid depositor address: %s", err) - } - return nil -} - -// Route returns the MsgUpdateParams message route. -func (msg MsgUpdateParams) Route() string { return ModuleName } - -// Type returns the MsgUpdateParams message type. -func (msg MsgUpdateParams) Type() string { return TypeMsgUpdateParams } - -// GetSigners returns the signer addresses that are expected to sign the result -// of GetSignBytes. -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - authority, _ := sdk.AccAddressFromBech32(msg.Authority) - return []sdk.AccAddress{authority} -} - -// GetSignBytes returns the raw bytes for a MsgUpdateParams message that -// the expected signer needs to sign. -func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// ValidateBasic performs basic MsgUpdateParams message validation. -func (msg MsgUpdateParams) ValidateBasic() error { - if (!msg.Params.BaseProposerReward.IsNil() && !msg.Params.BaseProposerReward.IsZero()) || - (!msg.Params.BonusProposerReward.IsNil() && !msg.Params.BonusProposerReward.IsZero()) { - return errors.New("base and bonus proposer reward are deprecated fields and should not be used") - } - - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Params.ValidateBasic() -} - -// Route returns the MsgCommunityPoolSpend message route. -func (msg MsgCommunityPoolSpend) Route() string { return ModuleName } - -// Type returns the MsgCommunityPoolSpend message type. -func (msg MsgCommunityPoolSpend) Type() string { return TypeMsgCommunityPoolSpend } - -// GetSigners returns the signer addresses that are expected to sign the result -// of GetSignBytes, which is the authority. -func (msg MsgCommunityPoolSpend) GetSigners() []sdk.AccAddress { - authority, _ := sdk.AccAddressFromBech32(msg.Authority) - return []sdk.AccAddress{authority} -} - -// GetSignBytes returns the raw bytes for a MsgCommunityPoolSpend message that -// the expected signer needs to sign. -func (msg MsgCommunityPoolSpend) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// ValidateBasic performs basic MsgCommunityPoolSpend message validation. -func (msg MsgCommunityPoolSpend) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) - } - - return msg.Amount.Validate() -} diff --git a/x/distribution/types/msg_test.go b/x/distribution/types/msg_test.go deleted file mode 100644 index 324626178..000000000 --- a/x/distribution/types/msg_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// test ValidateBasic for MsgSetWithdrawAddress -func TestMsgSetWithdrawAddress(t *testing.T) { - tests := []struct { - delegatorAddr sdk.AccAddress - withdrawAddr sdk.AccAddress - expectPass bool - }{ - {delAddr1, delAddr2, true}, - {delAddr1, delAddr1, true}, - {emptyDelAddr, delAddr1, false}, - {delAddr1, emptyDelAddr, false}, - {emptyDelAddr, emptyDelAddr, false}, - } - - for i, tc := range tests { - msg := NewMsgSetWithdrawAddress(tc.delegatorAddr, tc.withdrawAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgWithdrawDelegatorReward -func TestMsgWithdrawDelegatorReward(t *testing.T) { - tests := []struct { - delegatorAddr sdk.AccAddress - validatorAddr sdk.ValAddress - expectPass bool - }{ - {delAddr1, valAddr1, true}, - {emptyDelAddr, valAddr1, false}, - {delAddr1, emptyValAddr, false}, - {emptyDelAddr, emptyValAddr, false}, - } - for i, tc := range tests { - msg := NewMsgWithdrawDelegatorReward(tc.delegatorAddr, tc.validatorAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgWithdrawValidatorCommission -func TestMsgWithdrawValidatorCommission(t *testing.T) { - tests := []struct { - validatorAddr sdk.ValAddress - expectPass bool - }{ - {valAddr1, true}, - {emptyValAddr, false}, - } - for i, tc := range tests { - msg := NewMsgWithdrawValidatorCommission(tc.validatorAddr) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} - -// test ValidateBasic for MsgDepositIntoCommunityPool -func TestMsgDepositIntoCommunityPool(t *testing.T) { - tests := []struct { - amount sdk.Coins - depositor sdk.AccAddress - expectPass bool - }{ - {sdk.NewCoins(sdk.NewInt64Coin("uatom", 10000)), sdk.AccAddress{}, false}, - {sdk.Coins{sdk.NewInt64Coin("uatom", 10), sdk.NewInt64Coin("uatom", 10)}, delAddr1, false}, - {sdk.NewCoins(sdk.NewInt64Coin("uatom", 1000)), delAddr1, true}, - } - for i, tc := range tests { - msg := NewMsgFundCommunityPool(tc.amount, tc.depositor) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test index: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test index: %v", i) - } - } -} diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go deleted file mode 100644 index 97e085631..000000000 --- a/x/distribution/types/params.go +++ /dev/null @@ -1,64 +0,0 @@ -package types - -import ( - "fmt" - - "cosmossdk.io/math" - "sigs.k8s.io/yaml" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultParams returns default distribution parameters -func DefaultParams() Params { - return Params{ - CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% - BaseProposerReward: sdk.ZeroDec(), // deprecated - BonusProposerReward: sdk.ZeroDec(), // deprecated - WithdrawAddrEnabled: true, - } -} - -func (p Params) String() string { - out, _ := yaml.Marshal(p) - return string(out) -} - -// ValidateBasic performs basic validation on distribution parameters. -func (p Params) ValidateBasic() error { - if p.CommunityTax.IsNegative() || p.CommunityTax.GT(math.LegacyOneDec()) { - return fmt.Errorf( - "community tax should be non-negative and less than one: %s", p.CommunityTax, - ) - } - - return nil -} - -func validateCommunityTax(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNil() { - return fmt.Errorf("community tax must be not nil") - } - if v.IsNegative() { - return fmt.Errorf("community tax must be positive: %s", v) - } - if v.GT(math.LegacyOneDec()) { - return fmt.Errorf("community tax too large: %s", v) - } - - return nil -} - -func validateWithdrawAddrEnabled(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go deleted file mode 100644 index 2ea34f965..000000000 --- a/x/distribution/types/params_internal_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package types - -import ( - "testing" - - "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func Test_validateAuxFuncs(t *testing.T) { - type args struct { - i interface{} - } - tests := []struct { - name string - args args - wantErr bool - }{ - {"wrong type", args{10.5}, true}, - {"empty sdk.Dec", args{sdk.Dec{}}, true}, - {"negative", args{math.LegacyNewDec(-1)}, true}, - {"one dec", args{math.LegacyNewDec(1)}, false}, - {"two dec", args{math.LegacyNewDec(2)}, true}, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.wantErr, validateCommunityTax(tt.args.i) != nil) - }) - } -} diff --git a/x/distribution/types/params_legacy.go b/x/distribution/types/params_legacy.go deleted file mode 100644 index 4805e8bd8..000000000 --- a/x/distribution/types/params_legacy.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -// Parameter keys -var ( - ParamStoreKeyCommunityTax = []byte("communitytax") - ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") -) - -// Deprecated: ParamKeyTable returns the parameter key table. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Deprecated: ParamSetPairs returns the parameter set pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(ParamStoreKeyCommunityTax, &p.CommunityTax, validateCommunityTax), - paramtypes.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, &p.WithdrawAddrEnabled, validateWithdrawAddrEnabled), - } -} diff --git a/x/distribution/types/params_test.go b/x/distribution/types/params_test.go deleted file mode 100644 index 654b39827..000000000 --- a/x/distribution/types/params_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestParams_ValidateBasic(t *testing.T) { - toDec := sdk.MustNewDecFromStr - - type fields struct { - CommunityTax sdk.Dec - BaseProposerReward sdk.Dec - BonusProposerReward sdk.Dec - WithdrawAddrEnabled bool - } - tests := []struct { - name string - fields fields - wantErr bool - }{ - {"success", fields{toDec("0.1"), toDec("0"), toDec("0"), false}, false}, - {"negative community tax", fields{toDec("-0.1"), toDec("0"), toDec("0"), false}, true}, - {"negative base proposer reward (must not matter)", fields{toDec("0.1"), toDec("0"), toDec("-0.1"), false}, false}, - {"negative bonus proposer reward (must not matter)", fields{toDec("0.1"), toDec("0"), toDec("-0.1"), false}, false}, - {"total sum greater than 1 (must not matter)", fields{toDec("0.2"), toDec("0.5"), toDec("0.4"), false}, false}, - {"community tax greater than 1", fields{toDec("1.1"), toDec("0"), toDec("0"), false}, true}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - p := types.Params{ - CommunityTax: tt.fields.CommunityTax, - WithdrawAddrEnabled: tt.fields.WithdrawAddrEnabled, - } - if err := p.ValidateBasic(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func TestDefaultParams(t *testing.T) { - require.NoError(t, types.DefaultParams().ValidateBasic()) -} diff --git a/x/distribution/types/proposal.go b/x/distribution/types/proposal.go deleted file mode 100644 index 84dce599f..000000000 --- a/x/distribution/types/proposal.go +++ /dev/null @@ -1,48 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// GetTitle returns the title of a community pool spend proposal. -func (csp *CommunityPoolSpendProposal) GetTitle() string { return csp.Title } - -// GetDescription returns the description of a community pool spend proposal. -func (csp *CommunityPoolSpendProposal) GetDescription() string { return csp.Description } - -// GetDescription returns the routing key of a community pool spend proposal. -func (csp *CommunityPoolSpendProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool spend proposal. -func (csp *CommunityPoolSpendProposal) ProposalType() string { return "CommunityPoolSpend" } - -// ValidateBasic runs basic stateless validity checks -func (csp *CommunityPoolSpendProposal) ValidateBasic() error { - err := govtypes.ValidateAbstract(csp) - if err != nil { - return err - } - if !csp.Amount.IsValid() { - return ErrInvalidProposalAmount - } - if csp.Recipient == "" { - return ErrEmptyProposalRecipient - } - - return nil -} - -// String implements the Stringer interface. -func (csp CommunityPoolSpendProposal) String() string { - var b strings.Builder - fmt.Fprintf(&b, `Community Pool Spend Proposal: - Title: %s - Description: %s - Recipient: %s - Amount: %s -`, csp.Title, csp.Description, csp.Recipient, csp.Amount) - return b.String() -} diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go deleted file mode 100644 index fb9fd4677..000000000 --- a/x/distribution/types/querier.go +++ /dev/null @@ -1,94 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// querier keys -const ( - QueryParams = "params" - QueryValidatorOutstandingRewards = "validator_outstanding_rewards" - QueryValidatorCommission = "validator_commission" - QueryValidatorSlashes = "validator_slashes" - QueryDelegationRewards = "delegation_rewards" - QueryDelegatorTotalRewards = "delegator_total_rewards" - QueryDelegatorValidators = "delegator_validators" - QueryWithdrawAddr = "withdraw_addr" - QueryCommunityPool = "community_pool" -) - -// params for query 'custom/distr/validator_outstanding_rewards' -type QueryValidatorOutstandingRewardsParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address" yaml:"validator_address"` -} - -// creates a new instance of QueryValidatorOutstandingRewardsParams -func NewQueryValidatorOutstandingRewardsParams(validatorAddr sdk.ValAddress) QueryValidatorOutstandingRewardsParams { - return QueryValidatorOutstandingRewardsParams{ - ValidatorAddress: validatorAddr, - } -} - -// params for query 'custom/distr/validator_commission' -type QueryValidatorCommissionParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address" yaml:"validator_address"` -} - -// creates a new instance of QueryValidatorCommissionParams -func NewQueryValidatorCommissionParams(validatorAddr sdk.ValAddress) QueryValidatorCommissionParams { - return QueryValidatorCommissionParams{ - ValidatorAddress: validatorAddr, - } -} - -// params for query 'custom/distr/validator_slashes' -type QueryValidatorSlashesParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address" yaml:"validator_address"` - StartingHeight uint64 `json:"starting_height" yaml:"starting_height"` - EndingHeight uint64 `json:"ending_height" yaml:"ending_height"` -} - -// creates a new instance of QueryValidatorSlashesParams -func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { - return QueryValidatorSlashesParams{ - ValidatorAddress: validatorAddr, - StartingHeight: startingHeight, - EndingHeight: endingHeight, - } -} - -// params for query 'custom/distr/delegation_rewards' -type QueryDelegationRewardsParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address" yaml:"delegator_address"` - ValidatorAddress sdk.ValAddress `json:"validator_address" yaml:"validator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegationRewardsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryDelegationRewardsParams { - return QueryDelegationRewardsParams{ - DelegatorAddress: delegatorAddr, - ValidatorAddress: validatorAddr, - } -} - -// params for query 'custom/distr/delegator_total_rewards' and 'custom/distr/delegator_validators' -type QueryDelegatorParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address" yaml:"delegator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { - return QueryDelegatorParams{ - DelegatorAddress: delegatorAddr, - } -} - -// params for query 'custom/distr/withdraw_addr' -type QueryDelegatorWithdrawAddrParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address" yaml:"delegator_address"` -} - -// NewQueryDelegatorWithdrawAddrParams creates a new instance of QueryDelegatorWithdrawAddrParams. -func NewQueryDelegatorWithdrawAddrParams(delegatorAddr sdk.AccAddress) QueryDelegatorWithdrawAddrParams { - return QueryDelegatorWithdrawAddrParams{DelegatorAddress: delegatorAddr} -} diff --git a/x/distribution/types/query.go b/x/distribution/types/query.go deleted file mode 100644 index 38f6c0a35..000000000 --- a/x/distribution/types/query.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// QueryDelegatorTotalRewardsResponse defines the properties of -// QueryDelegatorTotalRewards query's response. -type QueryDelegatorTotalRewardsResponse struct { - Rewards []DelegationDelegatorReward `json:"rewards" yaml:"rewards"` - Total sdk.DecCoins `json:"total" yaml:"total"` -} - -// NewQueryDelegatorTotalRewardsResponse constructs a QueryDelegatorTotalRewardsResponse -func NewQueryDelegatorTotalRewardsResponse(rewards []DelegationDelegatorReward, total sdk.DecCoins) QueryDelegatorTotalRewardsResponse { - return QueryDelegatorTotalRewardsResponse{Rewards: rewards, Total: total} -} - -func (res QueryDelegatorTotalRewardsResponse) String() string { - out := "Delegator Total Rewards:\n" - out += " Rewards:" - for _, reward := range res.Rewards { - out += fmt.Sprintf(` - ValidatorAddress: %s - Reward: %s`, reward.ValidatorAddress, reward.Reward) - } - out += fmt.Sprintf("\n Total: %s\n", res.Total) - return strings.TrimSpace(out) -} - -// NewDelegationDelegatorReward constructs a DelegationDelegatorReward. -// -//nolint:interfacer -func NewDelegationDelegatorReward(valAddr sdk.ValAddress, reward sdk.DecCoins) DelegationDelegatorReward { - return DelegationDelegatorReward{ValidatorAddress: valAddr.String(), Reward: reward} -} diff --git a/x/distribution/types/query.pb.go b/x/distribution/types/query.pb.go deleted file mode 100644 index 65fd996eb..000000000 --- a/x/distribution/types/query.pb.go +++ /dev/null @@ -1,4422 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/distribution/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - 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 - -// QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.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 *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // params defines the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.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 *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryValidatorDistributionInfoRequest is the request type for the Query/ValidatorDistributionInfo RPC method. -type QueryValidatorDistributionInfoRequest struct { - // validator_address defines the validator address to query for. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *QueryValidatorDistributionInfoRequest) Reset() { *m = QueryValidatorDistributionInfoRequest{} } -func (m *QueryValidatorDistributionInfoRequest) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorDistributionInfoRequest) ProtoMessage() {} -func (*QueryValidatorDistributionInfoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{2} -} -func (m *QueryValidatorDistributionInfoRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorDistributionInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorDistributionInfoRequest.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 *QueryValidatorDistributionInfoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorDistributionInfoRequest.Merge(m, src) -} -func (m *QueryValidatorDistributionInfoRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorDistributionInfoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorDistributionInfoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorDistributionInfoRequest proto.InternalMessageInfo - -func (m *QueryValidatorDistributionInfoRequest) GetValidatorAddress() string { - if m != nil { - return m.ValidatorAddress - } - return "" -} - -// QueryValidatorDistributionInfoResponse is the response type for the Query/ValidatorDistributionInfo RPC method. -type QueryValidatorDistributionInfoResponse struct { - // operator_address defines the validator operator address. - OperatorAddress string `protobuf:"bytes,1,opt,name=operator_address,json=operatorAddress,proto3" json:"operator_address,omitempty"` - // self_bond_rewards defines the self delegations rewards. - SelfBondRewards github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,2,rep,name=self_bond_rewards,json=selfBondRewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"self_bond_rewards"` - // commission defines the commission the validator received. - Commission github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,3,rep,name=commission,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"commission"` -} - -func (m *QueryValidatorDistributionInfoResponse) Reset() { - *m = QueryValidatorDistributionInfoResponse{} -} -func (m *QueryValidatorDistributionInfoResponse) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorDistributionInfoResponse) ProtoMessage() {} -func (*QueryValidatorDistributionInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{3} -} -func (m *QueryValidatorDistributionInfoResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorDistributionInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorDistributionInfoResponse.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 *QueryValidatorDistributionInfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorDistributionInfoResponse.Merge(m, src) -} -func (m *QueryValidatorDistributionInfoResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorDistributionInfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorDistributionInfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorDistributionInfoResponse proto.InternalMessageInfo - -func (m *QueryValidatorDistributionInfoResponse) GetOperatorAddress() string { - if m != nil { - return m.OperatorAddress - } - return "" -} - -func (m *QueryValidatorDistributionInfoResponse) GetSelfBondRewards() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.SelfBondRewards - } - return nil -} - -func (m *QueryValidatorDistributionInfoResponse) GetCommission() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Commission - } - return nil -} - -// QueryValidatorOutstandingRewardsRequest is the request type for the -// Query/ValidatorOutstandingRewards RPC method. -type QueryValidatorOutstandingRewardsRequest struct { - // validator_address defines the validator address to query for. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *QueryValidatorOutstandingRewardsRequest) Reset() { - *m = QueryValidatorOutstandingRewardsRequest{} -} -func (m *QueryValidatorOutstandingRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorOutstandingRewardsRequest) ProtoMessage() {} -func (*QueryValidatorOutstandingRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{4} -} -func (m *QueryValidatorOutstandingRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorOutstandingRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorOutstandingRewardsRequest.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 *QueryValidatorOutstandingRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorOutstandingRewardsRequest.Merge(m, src) -} -func (m *QueryValidatorOutstandingRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorOutstandingRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorOutstandingRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorOutstandingRewardsRequest proto.InternalMessageInfo - -func (m *QueryValidatorOutstandingRewardsRequest) GetValidatorAddress() string { - if m != nil { - return m.ValidatorAddress - } - return "" -} - -// QueryValidatorOutstandingRewardsResponse is the response type for the -// Query/ValidatorOutstandingRewards RPC method. -type QueryValidatorOutstandingRewardsResponse struct { - Rewards ValidatorOutstandingRewards `protobuf:"bytes,1,opt,name=rewards,proto3" json:"rewards"` -} - -func (m *QueryValidatorOutstandingRewardsResponse) Reset() { - *m = QueryValidatorOutstandingRewardsResponse{} -} -func (m *QueryValidatorOutstandingRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorOutstandingRewardsResponse) ProtoMessage() {} -func (*QueryValidatorOutstandingRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{5} -} -func (m *QueryValidatorOutstandingRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorOutstandingRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorOutstandingRewardsResponse.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 *QueryValidatorOutstandingRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorOutstandingRewardsResponse.Merge(m, src) -} -func (m *QueryValidatorOutstandingRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorOutstandingRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorOutstandingRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorOutstandingRewardsResponse proto.InternalMessageInfo - -func (m *QueryValidatorOutstandingRewardsResponse) GetRewards() ValidatorOutstandingRewards { - if m != nil { - return m.Rewards - } - return ValidatorOutstandingRewards{} -} - -// QueryValidatorCommissionRequest is the request type for the -// Query/ValidatorCommission RPC method -type QueryValidatorCommissionRequest struct { - // validator_address defines the validator address to query for. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *QueryValidatorCommissionRequest) Reset() { *m = QueryValidatorCommissionRequest{} } -func (m *QueryValidatorCommissionRequest) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorCommissionRequest) ProtoMessage() {} -func (*QueryValidatorCommissionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{6} -} -func (m *QueryValidatorCommissionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorCommissionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorCommissionRequest.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 *QueryValidatorCommissionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorCommissionRequest.Merge(m, src) -} -func (m *QueryValidatorCommissionRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorCommissionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorCommissionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorCommissionRequest proto.InternalMessageInfo - -func (m *QueryValidatorCommissionRequest) GetValidatorAddress() string { - if m != nil { - return m.ValidatorAddress - } - return "" -} - -// QueryValidatorCommissionResponse is the response type for the -// Query/ValidatorCommission RPC method -type QueryValidatorCommissionResponse struct { - // commission defines the commission the validator received. - Commission ValidatorAccumulatedCommission `protobuf:"bytes,1,opt,name=commission,proto3" json:"commission"` -} - -func (m *QueryValidatorCommissionResponse) Reset() { *m = QueryValidatorCommissionResponse{} } -func (m *QueryValidatorCommissionResponse) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorCommissionResponse) ProtoMessage() {} -func (*QueryValidatorCommissionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{7} -} -func (m *QueryValidatorCommissionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorCommissionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorCommissionResponse.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 *QueryValidatorCommissionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorCommissionResponse.Merge(m, src) -} -func (m *QueryValidatorCommissionResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorCommissionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorCommissionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorCommissionResponse proto.InternalMessageInfo - -func (m *QueryValidatorCommissionResponse) GetCommission() ValidatorAccumulatedCommission { - if m != nil { - return m.Commission - } - return ValidatorAccumulatedCommission{} -} - -// QueryValidatorSlashesRequest is the request type for the -// Query/ValidatorSlashes RPC method -type QueryValidatorSlashesRequest struct { - // validator_address defines the validator address to query for. - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` - // starting_height defines the optional starting height to query the slashes. - StartingHeight uint64 `protobuf:"varint,2,opt,name=starting_height,json=startingHeight,proto3" json:"starting_height,omitempty"` - // starting_height defines the optional ending height to query the slashes. - EndingHeight uint64 `protobuf:"varint,3,opt,name=ending_height,json=endingHeight,proto3" json:"ending_height,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,4,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryValidatorSlashesRequest) Reset() { *m = QueryValidatorSlashesRequest{} } -func (m *QueryValidatorSlashesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorSlashesRequest) ProtoMessage() {} -func (*QueryValidatorSlashesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{8} -} -func (m *QueryValidatorSlashesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorSlashesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorSlashesRequest.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 *QueryValidatorSlashesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorSlashesRequest.Merge(m, src) -} -func (m *QueryValidatorSlashesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorSlashesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorSlashesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorSlashesRequest proto.InternalMessageInfo - -// QueryValidatorSlashesResponse is the response type for the -// Query/ValidatorSlashes RPC method. -type QueryValidatorSlashesResponse struct { - // slashes defines the slashes the validator received. - Slashes []ValidatorSlashEvent `protobuf:"bytes,1,rep,name=slashes,proto3" json:"slashes"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryValidatorSlashesResponse) Reset() { *m = QueryValidatorSlashesResponse{} } -func (m *QueryValidatorSlashesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryValidatorSlashesResponse) ProtoMessage() {} -func (*QueryValidatorSlashesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{9} -} -func (m *QueryValidatorSlashesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryValidatorSlashesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryValidatorSlashesResponse.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 *QueryValidatorSlashesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryValidatorSlashesResponse.Merge(m, src) -} -func (m *QueryValidatorSlashesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryValidatorSlashesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryValidatorSlashesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryValidatorSlashesResponse proto.InternalMessageInfo - -func (m *QueryValidatorSlashesResponse) GetSlashes() []ValidatorSlashEvent { - if m != nil { - return m.Slashes - } - return nil -} - -func (m *QueryValidatorSlashesResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDelegationRewardsRequest is the request type for the -// Query/DelegationRewards RPC method. -type QueryDelegationRewardsRequest struct { - // delegator_address defines the delegator address to query for. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` - // validator_address defines the validator address to query for. - ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *QueryDelegationRewardsRequest) Reset() { *m = QueryDelegationRewardsRequest{} } -func (m *QueryDelegationRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegationRewardsRequest) ProtoMessage() {} -func (*QueryDelegationRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{10} -} -func (m *QueryDelegationRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegationRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegationRewardsRequest.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 *QueryDelegationRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegationRewardsRequest.Merge(m, src) -} -func (m *QueryDelegationRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegationRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegationRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegationRewardsRequest proto.InternalMessageInfo - -// QueryDelegationRewardsResponse is the response type for the -// Query/DelegationRewards RPC method. -type QueryDelegationRewardsResponse struct { - // rewards defines the rewards accrued by a delegation. - Rewards github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=rewards,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"rewards"` -} - -func (m *QueryDelegationRewardsResponse) Reset() { *m = QueryDelegationRewardsResponse{} } -func (m *QueryDelegationRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegationRewardsResponse) ProtoMessage() {} -func (*QueryDelegationRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{11} -} -func (m *QueryDelegationRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegationRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegationRewardsResponse.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 *QueryDelegationRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegationRewardsResponse.Merge(m, src) -} -func (m *QueryDelegationRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegationRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegationRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegationRewardsResponse proto.InternalMessageInfo - -func (m *QueryDelegationRewardsResponse) GetRewards() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Rewards - } - return nil -} - -// QueryDelegationTotalRewardsRequest is the request type for the -// Query/DelegationTotalRewards RPC method. -type QueryDelegationTotalRewardsRequest struct { - // delegator_address defines the delegator address to query for. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` -} - -func (m *QueryDelegationTotalRewardsRequest) Reset() { *m = QueryDelegationTotalRewardsRequest{} } -func (m *QueryDelegationTotalRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegationTotalRewardsRequest) ProtoMessage() {} -func (*QueryDelegationTotalRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{12} -} -func (m *QueryDelegationTotalRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegationTotalRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegationTotalRewardsRequest.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 *QueryDelegationTotalRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegationTotalRewardsRequest.Merge(m, src) -} -func (m *QueryDelegationTotalRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegationTotalRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegationTotalRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegationTotalRewardsRequest proto.InternalMessageInfo - -// QueryDelegationTotalRewardsResponse is the response type for the -// Query/DelegationTotalRewards RPC method. -type QueryDelegationTotalRewardsResponse struct { - // rewards defines all the rewards accrued by a delegator. - Rewards []DelegationDelegatorReward `protobuf:"bytes,1,rep,name=rewards,proto3" json:"rewards"` - // total defines the sum of all the rewards. - Total github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,2,rep,name=total,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"total"` -} - -func (m *QueryDelegationTotalRewardsResponse) Reset() { *m = QueryDelegationTotalRewardsResponse{} } -func (m *QueryDelegationTotalRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegationTotalRewardsResponse) ProtoMessage() {} -func (*QueryDelegationTotalRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{13} -} -func (m *QueryDelegationTotalRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegationTotalRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegationTotalRewardsResponse.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 *QueryDelegationTotalRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegationTotalRewardsResponse.Merge(m, src) -} -func (m *QueryDelegationTotalRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegationTotalRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegationTotalRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegationTotalRewardsResponse proto.InternalMessageInfo - -func (m *QueryDelegationTotalRewardsResponse) GetRewards() []DelegationDelegatorReward { - if m != nil { - return m.Rewards - } - return nil -} - -func (m *QueryDelegationTotalRewardsResponse) GetTotal() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Total - } - return nil -} - -// QueryDelegatorValidatorsRequest is the request type for the -// Query/DelegatorValidators RPC method. -type QueryDelegatorValidatorsRequest struct { - // delegator_address defines the delegator address to query for. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` -} - -func (m *QueryDelegatorValidatorsRequest) Reset() { *m = QueryDelegatorValidatorsRequest{} } -func (m *QueryDelegatorValidatorsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatorValidatorsRequest) ProtoMessage() {} -func (*QueryDelegatorValidatorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{14} -} -func (m *QueryDelegatorValidatorsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatorValidatorsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatorValidatorsRequest.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 *QueryDelegatorValidatorsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatorValidatorsRequest.Merge(m, src) -} -func (m *QueryDelegatorValidatorsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatorValidatorsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatorValidatorsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatorValidatorsRequest proto.InternalMessageInfo - -// QueryDelegatorValidatorsResponse is the response type for the -// Query/DelegatorValidators RPC method. -type QueryDelegatorValidatorsResponse struct { - // validators defines the validators a delegator is delegating for. - Validators []string `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` -} - -func (m *QueryDelegatorValidatorsResponse) Reset() { *m = QueryDelegatorValidatorsResponse{} } -func (m *QueryDelegatorValidatorsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatorValidatorsResponse) ProtoMessage() {} -func (*QueryDelegatorValidatorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{15} -} -func (m *QueryDelegatorValidatorsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatorValidatorsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatorValidatorsResponse.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 *QueryDelegatorValidatorsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatorValidatorsResponse.Merge(m, src) -} -func (m *QueryDelegatorValidatorsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatorValidatorsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatorValidatorsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatorValidatorsResponse proto.InternalMessageInfo - -// QueryDelegatorWithdrawAddressRequest is the request type for the -// Query/DelegatorWithdrawAddress RPC method. -type QueryDelegatorWithdrawAddressRequest struct { - // delegator_address defines the delegator address to query for. - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` -} - -func (m *QueryDelegatorWithdrawAddressRequest) Reset() { *m = QueryDelegatorWithdrawAddressRequest{} } -func (m *QueryDelegatorWithdrawAddressRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatorWithdrawAddressRequest) ProtoMessage() {} -func (*QueryDelegatorWithdrawAddressRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{16} -} -func (m *QueryDelegatorWithdrawAddressRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatorWithdrawAddressRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatorWithdrawAddressRequest.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 *QueryDelegatorWithdrawAddressRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatorWithdrawAddressRequest.Merge(m, src) -} -func (m *QueryDelegatorWithdrawAddressRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatorWithdrawAddressRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatorWithdrawAddressRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatorWithdrawAddressRequest proto.InternalMessageInfo - -// QueryDelegatorWithdrawAddressResponse is the response type for the -// Query/DelegatorWithdrawAddress RPC method. -type QueryDelegatorWithdrawAddressResponse struct { - // withdraw_address defines the delegator address to query for. - WithdrawAddress string `protobuf:"bytes,1,opt,name=withdraw_address,json=withdrawAddress,proto3" json:"withdraw_address,omitempty"` -} - -func (m *QueryDelegatorWithdrawAddressResponse) Reset() { *m = QueryDelegatorWithdrawAddressResponse{} } -func (m *QueryDelegatorWithdrawAddressResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatorWithdrawAddressResponse) ProtoMessage() {} -func (*QueryDelegatorWithdrawAddressResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{17} -} -func (m *QueryDelegatorWithdrawAddressResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatorWithdrawAddressResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatorWithdrawAddressResponse.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 *QueryDelegatorWithdrawAddressResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatorWithdrawAddressResponse.Merge(m, src) -} -func (m *QueryDelegatorWithdrawAddressResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatorWithdrawAddressResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatorWithdrawAddressResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatorWithdrawAddressResponse proto.InternalMessageInfo - -// QueryCommunityPoolRequest is the request type for the Query/CommunityPool RPC -// method. -type QueryCommunityPoolRequest struct { -} - -func (m *QueryCommunityPoolRequest) Reset() { *m = QueryCommunityPoolRequest{} } -func (m *QueryCommunityPoolRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCommunityPoolRequest) ProtoMessage() {} -func (*QueryCommunityPoolRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{18} -} -func (m *QueryCommunityPoolRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommunityPoolRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommunityPoolRequest.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 *QueryCommunityPoolRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommunityPoolRequest.Merge(m, src) -} -func (m *QueryCommunityPoolRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCommunityPoolRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommunityPoolRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommunityPoolRequest proto.InternalMessageInfo - -// QueryCommunityPoolResponse is the response type for the Query/CommunityPool -// RPC method. -type QueryCommunityPoolResponse struct { - // pool defines community pool's coins. - Pool github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=pool,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"pool"` -} - -func (m *QueryCommunityPoolResponse) Reset() { *m = QueryCommunityPoolResponse{} } -func (m *QueryCommunityPoolResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCommunityPoolResponse) ProtoMessage() {} -func (*QueryCommunityPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5efd02cbc06efdc9, []int{19} -} -func (m *QueryCommunityPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCommunityPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCommunityPoolResponse.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 *QueryCommunityPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCommunityPoolResponse.Merge(m, src) -} -func (m *QueryCommunityPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCommunityPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCommunityPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCommunityPoolResponse proto.InternalMessageInfo - -func (m *QueryCommunityPoolResponse) GetPool() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Pool - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.distribution.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.distribution.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryValidatorDistributionInfoRequest)(nil), "cosmos.distribution.v1beta1.QueryValidatorDistributionInfoRequest") - proto.RegisterType((*QueryValidatorDistributionInfoResponse)(nil), "cosmos.distribution.v1beta1.QueryValidatorDistributionInfoResponse") - proto.RegisterType((*QueryValidatorOutstandingRewardsRequest)(nil), "cosmos.distribution.v1beta1.QueryValidatorOutstandingRewardsRequest") - proto.RegisterType((*QueryValidatorOutstandingRewardsResponse)(nil), "cosmos.distribution.v1beta1.QueryValidatorOutstandingRewardsResponse") - proto.RegisterType((*QueryValidatorCommissionRequest)(nil), "cosmos.distribution.v1beta1.QueryValidatorCommissionRequest") - proto.RegisterType((*QueryValidatorCommissionResponse)(nil), "cosmos.distribution.v1beta1.QueryValidatorCommissionResponse") - proto.RegisterType((*QueryValidatorSlashesRequest)(nil), "cosmos.distribution.v1beta1.QueryValidatorSlashesRequest") - proto.RegisterType((*QueryValidatorSlashesResponse)(nil), "cosmos.distribution.v1beta1.QueryValidatorSlashesResponse") - proto.RegisterType((*QueryDelegationRewardsRequest)(nil), "cosmos.distribution.v1beta1.QueryDelegationRewardsRequest") - proto.RegisterType((*QueryDelegationRewardsResponse)(nil), "cosmos.distribution.v1beta1.QueryDelegationRewardsResponse") - proto.RegisterType((*QueryDelegationTotalRewardsRequest)(nil), "cosmos.distribution.v1beta1.QueryDelegationTotalRewardsRequest") - proto.RegisterType((*QueryDelegationTotalRewardsResponse)(nil), "cosmos.distribution.v1beta1.QueryDelegationTotalRewardsResponse") - proto.RegisterType((*QueryDelegatorValidatorsRequest)(nil), "cosmos.distribution.v1beta1.QueryDelegatorValidatorsRequest") - proto.RegisterType((*QueryDelegatorValidatorsResponse)(nil), "cosmos.distribution.v1beta1.QueryDelegatorValidatorsResponse") - proto.RegisterType((*QueryDelegatorWithdrawAddressRequest)(nil), "cosmos.distribution.v1beta1.QueryDelegatorWithdrawAddressRequest") - proto.RegisterType((*QueryDelegatorWithdrawAddressResponse)(nil), "cosmos.distribution.v1beta1.QueryDelegatorWithdrawAddressResponse") - proto.RegisterType((*QueryCommunityPoolRequest)(nil), "cosmos.distribution.v1beta1.QueryCommunityPoolRequest") - proto.RegisterType((*QueryCommunityPoolResponse)(nil), "cosmos.distribution.v1beta1.QueryCommunityPoolResponse") -} - -func init() { - proto.RegisterFile("cosmos/distribution/v1beta1/query.proto", fileDescriptor_5efd02cbc06efdc9) -} - -var fileDescriptor_5efd02cbc06efdc9 = []byte{ - // 1257 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x58, 0x4f, 0x6c, 0x1b, 0xc5, - 0x17, 0xf6, 0x38, 0x69, 0xfa, 0xcb, 0xeb, 0xaf, 0x24, 0x99, 0x46, 0xc8, 0xd9, 0x04, 0x3b, 0xda, - 0xd0, 0x26, 0x6a, 0x14, 0x6f, 0x93, 0x48, 0xa5, 0x34, 0x54, 0x10, 0x3b, 0x09, 0x45, 0xad, 0xfa, - 0xc7, 0x2d, 0x44, 0x80, 0x2a, 0x6b, 0xed, 0xdd, 0xac, 0x17, 0xec, 0x1d, 0x67, 0x67, 0x9d, 0x10, - 0x55, 0xbd, 0x14, 0x21, 0x15, 0x4e, 0x08, 0x2e, 0x3d, 0xe6, 0x88, 0x38, 0x71, 0x00, 0x71, 0xe4, - 0xc2, 0xa1, 0xc7, 0x0a, 0x24, 0xc4, 0x09, 0x50, 0x02, 0xa2, 0x1c, 0x90, 0xb8, 0x71, 0x45, 0x9e, - 0x99, 0xb5, 0x77, 0xe3, 0xf5, 0xfa, 0x5f, 0x7c, 0x49, 0x56, 0x6f, 0xe6, 0x7d, 0xef, 0x7d, 0xef, - 0xcd, 0x9b, 0xf9, 0x12, 0x98, 0xcd, 0x13, 0x5a, 0x22, 0x54, 0xd1, 0x4c, 0xea, 0xd8, 0x66, 0xae, - 0xe2, 0x98, 0xc4, 0x52, 0x76, 0x16, 0x73, 0xba, 0xa3, 0x2e, 0x2a, 0xdb, 0x15, 0xdd, 0xde, 0x4b, - 0x96, 0x6d, 0xe2, 0x10, 0x3c, 0xc9, 0x37, 0x26, 0xbd, 0x1b, 0x93, 0x62, 0xa3, 0x74, 0x5e, 0xa0, - 0xe4, 0x54, 0xaa, 0x73, 0xaf, 0x1a, 0x46, 0x59, 0x35, 0x4c, 0x4b, 0x65, 0xbb, 0x19, 0x90, 0x34, - 0x6e, 0x10, 0x83, 0xb0, 0x4f, 0xa5, 0xfa, 0x25, 0xac, 0x53, 0x06, 0x21, 0x46, 0x51, 0x57, 0xd4, - 0xb2, 0xa9, 0xa8, 0x96, 0x45, 0x1c, 0xe6, 0x42, 0xc5, 0x6a, 0xdc, 0x8b, 0xef, 0x22, 0xe7, 0x89, - 0xe9, 0x62, 0x26, 0xc3, 0x58, 0xf8, 0x32, 0xe6, 0xfb, 0x27, 0xf8, 0xfe, 0x2c, 0x4f, 0x43, 0x30, - 0xe3, 0x4b, 0x63, 0x6a, 0xc9, 0xb4, 0x88, 0xc2, 0x7e, 0x72, 0x93, 0x3c, 0x0e, 0xf8, 0x76, 0x95, - 0xd3, 0x2d, 0xd5, 0x56, 0x4b, 0x34, 0xa3, 0x6f, 0x57, 0x74, 0xea, 0xc8, 0xf7, 0xe0, 0x8c, 0xcf, - 0x4a, 0xcb, 0xc4, 0xa2, 0x3a, 0xde, 0x80, 0xa1, 0x32, 0xb3, 0xc4, 0xd0, 0x34, 0x9a, 0x3b, 0xb5, - 0x34, 0x93, 0x0c, 0x29, 0x5c, 0x92, 0x3b, 0xa7, 0x86, 0x9f, 0xfc, 0x92, 0x88, 0x7c, 0xf1, 0xe7, - 0x57, 0xe7, 0x51, 0x46, 0x78, 0xcb, 0x16, 0x9c, 0x65, 0xf0, 0x6f, 0xa9, 0x45, 0x53, 0x53, 0x1d, - 0x62, 0xaf, 0x79, 0xfc, 0xdf, 0xb0, 0xb6, 0x88, 0xc8, 0x03, 0xaf, 0xc3, 0xd8, 0x8e, 0xbb, 0x27, - 0xab, 0x6a, 0x9a, 0xad, 0x53, 0x1e, 0x7b, 0x38, 0x15, 0xfb, 0xe1, 0xeb, 0x85, 0x71, 0x11, 0x7e, - 0x95, 0xaf, 0xdc, 0x71, 0x6c, 0xd3, 0x32, 0x32, 0xa3, 0x35, 0x17, 0x61, 0x97, 0xff, 0x88, 0xc2, - 0xb9, 0x56, 0x01, 0x05, 0xc5, 0x34, 0x8c, 0x92, 0xb2, 0x6e, 0x77, 0x14, 0x70, 0xc4, 0xf5, 0x10, - 0x66, 0xfc, 0x10, 0xc1, 0x18, 0xd5, 0x8b, 0x5b, 0xd9, 0x1c, 0xb1, 0xb4, 0xac, 0xad, 0xef, 0xaa, - 0xb6, 0x46, 0x63, 0xd1, 0xe9, 0x81, 0xb9, 0x53, 0x4b, 0x53, 0x6e, 0xcd, 0xaa, 0xfd, 0xae, 0xd5, - 0x6a, 0x4d, 0xcf, 0xa7, 0x89, 0x69, 0xa5, 0x2e, 0x55, 0x8b, 0xf5, 0xe5, 0xaf, 0x89, 0x79, 0xc3, - 0x74, 0x0a, 0x95, 0x5c, 0x32, 0x4f, 0x4a, 0xa2, 0x85, 0xe2, 0xd7, 0x02, 0xd5, 0xde, 0x57, 0x9c, - 0xbd, 0xb2, 0x4e, 0x5d, 0x1f, 0xca, 0x6b, 0x3b, 0x52, 0x0d, 0x98, 0x22, 0x96, 0x96, 0xe1, 0xe1, - 0xf0, 0x36, 0x40, 0x9e, 0x94, 0x4a, 0x26, 0xa5, 0x26, 0xb1, 0x62, 0x03, 0x6d, 0x04, 0x5f, 0xee, - 0x22, 0x78, 0xc6, 0x13, 0x44, 0x2e, 0xc3, 0xac, 0xbf, 0xcc, 0x37, 0x2b, 0x0e, 0x75, 0x54, 0x4b, - 0xab, 0x56, 0x89, 0xa7, 0x75, 0xcc, 0x9d, 0xfd, 0x18, 0xc1, 0x5c, 0xeb, 0x90, 0xa2, 0xb7, 0xf7, - 0xe0, 0xa4, 0xdb, 0x0b, 0x7e, 0x7e, 0x2f, 0x85, 0x9e, 0xdf, 0x10, 0x48, 0xef, 0xa1, 0x76, 0x31, - 0xe5, 0x02, 0x24, 0xfc, 0xa9, 0xa4, 0x6b, 0x95, 0x39, 0x66, 0xd6, 0x9f, 0x20, 0x98, 0x6e, 0x1e, - 0x4a, 0xb0, 0xdd, 0xf2, 0xf5, 0x9f, 0x13, 0x5e, 0x69, 0x8f, 0xf0, 0x6a, 0x3e, 0x5f, 0x29, 0x55, - 0x8a, 0xaa, 0xa3, 0x6b, 0x75, 0x60, 0x2f, 0x67, 0x6f, 0xd3, 0x3f, 0x8a, 0xc2, 0x94, 0x3f, 0x99, - 0x3b, 0x45, 0x95, 0x16, 0xf4, 0x63, 0x6e, 0x35, 0x9e, 0x85, 0x11, 0xea, 0xa8, 0xb6, 0x63, 0x5a, - 0x46, 0xb6, 0xa0, 0x9b, 0x46, 0xc1, 0x89, 0x45, 0xa7, 0xd1, 0xdc, 0x60, 0xe6, 0x39, 0xd7, 0x7c, - 0x95, 0x59, 0xf1, 0x0c, 0x9c, 0xd6, 0x59, 0xb3, 0xdc, 0x6d, 0x03, 0x6c, 0xdb, 0xff, 0xb9, 0x51, - 0x6c, 0xda, 0x00, 0xa8, 0xdf, 0xde, 0xb1, 0x41, 0x56, 0x9d, 0x73, 0xbe, 0xe9, 0xe0, 0x0f, 0x44, - 0xfd, 0x32, 0x33, 0x74, 0x41, 0x28, 0xe3, 0xf1, 0xbc, 0xfc, 0xbf, 0x47, 0xfb, 0x89, 0xc8, 0xe3, - 0xfd, 0x04, 0x92, 0xbf, 0x43, 0xf0, 0x42, 0x93, 0x3a, 0x88, 0x8e, 0xbc, 0x09, 0x27, 0x29, 0x37, - 0xc5, 0x10, 0x1b, 0xc7, 0x0b, 0xed, 0xb5, 0x83, 0xe1, 0xac, 0xef, 0xe8, 0x96, 0xe3, 0x3b, 0x77, - 0x02, 0x0b, 0xbf, 0xee, 0xa3, 0x12, 0x65, 0x54, 0x66, 0x5b, 0x52, 0xe1, 0x39, 0x79, 0xb9, 0xc8, - 0xdf, 0xba, 0x0c, 0xd6, 0xf4, 0xa2, 0x6e, 0x30, 0x5b, 0xe3, 0xd4, 0x6a, 0x7c, 0xad, 0x93, 0x56, - 0xd6, 0x5c, 0xdc, 0x56, 0x06, 0x9e, 0x88, 0x68, 0xa7, 0x27, 0x82, 0xd7, 0xfe, 0xd9, 0x7e, 0x22, - 0x22, 0x7f, 0x86, 0x20, 0xde, 0x2c, 0x73, 0x51, 0xfc, 0xb2, 0x77, 0xf8, 0xfb, 0x79, 0x11, 0xd7, - 0xee, 0x83, 0x0a, 0xc8, 0x47, 0x72, 0xba, 0x4b, 0x1c, 0xb5, 0xd8, 0x97, 0x92, 0x7a, 0x6a, 0xf1, - 0x0f, 0x82, 0x99, 0xd0, 0xb8, 0xa2, 0x20, 0xef, 0x1e, 0x2d, 0xc8, 0xc5, 0xd0, 0xd3, 0x58, 0x47, - 0x5b, 0x73, 0x63, 0x73, 0xc4, 0xa0, 0xbb, 0x10, 0x17, 0xe1, 0x84, 0x53, 0x0d, 0xda, 0xe7, 0x47, - 0x8f, 0x07, 0x91, 0x6d, 0x71, 0xf3, 0xd6, 0x32, 0xab, 0x8d, 0x4e, 0xff, 0xca, 0x7c, 0x5d, 0x5c, - 0xc1, 0x81, 0x31, 0x45, 0x89, 0xe3, 0x00, 0xb5, 0x43, 0xcb, 0xab, 0x3c, 0x9c, 0xf1, 0x58, 0x3c, - 0x68, 0xbb, 0xf0, 0xa2, 0x1f, 0x6d, 0xd3, 0x74, 0x0a, 0x9a, 0xad, 0xee, 0x8a, 0xc0, 0x7d, 0xa3, - 0xb1, 0x23, 0xa4, 0x58, 0xf3, 0xc0, 0x75, 0x61, 0xb4, 0x2b, 0x96, 0xda, 0x17, 0x46, 0xbb, 0x7e, - 0x30, 0x4f, 0xdc, 0x49, 0x98, 0x60, 0x71, 0xab, 0xef, 0x4b, 0xc5, 0x32, 0x9d, 0xbd, 0x5b, 0x84, - 0x14, 0x5d, 0xf9, 0xf9, 0x08, 0x81, 0x14, 0xb4, 0x2a, 0x52, 0x79, 0x0f, 0x06, 0xcb, 0x84, 0x14, - 0xfb, 0x3c, 0xc7, 0x2c, 0xc6, 0xd2, 0xf7, 0x63, 0x70, 0x82, 0xa5, 0x82, 0x1f, 0x23, 0x18, 0xe2, - 0x92, 0x16, 0x2b, 0xa1, 0x93, 0xd2, 0xa8, 0xa7, 0xa5, 0x0b, 0xed, 0x3b, 0x70, 0x8e, 0xf2, 0xfc, - 0xc3, 0x1f, 0x7f, 0xff, 0x3c, 0x7a, 0x16, 0xcf, 0x28, 0x61, 0xf2, 0x9f, 0xeb, 0x69, 0xfc, 0x17, - 0x82, 0x89, 0xa6, 0xd2, 0x16, 0xa7, 0x5a, 0x07, 0x6f, 0x25, 0xc4, 0xa5, 0x74, 0x4f, 0x18, 0x82, - 0x53, 0x9a, 0x71, 0xba, 0x82, 0x57, 0x42, 0x39, 0xd5, 0xe7, 0x43, 0xb9, 0xdf, 0xf0, 0x4a, 0x3c, - 0xc0, 0x1f, 0x46, 0x61, 0x32, 0x44, 0x99, 0xe1, 0xb5, 0x0e, 0x32, 0x6d, 0x2a, 0x4f, 0xa5, 0xf5, - 0x1e, 0x51, 0x04, 0xe3, 0x4d, 0xc6, 0xf8, 0x36, 0xbe, 0xd9, 0x03, 0x63, 0x85, 0xd4, 0xf1, 0xdd, - 0xbf, 0x25, 0xf0, 0x01, 0x82, 0x33, 0x01, 0xe2, 0x0f, 0xbf, 0xd2, 0x41, 0xde, 0x0d, 0xf2, 0x54, - 0xba, 0xd2, 0xa5, 0xb7, 0x60, 0x7b, 0x83, 0xb1, 0xbd, 0x8a, 0x37, 0x7a, 0x61, 0x5b, 0x57, 0x96, - 0xf8, 0x27, 0x04, 0xa3, 0x47, 0xc5, 0x14, 0x7e, 0xb9, 0x83, 0x1c, 0xfd, 0x42, 0x54, 0xba, 0xdc, - 0x8d, 0xab, 0xe0, 0x76, 0x8d, 0x71, 0x5b, 0xc7, 0xe9, 0x5e, 0xb8, 0xb9, 0x8a, 0xed, 0x6f, 0x04, - 0x63, 0x0d, 0x4a, 0x05, 0xb7, 0x91, 0x5e, 0x33, 0x61, 0x26, 0xad, 0x74, 0xe5, 0x2b, 0xb8, 0x65, - 0x19, 0xb7, 0xb7, 0xf1, 0x66, 0x28, 0xb7, 0xda, 0x23, 0x42, 0x95, 0xfb, 0x0d, 0x6f, 0xd0, 0x03, - 0x45, 0x9c, 0xcc, 0xc0, 0x99, 0x7d, 0x86, 0xe0, 0xf9, 0x60, 0x35, 0x82, 0x5f, 0xed, 0x24, 0xf1, - 0x00, 0xfd, 0x24, 0xbd, 0xd6, 0x3d, 0x40, 0x47, 0xad, 0x6d, 0x8f, 0x3e, 0x1b, 0xcc, 0x00, 0x49, - 0xd0, 0xce, 0x60, 0x36, 0x57, 0x2f, 0xed, 0x0c, 0x66, 0x88, 0x0e, 0x69, 0x73, 0x30, 0x5b, 0x30, - 0xac, 0x9f, 0x6d, 0xfc, 0x2f, 0x82, 0x58, 0x33, 0xc1, 0x80, 0x57, 0x3b, 0xc8, 0x35, 0x58, 0xe5, - 0x48, 0xa9, 0x5e, 0x20, 0x04, 0xe7, 0xbb, 0x8c, 0xf3, 0x0d, 0x7c, 0xbd, 0x17, 0xce, 0x47, 0x15, - 0x0f, 0xfe, 0x06, 0xc1, 0x69, 0x9f, 0x28, 0xc1, 0x17, 0x5b, 0xe7, 0x1a, 0xa4, 0x71, 0xa4, 0x97, - 0x3a, 0xf6, 0x13, 0xc4, 0x96, 0x19, 0xb1, 0x05, 0x3c, 0x1f, 0x4a, 0x2c, 0xef, 0xfa, 0x66, 0xab, - 0x32, 0x26, 0x75, 0xed, 0xc9, 0x41, 0x1c, 0x3d, 0x3d, 0x88, 0xa3, 0xdf, 0x0e, 0xe2, 0xe8, 0xd3, - 0xc3, 0x78, 0xe4, 0xe9, 0x61, 0x3c, 0xf2, 0xf3, 0x61, 0x3c, 0xf2, 0xce, 0x62, 0xa8, 0x30, 0xfa, - 0xc0, 0x8f, 0xce, 0x74, 0x52, 0x6e, 0x88, 0xfd, 0xeb, 0x70, 0xf9, 0xbf, 0x00, 0x00, 0x00, 0xff, - 0xff, 0x58, 0xdf, 0x9a, 0x20, 0x60, 0x15, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries params of the distribution module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // ValidatorDistributionInfo queries validator commission and self-delegation rewards for validator - ValidatorDistributionInfo(ctx context.Context, in *QueryValidatorDistributionInfoRequest, opts ...grpc.CallOption) (*QueryValidatorDistributionInfoResponse, error) - // ValidatorOutstandingRewards queries rewards of a validator address. - ValidatorOutstandingRewards(ctx context.Context, in *QueryValidatorOutstandingRewardsRequest, opts ...grpc.CallOption) (*QueryValidatorOutstandingRewardsResponse, error) - // ValidatorCommission queries accumulated commission for a validator. - ValidatorCommission(ctx context.Context, in *QueryValidatorCommissionRequest, opts ...grpc.CallOption) (*QueryValidatorCommissionResponse, error) - // ValidatorSlashes queries slash events of a validator. - ValidatorSlashes(ctx context.Context, in *QueryValidatorSlashesRequest, opts ...grpc.CallOption) (*QueryValidatorSlashesResponse, error) - // DelegationRewards queries the total rewards accrued by a delegation. - DelegationRewards(ctx context.Context, in *QueryDelegationRewardsRequest, opts ...grpc.CallOption) (*QueryDelegationRewardsResponse, error) - // DelegationTotalRewards queries the total rewards accrued by a each - // validator. - DelegationTotalRewards(ctx context.Context, in *QueryDelegationTotalRewardsRequest, opts ...grpc.CallOption) (*QueryDelegationTotalRewardsResponse, error) - // DelegatorValidators queries the validators of a delegator. - DelegatorValidators(ctx context.Context, in *QueryDelegatorValidatorsRequest, opts ...grpc.CallOption) (*QueryDelegatorValidatorsResponse, error) - // DelegatorWithdrawAddress queries withdraw address of a delegator. - DelegatorWithdrawAddress(ctx context.Context, in *QueryDelegatorWithdrawAddressRequest, opts ...grpc.CallOption) (*QueryDelegatorWithdrawAddressResponse, error) - // CommunityPool queries the community pool coins. - CommunityPool(ctx context.Context, in *QueryCommunityPoolRequest, opts ...grpc.CallOption) (*QueryCommunityPoolResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ValidatorDistributionInfo(ctx context.Context, in *QueryValidatorDistributionInfoRequest, opts ...grpc.CallOption) (*QueryValidatorDistributionInfoResponse, error) { - out := new(QueryValidatorDistributionInfoResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/ValidatorDistributionInfo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ValidatorOutstandingRewards(ctx context.Context, in *QueryValidatorOutstandingRewardsRequest, opts ...grpc.CallOption) (*QueryValidatorOutstandingRewardsResponse, error) { - out := new(QueryValidatorOutstandingRewardsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ValidatorCommission(ctx context.Context, in *QueryValidatorCommissionRequest, opts ...grpc.CallOption) (*QueryValidatorCommissionResponse, error) { - out := new(QueryValidatorCommissionResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/ValidatorCommission", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ValidatorSlashes(ctx context.Context, in *QueryValidatorSlashesRequest, opts ...grpc.CallOption) (*QueryValidatorSlashesResponse, error) { - out := new(QueryValidatorSlashesResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/ValidatorSlashes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DelegationRewards(ctx context.Context, in *QueryDelegationRewardsRequest, opts ...grpc.CallOption) (*QueryDelegationRewardsResponse, error) { - out := new(QueryDelegationRewardsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/DelegationRewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DelegationTotalRewards(ctx context.Context, in *QueryDelegationTotalRewardsRequest, opts ...grpc.CallOption) (*QueryDelegationTotalRewardsResponse, error) { - out := new(QueryDelegationTotalRewardsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/DelegationTotalRewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DelegatorValidators(ctx context.Context, in *QueryDelegatorValidatorsRequest, opts ...grpc.CallOption) (*QueryDelegatorValidatorsResponse, error) { - out := new(QueryDelegatorValidatorsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/DelegatorValidators", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) DelegatorWithdrawAddress(ctx context.Context, in *QueryDelegatorWithdrawAddressRequest, opts ...grpc.CallOption) (*QueryDelegatorWithdrawAddressResponse, error) { - out := new(QueryDelegatorWithdrawAddressResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) CommunityPool(ctx context.Context, in *QueryCommunityPoolRequest, opts ...grpc.CallOption) (*QueryCommunityPoolResponse, error) { - out := new(QueryCommunityPoolResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Query/CommunityPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries params of the distribution module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // ValidatorDistributionInfo queries validator commission and self-delegation rewards for validator - ValidatorDistributionInfo(context.Context, *QueryValidatorDistributionInfoRequest) (*QueryValidatorDistributionInfoResponse, error) - // ValidatorOutstandingRewards queries rewards of a validator address. - ValidatorOutstandingRewards(context.Context, *QueryValidatorOutstandingRewardsRequest) (*QueryValidatorOutstandingRewardsResponse, error) - // ValidatorCommission queries accumulated commission for a validator. - ValidatorCommission(context.Context, *QueryValidatorCommissionRequest) (*QueryValidatorCommissionResponse, error) - // ValidatorSlashes queries slash events of a validator. - ValidatorSlashes(context.Context, *QueryValidatorSlashesRequest) (*QueryValidatorSlashesResponse, error) - // DelegationRewards queries the total rewards accrued by a delegation. - DelegationRewards(context.Context, *QueryDelegationRewardsRequest) (*QueryDelegationRewardsResponse, error) - // DelegationTotalRewards queries the total rewards accrued by a each - // validator. - DelegationTotalRewards(context.Context, *QueryDelegationTotalRewardsRequest) (*QueryDelegationTotalRewardsResponse, error) - // DelegatorValidators queries the validators of a delegator. - DelegatorValidators(context.Context, *QueryDelegatorValidatorsRequest) (*QueryDelegatorValidatorsResponse, error) - // DelegatorWithdrawAddress queries withdraw address of a delegator. - DelegatorWithdrawAddress(context.Context, *QueryDelegatorWithdrawAddressRequest) (*QueryDelegatorWithdrawAddressResponse, error) - // CommunityPool queries the community pool coins. - CommunityPool(context.Context, *QueryCommunityPoolRequest) (*QueryCommunityPoolResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) ValidatorDistributionInfo(ctx context.Context, req *QueryValidatorDistributionInfoRequest) (*QueryValidatorDistributionInfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidatorDistributionInfo not implemented") -} -func (*UnimplementedQueryServer) ValidatorOutstandingRewards(ctx context.Context, req *QueryValidatorOutstandingRewardsRequest) (*QueryValidatorOutstandingRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidatorOutstandingRewards not implemented") -} -func (*UnimplementedQueryServer) ValidatorCommission(ctx context.Context, req *QueryValidatorCommissionRequest) (*QueryValidatorCommissionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidatorCommission not implemented") -} -func (*UnimplementedQueryServer) ValidatorSlashes(ctx context.Context, req *QueryValidatorSlashesRequest) (*QueryValidatorSlashesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidatorSlashes not implemented") -} -func (*UnimplementedQueryServer) DelegationRewards(ctx context.Context, req *QueryDelegationRewardsRequest) (*QueryDelegationRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegationRewards not implemented") -} -func (*UnimplementedQueryServer) DelegationTotalRewards(ctx context.Context, req *QueryDelegationTotalRewardsRequest) (*QueryDelegationTotalRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegationTotalRewards not implemented") -} -func (*UnimplementedQueryServer) DelegatorValidators(ctx context.Context, req *QueryDelegatorValidatorsRequest) (*QueryDelegatorValidatorsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegatorValidators not implemented") -} -func (*UnimplementedQueryServer) DelegatorWithdrawAddress(ctx context.Context, req *QueryDelegatorWithdrawAddressRequest) (*QueryDelegatorWithdrawAddressResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegatorWithdrawAddress not implemented") -} -func (*UnimplementedQueryServer) CommunityPool(ctx context.Context, req *QueryCommunityPoolRequest) (*QueryCommunityPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CommunityPool not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ValidatorDistributionInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorDistributionInfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ValidatorDistributionInfo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/ValidatorDistributionInfo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ValidatorDistributionInfo(ctx, req.(*QueryValidatorDistributionInfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ValidatorOutstandingRewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorOutstandingRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ValidatorOutstandingRewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ValidatorOutstandingRewards(ctx, req.(*QueryValidatorOutstandingRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ValidatorCommission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorCommissionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ValidatorCommission(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/ValidatorCommission", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ValidatorCommission(ctx, req.(*QueryValidatorCommissionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ValidatorSlashes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorSlashesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ValidatorSlashes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/ValidatorSlashes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ValidatorSlashes(ctx, req.(*QueryValidatorSlashesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DelegationRewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegationRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegationRewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/DelegationRewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegationRewards(ctx, req.(*QueryDelegationRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DelegationTotalRewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegationTotalRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegationTotalRewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/DelegationTotalRewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegationTotalRewards(ctx, req.(*QueryDelegationTotalRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DelegatorValidators_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegatorValidatorsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegatorValidators(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/DelegatorValidators", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegatorValidators(ctx, req.(*QueryDelegatorValidatorsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_DelegatorWithdrawAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegatorWithdrawAddressRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegatorWithdrawAddress(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegatorWithdrawAddress(ctx, req.(*QueryDelegatorWithdrawAddressRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_CommunityPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCommunityPoolRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).CommunityPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Query/CommunityPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).CommunityPool(ctx, req.(*QueryCommunityPoolRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.distribution.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "ValidatorDistributionInfo", - Handler: _Query_ValidatorDistributionInfo_Handler, - }, - { - MethodName: "ValidatorOutstandingRewards", - Handler: _Query_ValidatorOutstandingRewards_Handler, - }, - { - MethodName: "ValidatorCommission", - Handler: _Query_ValidatorCommission_Handler, - }, - { - MethodName: "ValidatorSlashes", - Handler: _Query_ValidatorSlashes_Handler, - }, - { - MethodName: "DelegationRewards", - Handler: _Query_DelegationRewards_Handler, - }, - { - MethodName: "DelegationTotalRewards", - Handler: _Query_DelegationTotalRewards_Handler, - }, - { - MethodName: "DelegatorValidators", - Handler: _Query_DelegatorValidators_Handler, - }, - { - MethodName: "DelegatorWithdrawAddress", - Handler: _Query_DelegatorWithdrawAddress_Handler, - }, - { - MethodName: "CommunityPool", - Handler: _Query_CommunityPool_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/distribution/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) 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 *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) 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 *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryValidatorDistributionInfoRequest) 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 *QueryValidatorDistributionInfoRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorDistributionInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryValidatorDistributionInfoResponse) 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 *QueryValidatorDistributionInfoResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorDistributionInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Commission) > 0 { - for iNdEx := len(m.Commission) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Commission[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.SelfBondRewards) > 0 { - for iNdEx := len(m.SelfBondRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SelfBondRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.OperatorAddress) > 0 { - i -= len(m.OperatorAddress) - copy(dAtA[i:], m.OperatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.OperatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryValidatorOutstandingRewardsRequest) 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 *QueryValidatorOutstandingRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorOutstandingRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryValidatorOutstandingRewardsResponse) 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 *QueryValidatorOutstandingRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorOutstandingRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Rewards.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryValidatorCommissionRequest) 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 *QueryValidatorCommissionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorCommissionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryValidatorCommissionResponse) 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 *QueryValidatorCommissionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorCommissionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Commission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryValidatorSlashesRequest) 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 *QueryValidatorSlashesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorSlashesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - if m.EndingHeight != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.EndingHeight)) - i-- - dAtA[i] = 0x18 - } - if m.StartingHeight != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.StartingHeight)) - i-- - dAtA[i] = 0x10 - } - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryValidatorSlashesResponse) 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 *QueryValidatorSlashesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryValidatorSlashesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Slashes) > 0 { - for iNdEx := len(m.Slashes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Slashes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegationRewardsRequest) 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 *QueryDelegationRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegationRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegationRewardsResponse) 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 *QueryDelegationRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegationRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Rewards) > 0 { - for iNdEx := len(m.Rewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Rewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegationTotalRewardsRequest) 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 *QueryDelegationTotalRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegationTotalRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegationTotalRewardsResponse) 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 *QueryDelegationTotalRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegationTotalRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Total) > 0 { - for iNdEx := len(m.Total) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Total[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Rewards) > 0 { - for iNdEx := len(m.Rewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Rewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatorValidatorsRequest) 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 *QueryDelegatorValidatorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatorValidatorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatorValidatorsResponse) 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 *QueryDelegatorValidatorsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatorValidatorsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Validators) > 0 { - for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Validators[iNdEx]) - copy(dAtA[i:], m.Validators[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Validators[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatorWithdrawAddressRequest) 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 *QueryDelegatorWithdrawAddressRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatorWithdrawAddressRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatorWithdrawAddressResponse) 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 *QueryDelegatorWithdrawAddressResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatorWithdrawAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.WithdrawAddress) > 0 { - i -= len(m.WithdrawAddress) - copy(dAtA[i:], m.WithdrawAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.WithdrawAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCommunityPoolRequest) 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 *QueryCommunityPoolRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommunityPoolRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryCommunityPoolResponse) 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 *QueryCommunityPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCommunityPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Pool) > 0 { - for iNdEx := len(m.Pool) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pool[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryValidatorDistributionInfoRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryValidatorDistributionInfoResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.OperatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.SelfBondRewards) > 0 { - for _, e := range m.SelfBondRewards { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Commission) > 0 { - for _, e := range m.Commission { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryValidatorOutstandingRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryValidatorOutstandingRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Rewards.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryValidatorCommissionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryValidatorCommissionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Commission.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryValidatorSlashesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.StartingHeight != 0 { - n += 1 + sovQuery(uint64(m.StartingHeight)) - } - if m.EndingHeight != 0 { - n += 1 + sovQuery(uint64(m.EndingHeight)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryValidatorSlashesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Slashes) > 0 { - for _, e := range m.Slashes { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegationRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegationRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Rewards) > 0 { - for _, e := range m.Rewards { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryDelegationTotalRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegationTotalRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Rewards) > 0 { - for _, e := range m.Rewards { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Total) > 0 { - for _, e := range m.Total { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryDelegatorValidatorsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegatorValidatorsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Validators) > 0 { - for _, s := range m.Validators { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryDelegatorWithdrawAddressRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegatorWithdrawAddressResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.WithdrawAddress) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCommunityPoolRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryCommunityPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pool) > 0 { - for _, e := range m.Pool { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) 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 ErrIntOverflowQuery - } - 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: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) 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 ErrIntOverflowQuery - } - 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: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorDistributionInfoRequest) 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 ErrIntOverflowQuery - } - 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: QueryValidatorDistributionInfoRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorDistributionInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorDistributionInfoResponse) 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 ErrIntOverflowQuery - } - 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: QueryValidatorDistributionInfoResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorDistributionInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OperatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.OperatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SelfBondRewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SelfBondRewards = append(m.SelfBondRewards, types.DecCoin{}) - if err := m.SelfBondRewards[len(m.SelfBondRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Commission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Commission = append(m.Commission, types.DecCoin{}) - if err := m.Commission[len(m.Commission)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorOutstandingRewardsRequest) 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 ErrIntOverflowQuery - } - 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: QueryValidatorOutstandingRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorOutstandingRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorOutstandingRewardsResponse) 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 ErrIntOverflowQuery - } - 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: QueryValidatorOutstandingRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorOutstandingRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Rewards.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorCommissionRequest) 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 ErrIntOverflowQuery - } - 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: QueryValidatorCommissionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorCommissionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorCommissionResponse) 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 ErrIntOverflowQuery - } - 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: QueryValidatorCommissionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorCommissionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Commission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Commission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorSlashesRequest) 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 ErrIntOverflowQuery - } - 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: QueryValidatorSlashesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorSlashesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartingHeight", wireType) - } - m.StartingHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.StartingHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field EndingHeight", wireType) - } - m.EndingHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.EndingHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryValidatorSlashesResponse) 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 ErrIntOverflowQuery - } - 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: QueryValidatorSlashesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryValidatorSlashesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slashes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Slashes = append(m.Slashes, ValidatorSlashEvent{}) - if err := m.Slashes[len(m.Slashes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegationRewardsRequest) 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 ErrIntOverflowQuery - } - 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: QueryDelegationRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegationRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegationRewardsResponse) 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 ErrIntOverflowQuery - } - 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: QueryDelegationRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegationRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Rewards = append(m.Rewards, types.DecCoin{}) - if err := m.Rewards[len(m.Rewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegationTotalRewardsRequest) 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 ErrIntOverflowQuery - } - 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: QueryDelegationTotalRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegationTotalRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegationTotalRewardsResponse) 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 ErrIntOverflowQuery - } - 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: QueryDelegationTotalRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegationTotalRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Rewards = append(m.Rewards, DelegationDelegatorReward{}) - if err := m.Rewards[len(m.Rewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Total = append(m.Total, types.DecCoin{}) - if err := m.Total[len(m.Total)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegatorValidatorsRequest) 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 ErrIntOverflowQuery - } - 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: QueryDelegatorValidatorsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatorValidatorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegatorValidatorsResponse) 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 ErrIntOverflowQuery - } - 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: QueryDelegatorValidatorsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatorValidatorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validators = append(m.Validators, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegatorWithdrawAddressRequest) 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 ErrIntOverflowQuery - } - 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: QueryDelegatorWithdrawAddressRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatorWithdrawAddressRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegatorWithdrawAddressResponse) 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 ErrIntOverflowQuery - } - 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: QueryDelegatorWithdrawAddressResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatorWithdrawAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WithdrawAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WithdrawAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCommunityPoolRequest) 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 ErrIntOverflowQuery - } - 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: QueryCommunityPoolRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommunityPoolRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCommunityPoolResponse) 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 ErrIntOverflowQuery - } - 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: QueryCommunityPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCommunityPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pool = append(m.Pool, types.DecCoin{}) - if err := m.Pool[len(m.Pool)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(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, ErrIntOverflowQuery - } - 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, ErrIntOverflowQuery - } - 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, ErrIntOverflowQuery - } - 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, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/distribution/types/query.pb.gw.go b/x/distribution/types/query.pb.gw.go deleted file mode 100644 index 9cf7f6801..000000000 --- a/x/distribution/types/query.pb.gw.go +++ /dev/null @@ -1,1066 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmos/distribution/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_ValidatorDistributionInfo_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorDistributionInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := client.ValidatorDistributionInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_ValidatorDistributionInfo_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorDistributionInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := server.ValidatorDistributionInfo(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_ValidatorOutstandingRewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorOutstandingRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := client.ValidatorOutstandingRewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_ValidatorOutstandingRewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorOutstandingRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := server.ValidatorOutstandingRewards(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_ValidatorCommission_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorCommissionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := client.ValidatorCommission(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_ValidatorCommission_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorCommissionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := server.ValidatorCommission(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_ValidatorSlashes_0 = &utilities.DoubleArray{Encoding: map[string]int{"validator_address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_ValidatorSlashes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorSlashesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ValidatorSlashes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ValidatorSlashes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_ValidatorSlashes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryValidatorSlashesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ValidatorSlashes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ValidatorSlashes(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_DelegationRewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegationRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := client.DelegationRewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DelegationRewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegationRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - val, ok = pathParams["validator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator_address") - } - - protoReq.ValidatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator_address", err) - } - - msg, err := server.DelegationRewards(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_DelegationTotalRewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegationTotalRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := client.DelegationTotalRewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DelegationTotalRewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegationTotalRewardsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := server.DelegationTotalRewards(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_DelegatorValidators_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatorValidatorsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := client.DelegatorValidators(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DelegatorValidators_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatorValidatorsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := server.DelegatorValidators(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_DelegatorWithdrawAddress_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatorWithdrawAddressRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := client.DelegatorWithdrawAddress(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DelegatorWithdrawAddress_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatorWithdrawAddressRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator_address") - } - - protoReq.DelegatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator_address", err) - } - - msg, err := server.DelegatorWithdrawAddress(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_CommunityPool_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommunityPoolRequest - var metadata runtime.ServerMetadata - - msg, err := client.CommunityPool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_CommunityPool_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCommunityPoolRequest - var metadata runtime.ServerMetadata - - msg, err := server.CommunityPool(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorDistributionInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ValidatorDistributionInfo_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorDistributionInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorOutstandingRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ValidatorOutstandingRewards_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorOutstandingRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorCommission_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ValidatorCommission_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorCommission_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorSlashes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ValidatorSlashes_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorSlashes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegationRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DelegationRewards_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegationRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegationTotalRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DelegationTotalRewards_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegationTotalRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegatorValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DelegatorValidators_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatorValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegatorWithdrawAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DelegatorWithdrawAddress_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatorWithdrawAddress_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_CommunityPool_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_CommunityPool_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_CommunityPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorDistributionInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ValidatorDistributionInfo_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorDistributionInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorOutstandingRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ValidatorOutstandingRewards_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorOutstandingRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorCommission_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ValidatorCommission_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorCommission_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ValidatorSlashes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ValidatorSlashes_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ValidatorSlashes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegationRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DelegationRewards_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegationRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegationTotalRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DelegationTotalRewards_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegationTotalRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegatorValidators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DelegatorValidators_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatorValidators_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_DelegatorWithdrawAddress_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DelegatorWithdrawAddress_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatorWithdrawAddress_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_CommunityPool_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_CommunityPool_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_CommunityPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "distribution", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ValidatorDistributionInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "distribution", "v1beta1", "validators", "validator_address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ValidatorOutstandingRewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "validators", "validator_address", "outstanding_rewards"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ValidatorCommission_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "validators", "validator_address", "commission"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ValidatorSlashes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "validators", "validator_address", "slashes"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DelegationRewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"cosmos", "distribution", "v1beta1", "delegators", "delegator_address", "rewards", "validator_address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DelegationTotalRewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "delegators", "delegator_address", "rewards"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DelegatorValidators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "delegators", "delegator_address", "validators"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_DelegatorWithdrawAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "distribution", "v1beta1", "delegators", "delegator_address", "withdraw_address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_CommunityPool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "distribution", "v1beta1", "community_pool"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_ValidatorDistributionInfo_0 = runtime.ForwardResponseMessage - - forward_Query_ValidatorOutstandingRewards_0 = runtime.ForwardResponseMessage - - forward_Query_ValidatorCommission_0 = runtime.ForwardResponseMessage - - forward_Query_ValidatorSlashes_0 = runtime.ForwardResponseMessage - - forward_Query_DelegationRewards_0 = runtime.ForwardResponseMessage - - forward_Query_DelegationTotalRewards_0 = runtime.ForwardResponseMessage - - forward_Query_DelegatorValidators_0 = runtime.ForwardResponseMessage - - forward_Query_DelegatorWithdrawAddress_0 = runtime.ForwardResponseMessage - - forward_Query_CommunityPool_0 = runtime.ForwardResponseMessage -) diff --git a/x/distribution/types/tx.pb.go b/x/distribution/types/tx.pb.go deleted file mode 100644 index d17fda875..000000000 --- a/x/distribution/types/tx.pb.go +++ /dev/null @@ -1,2879 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/distribution/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - 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 - -// MsgSetWithdrawAddress sets the withdraw address for -// a delegator (or validator self-delegation). -type MsgSetWithdrawAddress struct { - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` - WithdrawAddress string `protobuf:"bytes,2,opt,name=withdraw_address,json=withdrawAddress,proto3" json:"withdraw_address,omitempty"` -} - -func (m *MsgSetWithdrawAddress) Reset() { *m = MsgSetWithdrawAddress{} } -func (m *MsgSetWithdrawAddress) String() string { return proto.CompactTextString(m) } -func (*MsgSetWithdrawAddress) ProtoMessage() {} -func (*MsgSetWithdrawAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{0} -} -func (m *MsgSetWithdrawAddress) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetWithdrawAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetWithdrawAddress.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 *MsgSetWithdrawAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetWithdrawAddress.Merge(m, src) -} -func (m *MsgSetWithdrawAddress) XXX_Size() int { - return m.Size() -} -func (m *MsgSetWithdrawAddress) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetWithdrawAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetWithdrawAddress proto.InternalMessageInfo - -// MsgSetWithdrawAddressResponse defines the Msg/SetWithdrawAddress response -// type. -type MsgSetWithdrawAddressResponse struct { -} - -func (m *MsgSetWithdrawAddressResponse) Reset() { *m = MsgSetWithdrawAddressResponse{} } -func (m *MsgSetWithdrawAddressResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSetWithdrawAddressResponse) ProtoMessage() {} -func (*MsgSetWithdrawAddressResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{1} -} -func (m *MsgSetWithdrawAddressResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSetWithdrawAddressResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSetWithdrawAddressResponse.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 *MsgSetWithdrawAddressResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSetWithdrawAddressResponse.Merge(m, src) -} -func (m *MsgSetWithdrawAddressResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSetWithdrawAddressResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSetWithdrawAddressResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSetWithdrawAddressResponse proto.InternalMessageInfo - -// MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator -// from a single validator. -type MsgWithdrawDelegatorReward struct { - DelegatorAddress string `protobuf:"bytes,1,opt,name=delegator_address,json=delegatorAddress,proto3" json:"delegator_address,omitempty"` - ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *MsgWithdrawDelegatorReward) Reset() { *m = MsgWithdrawDelegatorReward{} } -func (m *MsgWithdrawDelegatorReward) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawDelegatorReward) ProtoMessage() {} -func (*MsgWithdrawDelegatorReward) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{2} -} -func (m *MsgWithdrawDelegatorReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawDelegatorReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawDelegatorReward.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 *MsgWithdrawDelegatorReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawDelegatorReward.Merge(m, src) -} -func (m *MsgWithdrawDelegatorReward) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawDelegatorReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawDelegatorReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawDelegatorReward proto.InternalMessageInfo - -// MsgWithdrawDelegatorRewardResponse defines the Msg/WithdrawDelegatorReward -// response type. -type MsgWithdrawDelegatorRewardResponse struct { - // Since: cosmos-sdk 0.46 - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdrawDelegatorRewardResponse) Reset() { *m = MsgWithdrawDelegatorRewardResponse{} } -func (m *MsgWithdrawDelegatorRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawDelegatorRewardResponse) ProtoMessage() {} -func (*MsgWithdrawDelegatorRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{3} -} -func (m *MsgWithdrawDelegatorRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawDelegatorRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawDelegatorRewardResponse.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 *MsgWithdrawDelegatorRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawDelegatorRewardResponse.Merge(m, src) -} -func (m *MsgWithdrawDelegatorRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawDelegatorRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawDelegatorRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawDelegatorRewardResponse proto.InternalMessageInfo - -func (m *MsgWithdrawDelegatorRewardResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgWithdrawValidatorCommission withdraws the full commission to the validator -// address. -type MsgWithdrawValidatorCommission struct { - ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` -} - -func (m *MsgWithdrawValidatorCommission) Reset() { *m = MsgWithdrawValidatorCommission{} } -func (m *MsgWithdrawValidatorCommission) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawValidatorCommission) ProtoMessage() {} -func (*MsgWithdrawValidatorCommission) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{4} -} -func (m *MsgWithdrawValidatorCommission) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawValidatorCommission) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawValidatorCommission.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 *MsgWithdrawValidatorCommission) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawValidatorCommission.Merge(m, src) -} -func (m *MsgWithdrawValidatorCommission) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawValidatorCommission) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawValidatorCommission.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawValidatorCommission proto.InternalMessageInfo - -// MsgWithdrawValidatorCommissionResponse defines the -// Msg/WithdrawValidatorCommission response type. -type MsgWithdrawValidatorCommissionResponse struct { - // Since: cosmos-sdk 0.46 - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdrawValidatorCommissionResponse) Reset() { - *m = MsgWithdrawValidatorCommissionResponse{} -} -func (m *MsgWithdrawValidatorCommissionResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawValidatorCommissionResponse) ProtoMessage() {} -func (*MsgWithdrawValidatorCommissionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{5} -} -func (m *MsgWithdrawValidatorCommissionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawValidatorCommissionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawValidatorCommissionResponse.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 *MsgWithdrawValidatorCommissionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawValidatorCommissionResponse.Merge(m, src) -} -func (m *MsgWithdrawValidatorCommissionResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawValidatorCommissionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawValidatorCommissionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawValidatorCommissionResponse proto.InternalMessageInfo - -func (m *MsgWithdrawValidatorCommissionResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgFundCommunityPool allows an account to directly -// fund the community pool. -type MsgFundCommunityPool struct { - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Depositor string `protobuf:"bytes,2,opt,name=depositor,proto3" json:"depositor,omitempty"` -} - -func (m *MsgFundCommunityPool) Reset() { *m = MsgFundCommunityPool{} } -func (m *MsgFundCommunityPool) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPool) ProtoMessage() {} -func (*MsgFundCommunityPool) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{6} -} -func (m *MsgFundCommunityPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPool.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 *MsgFundCommunityPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPool.Merge(m, src) -} -func (m *MsgFundCommunityPool) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPool proto.InternalMessageInfo - -// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. -type MsgFundCommunityPoolResponse struct { -} - -func (m *MsgFundCommunityPoolResponse) Reset() { *m = MsgFundCommunityPoolResponse{} } -func (m *MsgFundCommunityPoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPoolResponse) ProtoMessage() {} -func (*MsgFundCommunityPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{7} -} -func (m *MsgFundCommunityPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPoolResponse.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 *MsgFundCommunityPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPoolResponse.Merge(m, src) -} -func (m *MsgFundCommunityPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPoolResponse proto.InternalMessageInfo - -// MsgUpdateParams is the Msg/UpdateParams request type. -// -// Since: cosmos-sdk 0.47 -type MsgUpdateParams struct { - // authority is the address that controls the module (defaults to x/gov unless overwritten). - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/distribution parameters to update. - // - // NOTE: All parameters must be supplied. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{8} -} -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -func (m *MsgUpdateParams) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgUpdateParams) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: cosmos-sdk 0.47 -type MsgUpdateParamsResponse struct { -} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{9} -} -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -// MsgCommunityPoolSpend defines a message for sending tokens from the community -// pool to another account. This message is typically executed via a governance -// proposal with the governance module being the executing authority. -// -// Since: cosmos-sdk 0.47 -type MsgCommunityPoolSpend struct { - // authority is the address that controls the module (defaults to x/gov unless overwritten). - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - Recipient string `protobuf:"bytes,2,opt,name=recipient,proto3" json:"recipient,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgCommunityPoolSpend) Reset() { *m = MsgCommunityPoolSpend{} } -func (m *MsgCommunityPoolSpend) String() string { return proto.CompactTextString(m) } -func (*MsgCommunityPoolSpend) ProtoMessage() {} -func (*MsgCommunityPoolSpend) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{10} -} -func (m *MsgCommunityPoolSpend) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCommunityPoolSpend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCommunityPoolSpend.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 *MsgCommunityPoolSpend) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCommunityPoolSpend.Merge(m, src) -} -func (m *MsgCommunityPoolSpend) XXX_Size() int { - return m.Size() -} -func (m *MsgCommunityPoolSpend) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCommunityPoolSpend.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCommunityPoolSpend proto.InternalMessageInfo - -func (m *MsgCommunityPoolSpend) GetAuthority() string { - if m != nil { - return m.Authority - } - return "" -} - -func (m *MsgCommunityPoolSpend) GetRecipient() string { - if m != nil { - return m.Recipient - } - return "" -} - -func (m *MsgCommunityPoolSpend) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgCommunityPoolSpendResponse defines the response to executing a -// MsgCommunityPoolSpend message. -// -// Since: cosmos-sdk 0.47 -type MsgCommunityPoolSpendResponse struct { -} - -func (m *MsgCommunityPoolSpendResponse) Reset() { *m = MsgCommunityPoolSpendResponse{} } -func (m *MsgCommunityPoolSpendResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCommunityPoolSpendResponse) ProtoMessage() {} -func (*MsgCommunityPoolSpendResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed4f433d965e58ca, []int{11} -} -func (m *MsgCommunityPoolSpendResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCommunityPoolSpendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCommunityPoolSpendResponse.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 *MsgCommunityPoolSpendResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCommunityPoolSpendResponse.Merge(m, src) -} -func (m *MsgCommunityPoolSpendResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCommunityPoolSpendResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCommunityPoolSpendResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCommunityPoolSpendResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgSetWithdrawAddress)(nil), "cosmos.distribution.v1beta1.MsgSetWithdrawAddress") - proto.RegisterType((*MsgSetWithdrawAddressResponse)(nil), "cosmos.distribution.v1beta1.MsgSetWithdrawAddressResponse") - proto.RegisterType((*MsgWithdrawDelegatorReward)(nil), "cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward") - proto.RegisterType((*MsgWithdrawDelegatorRewardResponse)(nil), "cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse") - proto.RegisterType((*MsgWithdrawValidatorCommission)(nil), "cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission") - proto.RegisterType((*MsgWithdrawValidatorCommissionResponse)(nil), "cosmos.distribution.v1beta1.MsgWithdrawValidatorCommissionResponse") - proto.RegisterType((*MsgFundCommunityPool)(nil), "cosmos.distribution.v1beta1.MsgFundCommunityPool") - proto.RegisterType((*MsgFundCommunityPoolResponse)(nil), "cosmos.distribution.v1beta1.MsgFundCommunityPoolResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "cosmos.distribution.v1beta1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "cosmos.distribution.v1beta1.MsgUpdateParamsResponse") - proto.RegisterType((*MsgCommunityPoolSpend)(nil), "cosmos.distribution.v1beta1.MsgCommunityPoolSpend") - proto.RegisterType((*MsgCommunityPoolSpendResponse)(nil), "cosmos.distribution.v1beta1.MsgCommunityPoolSpendResponse") -} - -func init() { - proto.RegisterFile("cosmos/distribution/v1beta1/tx.proto", fileDescriptor_ed4f433d965e58ca) -} - -var fileDescriptor_ed4f433d965e58ca = []byte{ - // 829 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x56, 0xcd, 0x6b, 0x13, 0x4f, - 0x18, 0xce, 0xb4, 0xfc, 0x02, 0x99, 0xfe, 0xa0, 0x4d, 0xa8, 0xb4, 0xdd, 0xd6, 0x4d, 0xd9, 0x4a, - 0x2d, 0xc5, 0xee, 0x92, 0xf8, 0x45, 0xe3, 0x41, 0x4c, 0x6c, 0xc1, 0x43, 0xb0, 0xa4, 0xa8, 0xe0, - 0xa5, 0x6c, 0xb2, 0xeb, 0x66, 0xb0, 0xbb, 0xb3, 0xec, 0x4c, 0x9a, 0xe6, 0xa6, 0xe2, 0x41, 0x3c, - 0x88, 0xd4, 0x3f, 0xc0, 0x1e, 0x8b, 0x17, 0x7b, 0xf0, 0x8f, 0x28, 0x82, 0x50, 0x3c, 0x79, 0x52, - 0x49, 0x0f, 0x15, 0xbc, 0xea, 0x5d, 0xf6, 0x33, 0xbb, 0xd9, 0x4d, 0xd6, 0xd4, 0xaf, 0x4b, 0x5b, - 0x66, 0xde, 0xe7, 0xd9, 0xe7, 0x79, 0xe6, 0x9d, 0x77, 0x0a, 0xcf, 0xd4, 0x30, 0x51, 0x31, 0x11, - 0x24, 0x44, 0xa8, 0x81, 0xaa, 0x0d, 0x8a, 0xb0, 0x26, 0x6c, 0xe5, 0xaa, 0x32, 0x15, 0x73, 0x02, - 0xdd, 0xe6, 0x75, 0x03, 0x53, 0x9c, 0x99, 0xb6, 0xab, 0x78, 0x7f, 0x15, 0xef, 0x54, 0x31, 0xe3, - 0x0a, 0x56, 0xb0, 0x55, 0x27, 0x98, 0x7f, 0xd9, 0x10, 0x86, 0x75, 0x88, 0xab, 0x22, 0x91, 0x3d, - 0xc2, 0x1a, 0x46, 0x9a, 0xb3, 0x3f, 0x65, 0xef, 0x6f, 0xd8, 0x40, 0x87, 0xdf, 0xde, 0x9a, 0x70, - 0xa0, 0x2a, 0x51, 0x84, 0xad, 0x9c, 0xf9, 0xcb, 0xd9, 0x48, 0x8b, 0x2a, 0xd2, 0xb0, 0x60, 0xfd, - 0x74, 0x96, 0xf8, 0x7e, 0xfa, 0x03, 0x72, 0xad, 0x7a, 0xee, 0x2b, 0x80, 0xa7, 0xca, 0x44, 0x59, - 0x97, 0xe9, 0x1d, 0x44, 0xeb, 0x92, 0x21, 0x36, 0xaf, 0x49, 0x92, 0x21, 0x13, 0x92, 0x59, 0x81, - 0x69, 0x49, 0xde, 0x94, 0x15, 0x91, 0x62, 0x63, 0x43, 0xb4, 0x17, 0x27, 0xc1, 0x2c, 0x58, 0x48, - 0x15, 0x27, 0xdf, 0xbf, 0x59, 0x1a, 0x77, 0x24, 0x3a, 0xe5, 0xeb, 0xd4, 0x40, 0x9a, 0x52, 0x19, - 0xf3, 0x20, 0x2e, 0x4d, 0x09, 0x8e, 0x35, 0x1d, 0x66, 0x8f, 0x65, 0x28, 0x86, 0x65, 0xb4, 0x19, - 0xd4, 0x52, 0x58, 0x7d, 0xb2, 0x9b, 0x4d, 0x7c, 0xd9, 0xcd, 0x26, 0x1e, 0x1d, 0xef, 0x2f, 0x86, - 0x65, 0x3d, 0x3d, 0xde, 0x5f, 0x9c, 0xb3, 0x99, 0x96, 0x88, 0x74, 0x5f, 0x28, 0x13, 0xa5, 0x8c, - 0x25, 0x74, 0xaf, 0xd5, 0xe5, 0x89, 0xcb, 0xc2, 0xd3, 0x91, 0x66, 0x2b, 0x32, 0xd1, 0xb1, 0x46, - 0x64, 0xee, 0x3b, 0x80, 0x4c, 0x99, 0x28, 0xee, 0xf6, 0x75, 0xf7, 0x4b, 0x15, 0xb9, 0x29, 0x1a, - 0xd2, 0xef, 0xca, 0x64, 0x05, 0xa6, 0xb7, 0xc4, 0x4d, 0x24, 0x05, 0x68, 0xe2, 0x42, 0x19, 0xf3, - 0x20, 0x6e, 0x2a, 0x37, 0xe2, 0x53, 0x99, 0x0f, 0xa6, 0xd2, 0xe5, 0x0b, 0x61, 0xcd, 0x36, 0xc6, - 0x3d, 0x03, 0x90, 0xeb, 0xed, 0xdb, 0x8d, 0x27, 0x53, 0x87, 0x49, 0x51, 0xc5, 0x0d, 0x8d, 0x4e, - 0x82, 0xd9, 0xe1, 0x85, 0x91, 0xfc, 0x94, 0xd3, 0x6e, 0xbc, 0xd9, 0xd5, 0xee, 0x05, 0xe0, 0x4b, - 0x18, 0x69, 0xc5, 0x8b, 0x07, 0x1f, 0xb3, 0x89, 0x57, 0x9f, 0xb2, 0x0b, 0x0a, 0xa2, 0xf5, 0x46, - 0x95, 0xaf, 0x61, 0xd5, 0xe9, 0x6a, 0xc1, 0xa7, 0x89, 0xb6, 0x74, 0x99, 0x58, 0x00, 0xb2, 0x77, - 0xbc, 0xbf, 0x08, 0x2a, 0x0e, 0x3f, 0xf7, 0x1a, 0x40, 0xd6, 0x27, 0xe8, 0xb6, 0xeb, 0xbd, 0x84, - 0x55, 0x15, 0x11, 0x82, 0xb0, 0x16, 0x9d, 0x22, 0x18, 0x38, 0xc5, 0x60, 0x6f, 0x85, 0x18, 0x23, - 0x7a, 0xcb, 0x27, 0xaa, 0x23, 0x87, 0xdb, 0x01, 0x70, 0xbe, 0xbf, 0xe2, 0x7f, 0x10, 0xe3, 0x37, - 0x00, 0xc7, 0xcb, 0x44, 0x59, 0x6d, 0x68, 0x92, 0xa9, 0xa3, 0xa1, 0x21, 0xda, 0x5a, 0xc3, 0x78, - 0xf3, 0xef, 0x49, 0xc8, 0x5c, 0x82, 0x29, 0x49, 0xd6, 0x31, 0x41, 0x14, 0x1b, 0xb1, 0x4d, 0xde, - 0x29, 0x2d, 0x14, 0xfc, 0xe7, 0xd2, 0x59, 0x37, 0xcf, 0x23, 0x1b, 0x3c, 0x8f, 0x90, 0x3b, 0x8e, - 0x85, 0x33, 0x51, 0xeb, 0xde, 0x35, 0x7f, 0x07, 0xe0, 0x68, 0x99, 0x28, 0xb7, 0x74, 0x49, 0xa4, - 0xf2, 0x9a, 0x68, 0x88, 0x2a, 0x31, 0x75, 0x8a, 0x0d, 0x5a, 0xc7, 0x06, 0xa2, 0xad, 0xd8, 0x36, - 0xea, 0x94, 0x66, 0x56, 0x61, 0x52, 0xb7, 0x18, 0x2c, 0x73, 0x23, 0xf9, 0x39, 0xbe, 0xcf, 0xe3, - 0xc0, 0xdb, 0x1f, 0x2b, 0xa6, 0xcc, 0x4c, 0x9d, 0x9c, 0x6c, 0x74, 0xa1, 0x60, 0xf9, 0xf4, 0x78, - 0x4d, 0x9f, 0x67, 0x7d, 0x3e, 0x03, 0x03, 0xbd, 0x4b, 0x3b, 0x37, 0x05, 0x27, 0xba, 0x96, 0x3c, - 0xab, 0x3b, 0x43, 0xd6, 0x80, 0x0f, 0xe4, 0xb0, 0xae, 0xcb, 0x9a, 0x74, 0x62, 0xc3, 0x33, 0x30, - 0x65, 0xc8, 0x35, 0xa4, 0x23, 0x59, 0xa3, 0xf6, 0x81, 0x56, 0x3a, 0x0b, 0xbe, 0xc6, 0x1a, 0xfe, - 0xb3, 0x8d, 0x55, 0x58, 0x0e, 0x07, 0x36, 0xdf, 0x1d, 0x98, 0x10, 0x69, 0xdd, 0x79, 0x07, 0xc2, - 0x1b, 0x6e, 0x6a, 0xf9, 0xb7, 0x49, 0x38, 0x5c, 0x26, 0x4a, 0xe6, 0x31, 0x80, 0x99, 0x88, 0xb7, - 0x31, 0xdf, 0xf7, 0x8c, 0x23, 0x9f, 0x18, 0xa6, 0x30, 0x38, 0xc6, 0x1b, 0x18, 0x2f, 0x00, 0x9c, - 0xe8, 0xf5, 0x26, 0x5d, 0x8e, 0xe3, 0xed, 0x01, 0x64, 0xae, 0x9e, 0x10, 0xe8, 0xa9, 0x7a, 0x09, - 0xe0, 0x74, 0xbf, 0x01, 0x7d, 0xe5, 0x67, 0x3f, 0x10, 0x01, 0x66, 0x4a, 0xbf, 0x00, 0xf6, 0x14, - 0x3e, 0x04, 0x30, 0x1d, 0x9e, 0x7d, 0xb9, 0x38, 0xea, 0x10, 0x84, 0x59, 0x1e, 0x18, 0xe2, 0x69, - 0x30, 0xe0, 0xff, 0x81, 0x39, 0x73, 0x2e, 0x8e, 0xca, 0x5f, 0xcd, 0x5c, 0x18, 0xa4, 0xda, 0xfb, - 0xa6, 0xd9, 0xb6, 0x11, 0x37, 0x3e, 0xb6, 0x6d, 0xc3, 0x98, 0xf8, 0xb6, 0xed, 0x7d, 0x8b, 0x98, - 0xff, 0x1e, 0x98, 0x17, 0xb6, 0x78, 0x73, 0xaf, 0xcd, 0x82, 0x83, 0x36, 0x0b, 0x0e, 0xdb, 0x2c, - 0xf8, 0xdc, 0x66, 0xc1, 0xf3, 0x23, 0x36, 0x71, 0x78, 0xc4, 0x26, 0x3e, 0x1c, 0xb1, 0x89, 0xbb, - 0xb9, 0xbe, 0xb7, 0x7f, 0x3b, 0x38, 0xf8, 0xac, 0x61, 0x50, 0x4d, 0x5a, 0xff, 0xbb, 0x9e, 0xff, - 0x11, 0x00, 0x00, 0xff, 0xff, 0x3b, 0xc9, 0x2e, 0x04, 0xad, 0x0b, 0x00, 0x00, -} - -func (this *MsgSetWithdrawAddressResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgSetWithdrawAddressResponse) - if !ok { - that2, ok := that.(MsgSetWithdrawAddressResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *MsgWithdrawDelegatorRewardResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgWithdrawDelegatorRewardResponse) - if !ok { - that2, ok := that.(MsgWithdrawDelegatorRewardResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Amount) != len(that1.Amount) { - return false - } - for i := range this.Amount { - if !this.Amount[i].Equal(&that1.Amount[i]) { - return false - } - } - return true -} -func (this *MsgWithdrawValidatorCommissionResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgWithdrawValidatorCommissionResponse) - if !ok { - that2, ok := that.(MsgWithdrawValidatorCommissionResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Amount) != len(that1.Amount) { - return false - } - for i := range this.Amount { - if !this.Amount[i].Equal(&that1.Amount[i]) { - return false - } - } - return true -} -func (this *MsgFundCommunityPoolResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgFundCommunityPoolResponse) - if !ok { - that2, ok := that.(MsgFundCommunityPoolResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *MsgUpdateParams) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParams) - if !ok { - that2, ok := that.(MsgUpdateParams) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Authority != that1.Authority { - return false - } - if !this.Params.Equal(&that1.Params) { - return false - } - return true -} -func (this *MsgUpdateParamsResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParamsResponse) - if !ok { - that2, ok := that.(MsgUpdateParamsResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *MsgCommunityPoolSpend) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgCommunityPoolSpend) - if !ok { - that2, ok := that.(MsgCommunityPoolSpend) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Authority != that1.Authority { - return false - } - if this.Recipient != that1.Recipient { - return false - } - if len(this.Amount) != len(that1.Amount) { - return false - } - for i := range this.Amount { - if !this.Amount[i].Equal(&that1.Amount[i]) { - return false - } - } - return true -} -func (this *MsgCommunityPoolSpendResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgCommunityPoolSpendResponse) - if !ok { - that2, ok := that.(MsgCommunityPoolSpendResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // SetWithdrawAddress defines a method to change the withdraw address - // for a delegator (or validator self-delegation). - SetWithdrawAddress(ctx context.Context, in *MsgSetWithdrawAddress, opts ...grpc.CallOption) (*MsgSetWithdrawAddressResponse, error) - // WithdrawDelegatorReward defines a method to withdraw rewards of delegator - // from a single validator. - WithdrawDelegatorReward(ctx context.Context, in *MsgWithdrawDelegatorReward, opts ...grpc.CallOption) (*MsgWithdrawDelegatorRewardResponse, error) - // WithdrawValidatorCommission defines a method to withdraw the - // full commission to the validator address. - WithdrawValidatorCommission(ctx context.Context, in *MsgWithdrawValidatorCommission, opts ...grpc.CallOption) (*MsgWithdrawValidatorCommissionResponse, error) - // FundCommunityPool defines a method to allow an account to directly - // fund the community pool. - FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a governance operation for updating the x/distribution - // module parameters. The authority is defined in the keeper. - // - // Since: cosmos-sdk 0.47 - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) - // CommunityPoolSpend defines a governance operation for sending tokens from - // the community pool in the x/distribution module to another account, which - // could be the governance module itself. The authority is defined in the - // keeper. - // - // Since: cosmos-sdk 0.47 - CommunityPoolSpend(ctx context.Context, in *MsgCommunityPoolSpend, opts ...grpc.CallOption) (*MsgCommunityPoolSpendResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) SetWithdrawAddress(ctx context.Context, in *MsgSetWithdrawAddress, opts ...grpc.CallOption) (*MsgSetWithdrawAddressResponse, error) { - out := new(MsgSetWithdrawAddressResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/SetWithdrawAddress", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawDelegatorReward(ctx context.Context, in *MsgWithdrawDelegatorReward, opts ...grpc.CallOption) (*MsgWithdrawDelegatorRewardResponse, error) { - out := new(MsgWithdrawDelegatorRewardResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/WithdrawDelegatorReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawValidatorCommission(ctx context.Context, in *MsgWithdrawValidatorCommission, opts ...grpc.CallOption) (*MsgWithdrawValidatorCommissionResponse, error) { - out := new(MsgWithdrawValidatorCommissionResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/WithdrawValidatorCommission", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) { - out := new(MsgFundCommunityPoolResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/FundCommunityPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) CommunityPoolSpend(ctx context.Context, in *MsgCommunityPoolSpend, opts ...grpc.CallOption) (*MsgCommunityPoolSpendResponse, error) { - out := new(MsgCommunityPoolSpendResponse) - err := c.cc.Invoke(ctx, "/cosmos.distribution.v1beta1.Msg/CommunityPoolSpend", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // SetWithdrawAddress defines a method to change the withdraw address - // for a delegator (or validator self-delegation). - SetWithdrawAddress(context.Context, *MsgSetWithdrawAddress) (*MsgSetWithdrawAddressResponse, error) - // WithdrawDelegatorReward defines a method to withdraw rewards of delegator - // from a single validator. - WithdrawDelegatorReward(context.Context, *MsgWithdrawDelegatorReward) (*MsgWithdrawDelegatorRewardResponse, error) - // WithdrawValidatorCommission defines a method to withdraw the - // full commission to the validator address. - WithdrawValidatorCommission(context.Context, *MsgWithdrawValidatorCommission) (*MsgWithdrawValidatorCommissionResponse, error) - // FundCommunityPool defines a method to allow an account to directly - // fund the community pool. - FundCommunityPool(context.Context, *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a governance operation for updating the x/distribution - // module parameters. The authority is defined in the keeper. - // - // Since: cosmos-sdk 0.47 - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) - // CommunityPoolSpend defines a governance operation for sending tokens from - // the community pool in the x/distribution module to another account, which - // could be the governance module itself. The authority is defined in the - // keeper. - // - // Since: cosmos-sdk 0.47 - CommunityPoolSpend(context.Context, *MsgCommunityPoolSpend) (*MsgCommunityPoolSpendResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) SetWithdrawAddress(ctx context.Context, req *MsgSetWithdrawAddress) (*MsgSetWithdrawAddressResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SetWithdrawAddress not implemented") -} -func (*UnimplementedMsgServer) WithdrawDelegatorReward(ctx context.Context, req *MsgWithdrawDelegatorReward) (*MsgWithdrawDelegatorRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawDelegatorReward not implemented") -} -func (*UnimplementedMsgServer) WithdrawValidatorCommission(ctx context.Context, req *MsgWithdrawValidatorCommission) (*MsgWithdrawValidatorCommissionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawValidatorCommission not implemented") -} -func (*UnimplementedMsgServer) FundCommunityPool(ctx context.Context, req *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method FundCommunityPool not implemented") -} -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} -func (*UnimplementedMsgServer) CommunityPoolSpend(ctx context.Context, req *MsgCommunityPoolSpend) (*MsgCommunityPoolSpendResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CommunityPoolSpend not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_SetWithdrawAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSetWithdrawAddress) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SetWithdrawAddress(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/SetWithdrawAddress", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SetWithdrawAddress(ctx, req.(*MsgSetWithdrawAddress)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawDelegatorReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawDelegatorReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawDelegatorReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/WithdrawDelegatorReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawDelegatorReward(ctx, req.(*MsgWithdrawDelegatorReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawValidatorCommission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawValidatorCommission) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawValidatorCommission(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/WithdrawValidatorCommission", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawValidatorCommission(ctx, req.(*MsgWithdrawValidatorCommission)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_FundCommunityPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgFundCommunityPool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).FundCommunityPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/FundCommunityPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).FundCommunityPool(ctx, req.(*MsgFundCommunityPool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_CommunityPoolSpend_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCommunityPoolSpend) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CommunityPoolSpend(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmos.distribution.v1beta1.Msg/CommunityPoolSpend", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CommunityPoolSpend(ctx, req.(*MsgCommunityPoolSpend)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.distribution.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SetWithdrawAddress", - Handler: _Msg_SetWithdrawAddress_Handler, - }, - { - MethodName: "WithdrawDelegatorReward", - Handler: _Msg_WithdrawDelegatorReward_Handler, - }, - { - MethodName: "WithdrawValidatorCommission", - Handler: _Msg_WithdrawValidatorCommission_Handler, - }, - { - MethodName: "FundCommunityPool", - Handler: _Msg_FundCommunityPool_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - { - MethodName: "CommunityPoolSpend", - Handler: _Msg_CommunityPoolSpend_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/distribution/v1beta1/tx.proto", -} - -func (m *MsgSetWithdrawAddress) 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 *MsgSetWithdrawAddress) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetWithdrawAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.WithdrawAddress) > 0 { - i -= len(m.WithdrawAddress) - copy(dAtA[i:], m.WithdrawAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.WithdrawAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSetWithdrawAddressResponse) 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 *MsgSetWithdrawAddressResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSetWithdrawAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawDelegatorReward) 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 *MsgWithdrawDelegatorReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawDelegatorReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0x12 - } - if len(m.DelegatorAddress) > 0 { - i -= len(m.DelegatorAddress) - copy(dAtA[i:], m.DelegatorAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.DelegatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawDelegatorRewardResponse) 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 *MsgWithdrawDelegatorRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawDelegatorRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawValidatorCommission) 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 *MsgWithdrawValidatorCommission) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawValidatorCommission) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ValidatorAddress) > 0 { - i -= len(m.ValidatorAddress) - copy(dAtA[i:], m.ValidatorAddress) - i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawValidatorCommissionResponse) 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 *MsgWithdrawValidatorCommissionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawValidatorCommissionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgFundCommunityPool) 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 *MsgFundCommunityPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0x12 - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgFundCommunityPoolResponse) 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 *MsgFundCommunityPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgCommunityPoolSpend) 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 *MsgCommunityPoolSpend) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCommunityPoolSpend) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Recipient) > 0 { - i -= len(m.Recipient) - copy(dAtA[i:], m.Recipient) - i = encodeVarintTx(dAtA, i, uint64(len(m.Recipient))) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCommunityPoolSpendResponse) 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 *MsgCommunityPoolSpendResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCommunityPoolSpendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgSetWithdrawAddress) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.WithdrawAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgSetWithdrawAddressResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawDelegatorReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.DelegatorAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgWithdrawDelegatorRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawValidatorCommission) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgWithdrawValidatorCommissionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgFundCommunityPool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgFundCommunityPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgCommunityPoolSpend) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Recipient) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgCommunityPoolSpendResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgSetWithdrawAddress) 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 ErrIntOverflowTx - } - 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: MsgSetWithdrawAddress: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetWithdrawAddress: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WithdrawAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WithdrawAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSetWithdrawAddressResponse) 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 ErrIntOverflowTx - } - 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: MsgSetWithdrawAddressResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSetWithdrawAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawDelegatorReward) 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 ErrIntOverflowTx - } - 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: MsgWithdrawDelegatorReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawDelegatorReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawDelegatorRewardResponse) 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 ErrIntOverflowTx - } - 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: MsgWithdrawDelegatorRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawDelegatorRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawValidatorCommission) 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 ErrIntOverflowTx - } - 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: MsgWithdrawValidatorCommission: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawValidatorCommission: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawValidatorCommissionResponse) 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 ErrIntOverflowTx - } - 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: MsgWithdrawValidatorCommissionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawValidatorCommissionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgFundCommunityPool) 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 ErrIntOverflowTx - } - 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: MsgFundCommunityPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgFundCommunityPoolResponse) 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 ErrIntOverflowTx - } - 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: MsgFundCommunityPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParams) 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 ErrIntOverflowTx - } - 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: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParamsResponse) 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 ErrIntOverflowTx - } - 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: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCommunityPoolSpend) 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 ErrIntOverflowTx - } - 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: MsgCommunityPoolSpend: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCommunityPoolSpend: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Recipient", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Recipient = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCommunityPoolSpendResponse) 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 ErrIntOverflowTx - } - 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: MsgCommunityPoolSpendResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCommunityPoolSpendResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrIntOverflowTx - } - 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, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/distribution/types/validator.go b/x/distribution/types/validator.go deleted file mode 100644 index aa64a3703..000000000 --- a/x/distribution/types/validator.go +++ /dev/null @@ -1,48 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// create a new ValidatorHistoricalRewards -func NewValidatorHistoricalRewards(cumulativeRewardRatio sdk.DecCoins, referenceCount uint32) ValidatorHistoricalRewards { - return ValidatorHistoricalRewards{ - CumulativeRewardRatio: cumulativeRewardRatio, - ReferenceCount: referenceCount, - } -} - -// create a new ValidatorCurrentRewards -func NewValidatorCurrentRewards(rewards sdk.DecCoins, period uint64) ValidatorCurrentRewards { - return ValidatorCurrentRewards{ - Rewards: rewards, - Period: period, - } -} - -// return the initial accumulated commission (zero) -func InitialValidatorAccumulatedCommission() ValidatorAccumulatedCommission { - return ValidatorAccumulatedCommission{} -} - -// create a new ValidatorSlashEvent -func NewValidatorSlashEvent(validatorPeriod uint64, fraction sdk.Dec) ValidatorSlashEvent { - return ValidatorSlashEvent{ - ValidatorPeriod: validatorPeriod, - Fraction: fraction, - } -} - -func (vs ValidatorSlashEvents) String() string { - out := "Validator Slash Events:\n" - for i, sl := range vs.ValidatorSlashEvents { - out += fmt.Sprintf(` Slash %d: - Period: %d - Fraction: %s -`, i, sl.ValidatorPeriod, sl.Fraction) - } - return strings.TrimSpace(out) -} diff --git a/x/genutil/migrations/v047/migrate.go b/x/genutil/migrations/v047/migrate.go index 12bba8e2a..5d833662e 100644 --- a/x/genutil/migrations/v047/migrate.go +++ b/x/genutil/migrations/v047/migrate.go @@ -1,9 +1,9 @@ package v047 import ( - v1distr "x/distribution/migrations/v1" - v3distr "x/distribution/migrations/v3" - distrtypes "x/distribution/types" + v1distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1" + v3distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/client" v1auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v1" diff --git a/x/gravity/keeper/attestation_handler.go b/x/gravity/keeper/attestation_handler.go index 64c331246..f130fe2df 100644 --- a/x/gravity/keeper/attestation_handler.go +++ b/x/gravity/keeper/attestation_handler.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - distrkeeper "x/distribution/keeper" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/gravity/keeper/governance_proposals.go b/x/gravity/keeper/governance_proposals.go index 34314ae51..3b3ddd8bb 100644 --- a/x/gravity/keeper/governance_proposals.go +++ b/x/gravity/keeper/governance_proposals.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - disttypes "x/distribution/types" + disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" diff --git a/x/gravity/keeper/governance_proposals_test.go b/x/gravity/keeper/governance_proposals_test.go index 4860d1ee0..b1aca90df 100644 --- a/x/gravity/keeper/governance_proposals_test.go +++ b/x/gravity/keeper/governance_proposals_test.go @@ -3,7 +3,7 @@ package keeper import ( "testing" - disttypes "x/distribution/types" + disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/ODIN-PROTOCOL/odin-core/x/gravity/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/gravity/keeper/keeper.go b/x/gravity/keeper/keeper.go index aae6ba3c1..246400623 100644 --- a/x/gravity/keeper/keeper.go +++ b/x/gravity/keeper/keeper.go @@ -10,8 +10,8 @@ import ( ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" gethcommon "github.com/ethereum/go-ethereum/common" - distrkeeper "x/distribution/keeper" - distrtypes "x/distribution/types" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/gravity/keeper/test_gravity.go b/x/gravity/keeper/test_gravity.go index ac44c5bef..9d7e51998 100644 --- a/x/gravity/keeper/test_gravity.go +++ b/x/gravity/keeper/test_gravity.go @@ -1,781 +1,781 @@ package keeper -import ( - "bytes" - "fmt" - "testing" - "time" - - // bech32ibckeeper "github.com/althea-net/bech32-ibc/x/bech32ibc/keeper" - // bech32ibctypes "github.com/althea-net/bech32-ibc/x/bech32ibc/types" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmversion "github.com/cometbft/cometbft/proto/tendermint/version" - ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibchost "github.com/cosmos/ibc-go/v7/modules/core/24-host" - ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" - gethcommon "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" - - distrclient "github.com/ODIN-PROTOCOL/odin-core/x/distribution/client" - distrkeeper "github.com/ODIN-PROTOCOL/odin-core/x/distribution/keeper" - distrtypes "github.com/ODIN-PROTOCOL/odin-core/x/distribution/types" - - "github.com/ODIN-PROTOCOL/odin-core/x/distribution" - - "cosmossdk.io/store" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - ccodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - ccrypto "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/bank" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/evidence" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/gov" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" - paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - - gravityparams "github.com/ODIN-PROTOCOL/odin-core/app/params" - "github.com/ODIN-PROTOCOL/odin-core/x/gravity/types" -) - -const ( - Bech32MainPrefix = "odin" - Bip44CoinType = 118 -) - -// ModuleBasics is a mock module basic manager for testing -var ModuleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.AppModuleBasic{}, - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - gov.NewAppModuleBasic( - paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, - ), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - vesting.AppModuleBasic{}, -) - -var ( - // ConsPrivKeys generate ed25519 ConsPrivKeys to be used for validator operator keys - ConsPrivKeys = []ccrypto.PrivKey{ - ed25519.GenPrivKey(), - ed25519.GenPrivKey(), - ed25519.GenPrivKey(), - ed25519.GenPrivKey(), - ed25519.GenPrivKey(), - } - - // ConsPubKeys holds the consensus public keys to be used for validator operator keys - ConsPubKeys = []ccrypto.PubKey{ - ConsPrivKeys[0].PubKey(), - ConsPrivKeys[1].PubKey(), - ConsPrivKeys[2].PubKey(), - ConsPrivKeys[3].PubKey(), - ConsPrivKeys[4].PubKey(), - } - - // AccPrivKeys generate secp256k1 pubkeys to be used for account pub keys - AccPrivKeys = []ccrypto.PrivKey{ - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - } - - // AccPubKeys holds the pub keys for the account keys - AccPubKeys = []ccrypto.PubKey{ - AccPrivKeys[0].PubKey(), - AccPrivKeys[1].PubKey(), - AccPrivKeys[2].PubKey(), - AccPrivKeys[3].PubKey(), - AccPrivKeys[4].PubKey(), - } - - // AccAddrs holds the sdk.AccAddresses - AccAddrs = []sdk.AccAddress{ - sdk.AccAddress(AccPubKeys[0].Address()), - sdk.AccAddress(AccPubKeys[1].Address()), - sdk.AccAddress(AccPubKeys[2].Address()), - sdk.AccAddress(AccPubKeys[3].Address()), - sdk.AccAddress(AccPubKeys[4].Address()), - } - - // ValAddrs holds the sdk.ValAddresses - ValAddrs = []sdk.ValAddress{ - sdk.ValAddress(AccPubKeys[0].Address()), - sdk.ValAddress(AccPubKeys[1].Address()), - sdk.ValAddress(AccPubKeys[2].Address()), - sdk.ValAddress(AccPubKeys[3].Address()), - sdk.ValAddress(AccPubKeys[4].Address()), - } - - // AccPubKeys holds the pub keys for the account keys - OrchPubKeys = []ccrypto.PubKey{ - OrchPrivKeys[0].PubKey(), - OrchPrivKeys[1].PubKey(), - OrchPrivKeys[2].PubKey(), - OrchPrivKeys[3].PubKey(), - OrchPrivKeys[4].PubKey(), - } - - // Orchestrator private keys - OrchPrivKeys = []ccrypto.PrivKey{ - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - secp256k1.GenPrivKey(), - } - - // AccAddrs holds the sdk.AccAddresses - OrchAddrs = []sdk.AccAddress{ - sdk.AccAddress(OrchPubKeys[0].Address()), - sdk.AccAddress(OrchPubKeys[1].Address()), - sdk.AccAddress(OrchPubKeys[2].Address()), - sdk.AccAddress(OrchPubKeys[3].Address()), - sdk.AccAddress(OrchPubKeys[4].Address()), - } - - // TODO: generate the eth priv keys here and - // derive the address from them. - - // EthAddrs holds etheruem addresses - EthAddrs = []gethcommon.Address{ - gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(1)}, 20)), - gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(2)}, 20)), - gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(3)}, 20)), - gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(4)}, 20)), - gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(5)}, 20)), - } - - // TokenContractAddrs holds example token contract addresses - TokenContractAddrs = []string{ - "0x6b175474e89094c44da98b954eedeac495271d0f", // DAI - "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e", // YFI - "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // UNI - "0xc00e94cb662c3520282e6f5717214004a7f26888", // COMP - "0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f", // SNX - } - - // InitTokens holds the number of tokens to initialize an account with - InitTokens = sdk.TokensFromConsensusPower(110, sdk.DefaultPowerReduction) - - // InitCoins holds the number of coins to initialize an account with - InitCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, InitTokens)) - - // StakingAmount holds the staking power to start a validator with - StakingAmount = sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) - - // StakingCoins holds the staking coins to start a validator with - StakingCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, StakingAmount)) - - // TestingStakeParams is a set of staking params for testing - TestingStakeParams = stakingtypes.Params{ - UnbondingTime: 100, - MaxValidators: 10, - MaxEntries: 10, - HistoricalEntries: 10000, - BondDenom: "stake", - } - - // TestingGravityParams is a set of gravity params for testing - TestingGravityParams = types.Params{ - GravityId: "testgravityid", - ContractSourceHash: "62328f7bc12efb28f86111d08c29b39285680a906ea0e524e0209d6f6657b713", - BridgeEthereumAddress: "0x8858eeb3dfffa017d4bce9801d340d36cf895ccf", - BridgeChainId: 11, - SignedValsetsWindow: 10, - SignedBatchesWindow: 10, - SignedLogicCallsWindow: 10, - TargetBatchTimeout: 60001, - AverageBlockTime: 5000, - AverageEthereumBlockTime: 15000, - SlashFractionValset: sdk.NewDecWithPrec(1, 2), - SlashFractionBatch: sdk.NewDecWithPrec(1, 2), - SlashFractionLogicCall: sdk.Dec{}, - UnbondSlashingValsetsWindow: 15, - SlashFractionBadEthSignature: sdk.NewDecWithPrec(1, 2), - ValsetReward: sdk.Coin{Denom: "", Amount: sdk.ZeroInt()}, - BridgeActive: true, - } -) - -// TestInput stores the various keepers required to test gravity -type TestInput struct { - GravityKeeper Keeper - AccountKeeper authkeeper.AccountKeeper - StakingKeeper stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - DistKeeper distrkeeper.Keeper - BankKeeper bankkeeper.BaseKeeper - GovKeeper govkeeper.Keeper - IbcTransferKeeper ibctransferkeeper.Keeper - Context sdk.Context - Marshaler codec.Codec - LegacyAmino *codec.LegacyAmino - GravityStoreKey *sdk.KVStoreKey -} - -func SetBech32AddressPrefixesAndBip44CoinType(config *sdk.Config) { - accountPrefix := Bech32MainPrefix - validatorPrefix := Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator - consensusPrefix := Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus - config.SetBech32PrefixForAccount(accountPrefix, accountPrefix+sdk.PrefixPublic) - config.SetBech32PrefixForValidator(validatorPrefix, validatorPrefix+sdk.PrefixPublic) - config.SetBech32PrefixForConsensusNode(consensusPrefix, consensusPrefix+sdk.PrefixPublic) - config.SetCoinType(Bip44CoinType) -} - -// SetupFiveValChain does all the initialization for a 5 Validator chain using the keys here -func SetupFiveValChain(t *testing.T) (TestInput, sdk.Context) { - t.Helper() - input := CreateTestEnv(t) - SetBech32AddressPrefixesAndBip44CoinType(sdk.GetConfig()) - - // Set the params for our modules - input.StakingKeeper.SetParams(input.Context, TestingStakeParams) - - // Initialize each of the validators - sh := staking.NewHandler(input.StakingKeeper) - for i := range []int{0, 1, 2, 3, 4} { - - // Initialize the account for the key - acc := input.AccountKeeper.NewAccount( - input.Context, - authtypes.NewBaseAccount(AccAddrs[i], AccPubKeys[i], uint64(i), 0), - ) - - // Set the balance for the account - require.NoError(t, input.BankKeeper.MintCoins(input.Context, types.ModuleName, InitCoins)) - input.BankKeeper.SendCoinsFromModuleToAccount(input.Context, types.ModuleName, acc.GetAddress(), InitCoins) - - // Set the account in state - input.AccountKeeper.SetAccount(input.Context, acc) - - // Create a validator for that account using some of the tokens in the account - // and the staking handler - _, err := sh( - input.Context, - NewTestMsgCreateValidator(ValAddrs[i], ConsPubKeys[i], StakingAmount), - ) - - // Return error if one exists - require.NoError(t, err) - } - - // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, input.StakingKeeper) - - // Register eth addresses and orchestrator address for each validator - for i, addr := range ValAddrs { - ethAddr, err := types.NewEthAddress(EthAddrs[i].String()) - if err != nil { - panic("found invalid address in EthAddrs") - } - input.GravityKeeper.SetEthAddressForValidator(input.Context, addr, *ethAddr) - - input.GravityKeeper.SetOrchestratorValidator(input.Context, addr, OrchAddrs[i]) - } - - // Return the test input - return input, input.Context -} - -// SetupTestChain sets up a test environment with the provided validator voting weights -func SetupTestChain(t *testing.T, weights []uint64, setDelegateAddresses bool) (TestInput, sdk.Context) { - t.Helper() - input := CreateTestEnv(t) - - // Set the params for our modules - TestingStakeParams.MaxValidators = 100 - input.StakingKeeper.SetParams(input.Context, TestingStakeParams) - - // Initialize each of the validators - sh := staking.NewHandler(input.StakingKeeper) - for i, weight := range weights { - consPrivKey := ed25519.GenPrivKey() - consPubKey := consPrivKey.PubKey() - valPrivKey := secp256k1.GenPrivKey() - valPubKey := valPrivKey.PubKey() - valAddr := sdk.ValAddress(valPubKey.Address()) - accAddr := sdk.AccAddress(valPubKey.Address()) - - // Initialize the account for the key - acc := input.AccountKeeper.NewAccount( - input.Context, - authtypes.NewBaseAccount(accAddr, valPubKey, uint64(i), 0), - ) - - // Set the balance for the account - weightCoins := sdk.NewCoins(sdk.NewInt64Coin(TestingStakeParams.BondDenom, int64(weight))) - require.NoError(t, input.BankKeeper.MintCoins(input.Context, types.ModuleName, weightCoins)) - require.NoError(t, input.BankKeeper.SendCoinsFromModuleToAccount(input.Context, types.ModuleName, accAddr, weightCoins)) - - // Set the account in state - input.AccountKeeper.SetAccount(input.Context, acc) - - // Create a validator for that account using some of the tokens in the account - // and the staking handler - _, err := sh( - input.Context, - NewTestMsgCreateValidator(valAddr, consPubKey, sdk.NewIntFromUint64(weight)), - ) - require.NoError(t, err) - - // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, input.StakingKeeper) - - if setDelegateAddresses { - // set the delegate addresses for this key - ethAddr, err := types.NewEthAddress(gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(i)}, 20)).String()) - if err != nil { - panic("found invalid address in EthAddrs") - } - input.GravityKeeper.SetEthAddressForValidator(input.Context, valAddr, *ethAddr) - input.GravityKeeper.SetOrchestratorValidator(input.Context, valAddr, accAddr) - - // increase block height by 100 blocks - input.Context = input.Context.WithBlockHeight(input.Context.BlockHeight() + 100) - - // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, input.StakingKeeper) - - // set a request every time. - input.GravityKeeper.SetValsetRequest(input.Context) - } - - } - - // some inputs can cause the validator creation ot not work, this checks that - // everything was successful - validators := input.StakingKeeper.GetBondedValidatorsByPower(input.Context) - require.Equal(t, len(weights), len(validators)) - - // Return the test input - return input, input.Context -} - -// CreateTestEnv creates the keeper testing environment for gravity -func CreateTestEnv(t *testing.T) TestInput { - t.Helper() - - SetBech32AddressPrefixesAndBip44CoinType(sdk.GetConfig()) - - // Initialize store keys - gravityKey := sdk.NewKVStoreKey(types.StoreKey) - keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey) - keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey) - keyBank := sdk.NewKVStoreKey(banktypes.StoreKey) - keyDistro := sdk.NewKVStoreKey(distrtypes.StoreKey) - keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey) - keyGov := sdk.NewKVStoreKey(govtypes.StoreKey) - keySlashing := sdk.NewKVStoreKey(slashingtypes.StoreKey) - keyCapability := sdk.NewKVStoreKey(capabilitytypes.StoreKey) - keyUpgrade := sdk.NewKVStoreKey(upgradetypes.StoreKey) - keyIbc := sdk.NewKVStoreKey(ibchost.StoreKey) - keyIbcTransfer := sdk.NewKVStoreKey(ibctransfertypes.StoreKey) - //keyBech32Ibc := sdk.NewKVStoreKey(bech32ibctypes.StoreKey) - - // Initialize memory database and mount stores on it - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(gravityKey, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyDistro, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) - ms.MountStoreWithDB(keyGov, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keySlashing, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyCapability, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyUpgrade, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyIbc, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyIbcTransfer, sdk.StoreTypeIAVL, db) - //ms.MountStoreWithDB(keyBech32Ibc, sdk.StoreTypeIAVL, db) - err := ms.LoadLatestVersion() - require.Nil(t, err) - - // Create sdk.Context - ctx := sdk.NewContext(ms, tmproto.Header{ - Version: tmversion.Consensus{ - Block: 0, - App: 0, - }, - ChainID: "", - Height: 1234567, - Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), - LastBlockId: tmproto.BlockID{ - Hash: []byte{}, - PartSetHeader: tmproto.PartSetHeader{ - Total: 0, - Hash: []byte{}, - }, - }, - LastCommitHash: []byte{}, - DataHash: []byte{}, - ValidatorsHash: []byte{}, - NextValidatorsHash: []byte{}, - ConsensusHash: []byte{}, - AppHash: []byte{}, - LastResultsHash: []byte{}, - EvidenceHash: []byte{}, - ProposerAddress: []byte{}, - }, false, log.TestingLogger()) - - cdc := MakeTestCodec() - marshaler := MakeTestMarshaler() - - paramsKeeper := paramskeeper.NewKeeper(marshaler, cdc, keyParams, tkeyParams) - paramsKeeper.Subspace(authtypes.ModuleName) - paramsKeeper.Subspace(banktypes.ModuleName) - paramsKeeper.Subspace(stakingtypes.ModuleName) - paramsKeeper.Subspace(distrtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName) - paramsKeeper.Subspace(types.DefaultParamspace) - paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(ibchost.ModuleName) - paramsKeeper.Subspace(ibctransfertypes.ModuleName) - //paramsKeeper.Subspace(bech32ibctypes.ModuleName) - - // this is also used to initialize module accounts for all the map keys - maccPerms := map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - types.ModuleName: {authtypes.Minter, authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - } - - accountKeeper := authkeeper.NewAccountKeeper( - marshaler, - keyAcc, // target store - getSubspace(paramsKeeper, authtypes.ModuleName), - authtypes.ProtoBaseAccount, // prototype - maccPerms, - ) - - blockedAddr := make(map[string]bool, len(maccPerms)) - for acc := range maccPerms { - blockedAddr[authtypes.NewModuleAddress(acc).String()] = true - } - bankKeeper := bankkeeper.NewBaseKeeper( - marshaler, - keyBank, - accountKeeper, - getSubspace(paramsKeeper, banktypes.ModuleName), - blockedAddr, - ) - bankKeeper.SetParams(ctx, banktypes.Params{ - SendEnabled: []*banktypes.SendEnabled{}, - DefaultSendEnabled: true, - }) - - stakingKeeper := stakingkeeper.NewKeeper(marshaler, keyStaking, accountKeeper, bankKeeper, getSubspace(paramsKeeper, stakingtypes.ModuleName)) - stakingKeeper.SetParams(ctx, TestingStakeParams) - - distKeeper := distrkeeper.NewKeeper(marshaler, keyDistro, getSubspace(paramsKeeper, distrtypes.ModuleName), accountKeeper, bankKeeper, stakingKeeper, authtypes.FeeCollectorName, nil) - distKeeper.SetParams(ctx, distrtypes.DefaultParams()) - - // set genesis items required for distribution - distKeeper.SetFeePool(ctx, distrtypes.InitialFeePool()) - - // set up initial accounts - for name, perms := range maccPerms { - mod := authtypes.NewEmptyModuleAccount(name, perms...) - if name == distrtypes.ModuleName { - // some big pot to pay out - amt := sdk.NewCoins(sdk.NewInt64Coin("stake", 500000)) - err = bankKeeper.MintCoins(ctx, types.ModuleName, amt) - require.NoError(t, err) - err = bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, mod.Name, amt) - - // distribution module balance must be outstanding rewards + community pool in order to pass - // invariants checks, therefore we must add any amount we add to the module balance to the fee pool - feePool := distKeeper.GetFeePool(ctx) - newCoins := feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) - feePool.CommunityPool = newCoins - distKeeper.SetFeePool(ctx, feePool) - - require.NoError(t, err) - } - accountKeeper.SetModuleAccount(ctx, mod) - } - - stakeAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName) - moduleAcct := accountKeeper.GetAccount(ctx, stakeAddr) - require.NotNil(t, moduleAcct) - - router := baseapp.NewRouter() - router.AddRoute(bank.AppModule{ - AppModuleBasic: bank.AppModuleBasic{}, - }.Route()) - router.AddRoute(staking.AppModule{ - AppModuleBasic: staking.AppModuleBasic{}, - }.Route()) - router.AddRoute(distribution.AppModule{ - AppModuleBasic: distribution.AppModuleBasic{}, - }.Route()) - - // Load default wasm config - - govRouter := govtypes.NewRouter(). - AddRoute(paramsproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). - AddRoute(govtypes.RouterKey, govtypes.ProposalHandler) - - govKeeper := govkeeper.NewKeeper( - marshaler, keyGov, getSubspace(paramsKeeper, govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()), accountKeeper, bankKeeper, stakingKeeper, govRouter, - ) - - govKeeper.SetProposalID(ctx, govtypes.DefaultStartingProposalID) - govKeeper.SetDepositParams(ctx, govtypes.DefaultDepositParams()) - govKeeper.SetVotingParams(ctx, govtypes.DefaultVotingParams()) - govKeeper.SetTallyParams(ctx, govtypes.DefaultTallyParams()) - - slashingKeeper := slashingkeeper.NewKeeper( - marshaler, - keySlashing, - &stakingKeeper, - getSubspace(paramsKeeper, slashingtypes.ModuleName).WithKeyTable(slashingtypes.ParamKeyTable()), - ) - - bApp := *baseapp.NewBaseApp("test", log.TestingLogger(), db, MakeTestEncodingConfig().TxConfig.TxDecoder()) - upgradeKeeper := upgradekeeper.NewKeeper( - make(map[int64]bool), - keyUpgrade, - marshaler, - "", - &bApp, - ) - - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - capabilityKeeper := *capabilitykeeper.NewKeeper( - marshaler, - keyCapability, - memKeys[capabilitytypes.MemStoreKey], - ) - - scopedIbcKeeper := capabilityKeeper.ScopeToModule(ibchost.ModuleName) - ibcKeeper := *ibckeeper.NewKeeper( - marshaler, - keyIbc, - getSubspace(paramsKeeper, ibchost.ModuleName), - stakingKeeper, - upgradeKeeper, - scopedIbcKeeper, - ) - - scopedTransferKeeper := capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - ibcTransferKeeper := ibctransferkeeper.NewKeeper( - marshaler, keyIbcTransfer, getSubspace(paramsKeeper, ibctransfertypes.ModuleName), ibcKeeper.ChannelKeeper, - ibcKeeper.ChannelKeeper, &ibcKeeper.PortKeeper, - accountKeeper, bankKeeper, scopedTransferKeeper, - ) - - // bech32IbcKeeper := *bech32ibckeeper.NewKeeper( - // ibcKeeper.ChannelKeeper, marshaler, keyBech32Ibc, - // ibcTransferKeeper, - // ) - // Set the native prefix to the "gravity" value we like in module/config/config.go - // err = bech32IbcKeeper.SetNativeHrp(ctx, sdk.GetConfig().GetBech32AccountAddrPrefix()) - // if err != nil { - // panic("Test Env Creation failure, could not set native hrp") - // } - - k := NewKeeper(gravityKey, getSubspace(paramsKeeper, types.DefaultParamspace), marshaler, &bankKeeper, - &stakingKeeper, &slashingKeeper, &distKeeper, &accountKeeper, &ibcTransferKeeper) - - stakingKeeper = *stakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks( - distKeeper.Hooks(), - slashingKeeper.Hooks(), - k.Hooks(), - ), - ) - - // set gravityIDs for batches and tx items, simulating genesis setup - k.SetLatestValsetNonce(ctx, 0) - k.SetLastObservedEventNonce(ctx, 0) - k.SetLastSlashedValsetNonce(ctx, 0) - k.SetLastSlashedBatchBlock(ctx, 0) - k.SetLastSlashedLogicCallBlock(ctx, 0) - k.SetID(ctx, 0, types.KeyLastTXPoolID) - k.SetID(ctx, 0, types.KeyLastOutgoingBatchID) - - k.SetParams(ctx, TestingGravityParams) - params := k.GetParams(ctx) - - fmt.Println(params) - - testInput := TestInput{ - GravityKeeper: k, - AccountKeeper: accountKeeper, - BankKeeper: bankKeeper, - StakingKeeper: stakingKeeper, - SlashingKeeper: slashingKeeper, - DistKeeper: distKeeper, - GovKeeper: govKeeper, - Context: ctx, - Marshaler: marshaler, - LegacyAmino: cdc, - GravityStoreKey: gravityKey, - } - // check invariants before starting - testInput.Context.Logger().Info("Asserting invariants on new test env") - testInput.AssertInvariants() - return testInput -} - -// AssertInvariants tests each modules invariants individually, this is easier than -// dealing with all the init required to get the crisis keeper working properly by -// running appModuleBasic for every module and allowing them to register their invariants -func (t TestInput) AssertInvariants() { - distrInvariantFunc := distrkeeper.AllInvariants(t.DistKeeper) - bankInvariantFunc := bankkeeper.AllInvariants(t.BankKeeper) - govInvariantFunc := govkeeper.AllInvariants(t.GovKeeper, t.BankKeeper) - stakeInvariantFunc := stakingkeeper.AllInvariants(t.StakingKeeper) - gravInvariantFunc := AllInvariants(t.GravityKeeper) - - invariantStr, invariantViolated := distrInvariantFunc(t.Context) - if invariantViolated { - panic(invariantStr) - } - invariantStr, invariantViolated = bankInvariantFunc(t.Context) - if invariantViolated { - panic(invariantStr) - } - invariantStr, invariantViolated = govInvariantFunc(t.Context) - if invariantViolated { - panic(invariantStr) - } - invariantStr, invariantViolated = stakeInvariantFunc(t.Context) - if invariantViolated { - panic(invariantStr) - } - invariantStr, invariantViolated = gravInvariantFunc(t.Context) - if invariantViolated { - panic(invariantStr) - } - - t.Context.Logger().Info("All invariants successful") -} - -// getSubspace returns a param subspace for a given module name. -func getSubspace(k paramskeeper.Keeper, moduleName string) paramstypes.Subspace { - subspace, _ := k.GetSubspace(moduleName) - return subspace -} - -// MakeTestCodec creates a legacy amino codec for testing -func MakeTestCodec() *codec.LegacyAmino { - cdc := codec.NewLegacyAmino() - auth.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) - bank.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) - staking.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) - distribution.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) - sdk.RegisterLegacyAminoCodec(cdc) - ccodec.RegisterCrypto(cdc) - params.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) - types.RegisterCodec(cdc) - return cdc -} - -// MakeTestMarshaler creates a proto codec for use in testing -func MakeTestMarshaler() codec.Codec { - interfaceRegistry := codectypes.NewInterfaceRegistry() - std.RegisterInterfaces(interfaceRegistry) - ModuleBasics.RegisterInterfaces(interfaceRegistry) - types.RegisterInterfaces(interfaceRegistry) - return codec.NewProtoCodec(interfaceRegistry) -} - -func MakeTestEncodingConfig() gravityparams.EncodingConfig { - encodingConfig := gravityparams.MakeEncodingConfig() - std.RegisterLegacyAminoCodec(encodingConfig.Amino) - std.RegisterInterfaces(encodingConfig.InterfaceRegistry) - ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) - ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) - return encodingConfig -} - -// MintVouchersFromAir creates new gravity vouchers given erc20tokens -func MintVouchersFromAir(t *testing.T, ctx sdk.Context, k Keeper, dest sdk.AccAddress, amount types.InternalERC20Token) sdk.Coin { - coin := amount.GravityCoin() - vouchers := sdk.Coins{coin} - err := k.BankKeeper.MintCoins(ctx, types.ModuleName, vouchers) - require.NoError(t, err) - err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, dest, vouchers) - require.NoError(t, err) - return coin -} - -func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey ccrypto.PubKey, amt sdk.Int) *stakingtypes.MsgCreateValidator { - commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - out, err := stakingtypes.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin("stake", amt), - stakingtypes.Description{ - Moniker: "", - Identity: "", - Website: "", - SecurityContact: "", - Details: "", - }, commission, sdk.OneInt(), - ) - if err != nil { - panic(err) - } - return out -} - -func NewTestMsgUnDelegateValidator(address sdk.ValAddress, amt sdk.Int) *stakingtypes.MsgUndelegate { - msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(address), address, sdk.NewCoin("stake", amt)) - return msg -} +// import ( +// "bytes" +// "fmt" +// "testing" +// "time" + +// // bech32ibckeeper "github.com/althea-net/bech32-ibc/x/bech32ibc/keeper" +// // bech32ibctypes "github.com/althea-net/bech32-ibc/x/bech32ibc/types" + +// dbm "github.com/cometbft/cometbft-db" +// "github.com/cometbft/cometbft/libs/log" +// tmproto "github.com/cometbft/cometbft/proto/tendermint/types" +// tmversion "github.com/cometbft/cometbft/proto/tendermint/version" +// ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" +// ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" +// ibchost "github.com/cosmos/ibc-go/v7/modules/core/24-host" +// ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" +// gethcommon "github.com/ethereum/go-ethereum/common" +// "github.com/stretchr/testify/require" + +// distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" +// distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" +// distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + +// "github.com/cosmos/cosmos-sdk/x/distribution" + +// "cosmossdk.io/store" +// "github.com/cosmos/cosmos-sdk/baseapp" +// "github.com/cosmos/cosmos-sdk/codec" +// codectypes "github.com/cosmos/cosmos-sdk/codec/types" +// ccodec "github.com/cosmos/cosmos-sdk/crypto/codec" +// "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" +// "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" +// ccrypto "github.com/cosmos/cosmos-sdk/crypto/types" +// "github.com/cosmos/cosmos-sdk/std" +// sdk "github.com/cosmos/cosmos-sdk/types" +// "github.com/cosmos/cosmos-sdk/types/module" +// "github.com/cosmos/cosmos-sdk/x/auth" +// authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" +// authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +// "github.com/cosmos/cosmos-sdk/x/auth/vesting" +// "github.com/cosmos/cosmos-sdk/x/bank" +// bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" +// banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +// "github.com/cosmos/cosmos-sdk/x/capability" +// capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" +// capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +// "github.com/cosmos/cosmos-sdk/x/crisis" +// "github.com/cosmos/cosmos-sdk/x/evidence" +// "github.com/cosmos/cosmos-sdk/x/genutil" +// "github.com/cosmos/cosmos-sdk/x/gov" +// govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" +// govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" +// "github.com/cosmos/cosmos-sdk/x/mint" +// "github.com/cosmos/cosmos-sdk/x/params" +// paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" +// paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" +// paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" +// paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" +// "github.com/cosmos/cosmos-sdk/x/slashing" +// slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" +// slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" +// "github.com/cosmos/cosmos-sdk/x/staking" +// stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" +// stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +// "github.com/cosmos/cosmos-sdk/x/upgrade" +// upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" +// upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" +// upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + +// gravityparams "github.com/ODIN-PROTOCOL/odin-core/app/params" +// "github.com/ODIN-PROTOCOL/odin-core/x/gravity/types" +// ) + +// const ( +// Bech32MainPrefix = "odin" +// Bip44CoinType = 118 +// ) + +// // ModuleBasics is a mock module basic manager for testing +// var ModuleBasics = module.NewBasicManager( +// auth.AppModuleBasic{}, +// genutil.AppModuleBasic{}, +// bank.AppModuleBasic{}, +// capability.AppModuleBasic{}, +// staking.AppModuleBasic{}, +// mint.AppModuleBasic{}, +// distribution.AppModuleBasic{}, +// gov.NewAppModuleBasic( +// paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, +// ), +// params.AppModuleBasic{}, +// crisis.AppModuleBasic{}, +// slashing.AppModuleBasic{}, +// upgrade.AppModuleBasic{}, +// evidence.AppModuleBasic{}, +// vesting.AppModuleBasic{}, +// ) + +// var ( +// // ConsPrivKeys generate ed25519 ConsPrivKeys to be used for validator operator keys +// ConsPrivKeys = []ccrypto.PrivKey{ +// ed25519.GenPrivKey(), +// ed25519.GenPrivKey(), +// ed25519.GenPrivKey(), +// ed25519.GenPrivKey(), +// ed25519.GenPrivKey(), +// } + +// // ConsPubKeys holds the consensus public keys to be used for validator operator keys +// ConsPubKeys = []ccrypto.PubKey{ +// ConsPrivKeys[0].PubKey(), +// ConsPrivKeys[1].PubKey(), +// ConsPrivKeys[2].PubKey(), +// ConsPrivKeys[3].PubKey(), +// ConsPrivKeys[4].PubKey(), +// } + +// // AccPrivKeys generate secp256k1 pubkeys to be used for account pub keys +// AccPrivKeys = []ccrypto.PrivKey{ +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// } + +// // AccPubKeys holds the pub keys for the account keys +// AccPubKeys = []ccrypto.PubKey{ +// AccPrivKeys[0].PubKey(), +// AccPrivKeys[1].PubKey(), +// AccPrivKeys[2].PubKey(), +// AccPrivKeys[3].PubKey(), +// AccPrivKeys[4].PubKey(), +// } + +// // AccAddrs holds the sdk.AccAddresses +// AccAddrs = []sdk.AccAddress{ +// sdk.AccAddress(AccPubKeys[0].Address()), +// sdk.AccAddress(AccPubKeys[1].Address()), +// sdk.AccAddress(AccPubKeys[2].Address()), +// sdk.AccAddress(AccPubKeys[3].Address()), +// sdk.AccAddress(AccPubKeys[4].Address()), +// } + +// // ValAddrs holds the sdk.ValAddresses +// ValAddrs = []sdk.ValAddress{ +// sdk.ValAddress(AccPubKeys[0].Address()), +// sdk.ValAddress(AccPubKeys[1].Address()), +// sdk.ValAddress(AccPubKeys[2].Address()), +// sdk.ValAddress(AccPubKeys[3].Address()), +// sdk.ValAddress(AccPubKeys[4].Address()), +// } + +// // AccPubKeys holds the pub keys for the account keys +// OrchPubKeys = []ccrypto.PubKey{ +// OrchPrivKeys[0].PubKey(), +// OrchPrivKeys[1].PubKey(), +// OrchPrivKeys[2].PubKey(), +// OrchPrivKeys[3].PubKey(), +// OrchPrivKeys[4].PubKey(), +// } + +// // Orchestrator private keys +// OrchPrivKeys = []ccrypto.PrivKey{ +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// secp256k1.GenPrivKey(), +// } + +// // AccAddrs holds the sdk.AccAddresses +// OrchAddrs = []sdk.AccAddress{ +// sdk.AccAddress(OrchPubKeys[0].Address()), +// sdk.AccAddress(OrchPubKeys[1].Address()), +// sdk.AccAddress(OrchPubKeys[2].Address()), +// sdk.AccAddress(OrchPubKeys[3].Address()), +// sdk.AccAddress(OrchPubKeys[4].Address()), +// } + +// // TODO: generate the eth priv keys here and +// // derive the address from them. + +// // EthAddrs holds etheruem addresses +// EthAddrs = []gethcommon.Address{ +// gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(1)}, 20)), +// gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(2)}, 20)), +// gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(3)}, 20)), +// gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(4)}, 20)), +// gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(5)}, 20)), +// } + +// // TokenContractAddrs holds example token contract addresses +// TokenContractAddrs = []string{ +// "0x6b175474e89094c44da98b954eedeac495271d0f", // DAI +// "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e", // YFI +// "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // UNI +// "0xc00e94cb662c3520282e6f5717214004a7f26888", // COMP +// "0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f", // SNX +// } + +// // InitTokens holds the number of tokens to initialize an account with +// InitTokens = sdk.TokensFromConsensusPower(110, sdk.DefaultPowerReduction) + +// // InitCoins holds the number of coins to initialize an account with +// InitCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, InitTokens)) + +// // StakingAmount holds the staking power to start a validator with +// StakingAmount = sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) + +// // StakingCoins holds the staking coins to start a validator with +// StakingCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, StakingAmount)) + +// // TestingStakeParams is a set of staking params for testing +// TestingStakeParams = stakingtypes.Params{ +// UnbondingTime: 100, +// MaxValidators: 10, +// MaxEntries: 10, +// HistoricalEntries: 10000, +// BondDenom: "stake", +// } + +// // TestingGravityParams is a set of gravity params for testing +// TestingGravityParams = types.Params{ +// GravityId: "testgravityid", +// ContractSourceHash: "62328f7bc12efb28f86111d08c29b39285680a906ea0e524e0209d6f6657b713", +// BridgeEthereumAddress: "0x8858eeb3dfffa017d4bce9801d340d36cf895ccf", +// BridgeChainId: 11, +// SignedValsetsWindow: 10, +// SignedBatchesWindow: 10, +// SignedLogicCallsWindow: 10, +// TargetBatchTimeout: 60001, +// AverageBlockTime: 5000, +// AverageEthereumBlockTime: 15000, +// SlashFractionValset: sdk.NewDecWithPrec(1, 2), +// SlashFractionBatch: sdk.NewDecWithPrec(1, 2), +// SlashFractionLogicCall: sdk.Dec{}, +// UnbondSlashingValsetsWindow: 15, +// SlashFractionBadEthSignature: sdk.NewDecWithPrec(1, 2), +// ValsetReward: sdk.Coin{Denom: "", Amount: sdk.ZeroInt()}, +// BridgeActive: true, +// } +// ) + +// // TestInput stores the various keepers required to test gravity +// type TestInput struct { +// GravityKeeper Keeper +// AccountKeeper authkeeper.AccountKeeper +// StakingKeeper stakingkeeper.Keeper +// SlashingKeeper slashingkeeper.Keeper +// DistKeeper distrkeeper.Keeper +// BankKeeper bankkeeper.BaseKeeper +// GovKeeper govkeeper.Keeper +// IbcTransferKeeper ibctransferkeeper.Keeper +// Context sdk.Context +// Marshaler codec.Codec +// LegacyAmino *codec.LegacyAmino +// GravityStoreKey *sdk.KVStoreKey +// } + +// func SetBech32AddressPrefixesAndBip44CoinType(config *sdk.Config) { +// accountPrefix := Bech32MainPrefix +// validatorPrefix := Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator +// consensusPrefix := Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus +// config.SetBech32PrefixForAccount(accountPrefix, accountPrefix+sdk.PrefixPublic) +// config.SetBech32PrefixForValidator(validatorPrefix, validatorPrefix+sdk.PrefixPublic) +// config.SetBech32PrefixForConsensusNode(consensusPrefix, consensusPrefix+sdk.PrefixPublic) +// config.SetCoinType(Bip44CoinType) +// } + +// // SetupFiveValChain does all the initialization for a 5 Validator chain using the keys here +// func SetupFiveValChain(t *testing.T) (TestInput, sdk.Context) { +// t.Helper() +// input := CreateTestEnv(t) +// SetBech32AddressPrefixesAndBip44CoinType(sdk.GetConfig()) + +// // Set the params for our modules +// input.StakingKeeper.SetParams(input.Context, TestingStakeParams) + +// // Initialize each of the validators +// sh := staking.NewHandler(input.StakingKeeper) +// for i := range []int{0, 1, 2, 3, 4} { + +// // Initialize the account for the key +// acc := input.AccountKeeper.NewAccount( +// input.Context, +// authtypes.NewBaseAccount(AccAddrs[i], AccPubKeys[i], uint64(i), 0), +// ) + +// // Set the balance for the account +// require.NoError(t, input.BankKeeper.MintCoins(input.Context, types.ModuleName, InitCoins)) +// input.BankKeeper.SendCoinsFromModuleToAccount(input.Context, types.ModuleName, acc.GetAddress(), InitCoins) + +// // Set the account in state +// input.AccountKeeper.SetAccount(input.Context, acc) + +// // Create a validator for that account using some of the tokens in the account +// // and the staking handler +// _, err := sh( +// input.Context, +// NewTestMsgCreateValidator(ValAddrs[i], ConsPubKeys[i], StakingAmount), +// ) + +// // Return error if one exists +// require.NoError(t, err) +// } + +// // Run the staking endblocker to ensure valset is correct in state +// staking.EndBlocker(input.Context, input.StakingKeeper) + +// // Register eth addresses and orchestrator address for each validator +// for i, addr := range ValAddrs { +// ethAddr, err := types.NewEthAddress(EthAddrs[i].String()) +// if err != nil { +// panic("found invalid address in EthAddrs") +// } +// input.GravityKeeper.SetEthAddressForValidator(input.Context, addr, *ethAddr) + +// input.GravityKeeper.SetOrchestratorValidator(input.Context, addr, OrchAddrs[i]) +// } + +// // Return the test input +// return input, input.Context +// } + +// // SetupTestChain sets up a test environment with the provided validator voting weights +// func SetupTestChain(t *testing.T, weights []uint64, setDelegateAddresses bool) (TestInput, sdk.Context) { +// t.Helper() +// input := CreateTestEnv(t) + +// // Set the params for our modules +// TestingStakeParams.MaxValidators = 100 +// input.StakingKeeper.SetParams(input.Context, TestingStakeParams) + +// // Initialize each of the validators +// sh := staking.NewHandler(input.StakingKeeper) +// for i, weight := range weights { +// consPrivKey := ed25519.GenPrivKey() +// consPubKey := consPrivKey.PubKey() +// valPrivKey := secp256k1.GenPrivKey() +// valPubKey := valPrivKey.PubKey() +// valAddr := sdk.ValAddress(valPubKey.Address()) +// accAddr := sdk.AccAddress(valPubKey.Address()) + +// // Initialize the account for the key +// acc := input.AccountKeeper.NewAccount( +// input.Context, +// authtypes.NewBaseAccount(accAddr, valPubKey, uint64(i), 0), +// ) + +// // Set the balance for the account +// weightCoins := sdk.NewCoins(sdk.NewInt64Coin(TestingStakeParams.BondDenom, int64(weight))) +// require.NoError(t, input.BankKeeper.MintCoins(input.Context, types.ModuleName, weightCoins)) +// require.NoError(t, input.BankKeeper.SendCoinsFromModuleToAccount(input.Context, types.ModuleName, accAddr, weightCoins)) + +// // Set the account in state +// input.AccountKeeper.SetAccount(input.Context, acc) + +// // Create a validator for that account using some of the tokens in the account +// // and the staking handler +// _, err := sh( +// input.Context, +// NewTestMsgCreateValidator(valAddr, consPubKey, sdk.NewIntFromUint64(weight)), +// ) +// require.NoError(t, err) + +// // Run the staking endblocker to ensure valset is correct in state +// staking.EndBlocker(input.Context, input.StakingKeeper) + +// if setDelegateAddresses { +// // set the delegate addresses for this key +// ethAddr, err := types.NewEthAddress(gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(i)}, 20)).String()) +// if err != nil { +// panic("found invalid address in EthAddrs") +// } +// input.GravityKeeper.SetEthAddressForValidator(input.Context, valAddr, *ethAddr) +// input.GravityKeeper.SetOrchestratorValidator(input.Context, valAddr, accAddr) + +// // increase block height by 100 blocks +// input.Context = input.Context.WithBlockHeight(input.Context.BlockHeight() + 100) + +// // Run the staking endblocker to ensure valset is correct in state +// staking.EndBlocker(input.Context, input.StakingKeeper) + +// // set a request every time. +// input.GravityKeeper.SetValsetRequest(input.Context) +// } + +// } + +// // some inputs can cause the validator creation ot not work, this checks that +// // everything was successful +// validators := input.StakingKeeper.GetBondedValidatorsByPower(input.Context) +// require.Equal(t, len(weights), len(validators)) + +// // Return the test input +// return input, input.Context +// } + +// // CreateTestEnv creates the keeper testing environment for gravity +// func CreateTestEnv(t *testing.T) TestInput { +// t.Helper() + +// SetBech32AddressPrefixesAndBip44CoinType(sdk.GetConfig()) + +// // Initialize store keys +// gravityKey := sdk.NewKVStoreKey(types.StoreKey) +// keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey) +// keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey) +// keyBank := sdk.NewKVStoreKey(banktypes.StoreKey) +// keyDistro := sdk.NewKVStoreKey(distrtypes.StoreKey) +// keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey) +// tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey) +// keyGov := sdk.NewKVStoreKey(govtypes.StoreKey) +// keySlashing := sdk.NewKVStoreKey(slashingtypes.StoreKey) +// keyCapability := sdk.NewKVStoreKey(capabilitytypes.StoreKey) +// keyUpgrade := sdk.NewKVStoreKey(upgradetypes.StoreKey) +// keyIbc := sdk.NewKVStoreKey(ibchost.StoreKey) +// keyIbcTransfer := sdk.NewKVStoreKey(ibctransfertypes.StoreKey) +// //keyBech32Ibc := sdk.NewKVStoreKey(bech32ibctypes.StoreKey) + +// // Initialize memory database and mount stores on it +// db := dbm.NewMemDB() +// ms := store.NewCommitMultiStore(db) +// ms.MountStoreWithDB(gravityKey, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyDistro, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) +// ms.MountStoreWithDB(keyGov, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keySlashing, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyCapability, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyUpgrade, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyIbc, sdk.StoreTypeIAVL, db) +// ms.MountStoreWithDB(keyIbcTransfer, sdk.StoreTypeIAVL, db) +// //ms.MountStoreWithDB(keyBech32Ibc, sdk.StoreTypeIAVL, db) +// err := ms.LoadLatestVersion() +// require.Nil(t, err) + +// // Create sdk.Context +// ctx := sdk.NewContext(ms, tmproto.Header{ +// Version: tmversion.Consensus{ +// Block: 0, +// App: 0, +// }, +// ChainID: "", +// Height: 1234567, +// Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), +// LastBlockId: tmproto.BlockID{ +// Hash: []byte{}, +// PartSetHeader: tmproto.PartSetHeader{ +// Total: 0, +// Hash: []byte{}, +// }, +// }, +// LastCommitHash: []byte{}, +// DataHash: []byte{}, +// ValidatorsHash: []byte{}, +// NextValidatorsHash: []byte{}, +// ConsensusHash: []byte{}, +// AppHash: []byte{}, +// LastResultsHash: []byte{}, +// EvidenceHash: []byte{}, +// ProposerAddress: []byte{}, +// }, false, log.TestingLogger()) + +// cdc := MakeTestCodec() +// marshaler := MakeTestMarshaler() + +// paramsKeeper := paramskeeper.NewKeeper(marshaler, cdc, keyParams, tkeyParams) +// paramsKeeper.Subspace(authtypes.ModuleName) +// paramsKeeper.Subspace(banktypes.ModuleName) +// paramsKeeper.Subspace(stakingtypes.ModuleName) +// paramsKeeper.Subspace(distrtypes.ModuleName) +// paramsKeeper.Subspace(govtypes.ModuleName) +// paramsKeeper.Subspace(types.DefaultParamspace) +// paramsKeeper.Subspace(slashingtypes.ModuleName) +// paramsKeeper.Subspace(ibchost.ModuleName) +// paramsKeeper.Subspace(ibctransfertypes.ModuleName) +// //paramsKeeper.Subspace(bech32ibctypes.ModuleName) + +// // this is also used to initialize module accounts for all the map keys +// maccPerms := map[string][]string{ +// authtypes.FeeCollectorName: nil, +// distrtypes.ModuleName: nil, +// stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, +// stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, +// govtypes.ModuleName: {authtypes.Burner}, +// types.ModuleName: {authtypes.Minter, authtypes.Burner}, +// ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, +// } + +// accountKeeper := authkeeper.NewAccountKeeper( +// marshaler, +// keyAcc, // target store +// getSubspace(paramsKeeper, authtypes.ModuleName), +// authtypes.ProtoBaseAccount, // prototype +// maccPerms, +// ) + +// blockedAddr := make(map[string]bool, len(maccPerms)) +// for acc := range maccPerms { +// blockedAddr[authtypes.NewModuleAddress(acc).String()] = true +// } +// bankKeeper := bankkeeper.NewBaseKeeper( +// marshaler, +// keyBank, +// accountKeeper, +// getSubspace(paramsKeeper, banktypes.ModuleName), +// blockedAddr, +// ) +// bankKeeper.SetParams(ctx, banktypes.Params{ +// SendEnabled: []*banktypes.SendEnabled{}, +// DefaultSendEnabled: true, +// }) + +// stakingKeeper := stakingkeeper.NewKeeper(marshaler, keyStaking, accountKeeper, bankKeeper, getSubspace(paramsKeeper, stakingtypes.ModuleName)) +// stakingKeeper.SetParams(ctx, TestingStakeParams) + +// distKeeper := distrkeeper.NewKeeper(marshaler, keyDistro, getSubspace(paramsKeeper, distrtypes.ModuleName), accountKeeper, bankKeeper, stakingKeeper, authtypes.FeeCollectorName, nil) +// distKeeper.SetParams(ctx, distrtypes.DefaultParams()) + +// // set genesis items required for distribution +// distKeeper.SetFeePool(ctx, distrtypes.InitialFeePool()) + +// // set up initial accounts +// for name, perms := range maccPerms { +// mod := authtypes.NewEmptyModuleAccount(name, perms...) +// if name == distrtypes.ModuleName { +// // some big pot to pay out +// amt := sdk.NewCoins(sdk.NewInt64Coin("stake", 500000)) +// err = bankKeeper.MintCoins(ctx, types.ModuleName, amt) +// require.NoError(t, err) +// err = bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, mod.Name, amt) + +// // distribution module balance must be outstanding rewards + community pool in order to pass +// // invariants checks, therefore we must add any amount we add to the module balance to the fee pool +// feePool := distKeeper.GetFeePool(ctx) +// newCoins := feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) +// feePool.CommunityPool = newCoins +// distKeeper.SetFeePool(ctx, feePool) + +// require.NoError(t, err) +// } +// accountKeeper.SetModuleAccount(ctx, mod) +// } + +// stakeAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName) +// moduleAcct := accountKeeper.GetAccount(ctx, stakeAddr) +// require.NotNil(t, moduleAcct) + +// router := baseapp.NewRouter() +// router.AddRoute(bank.AppModule{ +// AppModuleBasic: bank.AppModuleBasic{}, +// }.Route()) +// router.AddRoute(staking.AppModule{ +// AppModuleBasic: staking.AppModuleBasic{}, +// }.Route()) +// router.AddRoute(distribution.AppModule{ +// AppModuleBasic: distribution.AppModuleBasic{}, +// }.Route()) + +// // Load default wasm config + +// govRouter := govtypes.NewRouter(). +// AddRoute(paramsproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). +// AddRoute(govtypes.RouterKey, govtypes.ProposalHandler) + +// govKeeper := govkeeper.NewKeeper( +// marshaler, keyGov, getSubspace(paramsKeeper, govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()), accountKeeper, bankKeeper, stakingKeeper, govRouter, +// ) + +// govKeeper.SetProposalID(ctx, govtypes.DefaultStartingProposalID) +// govKeeper.SetDepositParams(ctx, govtypes.DefaultDepositParams()) +// govKeeper.SetVotingParams(ctx, govtypes.DefaultVotingParams()) +// govKeeper.SetTallyParams(ctx, govtypes.DefaultTallyParams()) + +// slashingKeeper := slashingkeeper.NewKeeper( +// marshaler, +// keySlashing, +// &stakingKeeper, +// getSubspace(paramsKeeper, slashingtypes.ModuleName).WithKeyTable(slashingtypes.ParamKeyTable()), +// ) + +// bApp := *baseapp.NewBaseApp("test", log.TestingLogger(), db, MakeTestEncodingConfig().TxConfig.TxDecoder()) +// upgradeKeeper := upgradekeeper.NewKeeper( +// make(map[int64]bool), +// keyUpgrade, +// marshaler, +// "", +// &bApp, +// ) + +// memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) +// capabilityKeeper := *capabilitykeeper.NewKeeper( +// marshaler, +// keyCapability, +// memKeys[capabilitytypes.MemStoreKey], +// ) + +// scopedIbcKeeper := capabilityKeeper.ScopeToModule(ibchost.ModuleName) +// ibcKeeper := *ibckeeper.NewKeeper( +// marshaler, +// keyIbc, +// getSubspace(paramsKeeper, ibchost.ModuleName), +// stakingKeeper, +// upgradeKeeper, +// scopedIbcKeeper, +// ) + +// scopedTransferKeeper := capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) +// ibcTransferKeeper := ibctransferkeeper.NewKeeper( +// marshaler, keyIbcTransfer, getSubspace(paramsKeeper, ibctransfertypes.ModuleName), ibcKeeper.ChannelKeeper, +// ibcKeeper.ChannelKeeper, &ibcKeeper.PortKeeper, +// accountKeeper, bankKeeper, scopedTransferKeeper, +// ) + +// // bech32IbcKeeper := *bech32ibckeeper.NewKeeper( +// // ibcKeeper.ChannelKeeper, marshaler, keyBech32Ibc, +// // ibcTransferKeeper, +// // ) +// // Set the native prefix to the "gravity" value we like in module/config/config.go +// // err = bech32IbcKeeper.SetNativeHrp(ctx, sdk.GetConfig().GetBech32AccountAddrPrefix()) +// // if err != nil { +// // panic("Test Env Creation failure, could not set native hrp") +// // } + +// k := NewKeeper(gravityKey, getSubspace(paramsKeeper, types.DefaultParamspace), marshaler, &bankKeeper, +// &stakingKeeper, &slashingKeeper, &distKeeper, &accountKeeper, &ibcTransferKeeper) + +// stakingKeeper = *stakingKeeper.SetHooks( +// stakingtypes.NewMultiStakingHooks( +// distKeeper.Hooks(), +// slashingKeeper.Hooks(), +// k.Hooks(), +// ), +// ) + +// // set gravityIDs for batches and tx items, simulating genesis setup +// k.SetLatestValsetNonce(ctx, 0) +// k.SetLastObservedEventNonce(ctx, 0) +// k.SetLastSlashedValsetNonce(ctx, 0) +// k.SetLastSlashedBatchBlock(ctx, 0) +// k.SetLastSlashedLogicCallBlock(ctx, 0) +// k.SetID(ctx, 0, types.KeyLastTXPoolID) +// k.SetID(ctx, 0, types.KeyLastOutgoingBatchID) + +// k.SetParams(ctx, TestingGravityParams) +// params := k.GetParams(ctx) + +// fmt.Println(params) + +// testInput := TestInput{ +// GravityKeeper: k, +// AccountKeeper: accountKeeper, +// BankKeeper: bankKeeper, +// StakingKeeper: stakingKeeper, +// SlashingKeeper: slashingKeeper, +// DistKeeper: distKeeper, +// GovKeeper: govKeeper, +// Context: ctx, +// Marshaler: marshaler, +// LegacyAmino: cdc, +// GravityStoreKey: gravityKey, +// } +// // check invariants before starting +// testInput.Context.Logger().Info("Asserting invariants on new test env") +// testInput.AssertInvariants() +// return testInput +// } + +// // AssertInvariants tests each modules invariants individually, this is easier than +// // dealing with all the init required to get the crisis keeper working properly by +// // running appModuleBasic for every module and allowing them to register their invariants +// func (t TestInput) AssertInvariants() { +// distrInvariantFunc := distrkeeper.AllInvariants(t.DistKeeper) +// bankInvariantFunc := bankkeeper.AllInvariants(t.BankKeeper) +// govInvariantFunc := govkeeper.AllInvariants(t.GovKeeper, t.BankKeeper) +// stakeInvariantFunc := stakingkeeper.AllInvariants(t.StakingKeeper) +// gravInvariantFunc := AllInvariants(t.GravityKeeper) + +// invariantStr, invariantViolated := distrInvariantFunc(t.Context) +// if invariantViolated { +// panic(invariantStr) +// } +// invariantStr, invariantViolated = bankInvariantFunc(t.Context) +// if invariantViolated { +// panic(invariantStr) +// } +// invariantStr, invariantViolated = govInvariantFunc(t.Context) +// if invariantViolated { +// panic(invariantStr) +// } +// invariantStr, invariantViolated = stakeInvariantFunc(t.Context) +// if invariantViolated { +// panic(invariantStr) +// } +// invariantStr, invariantViolated = gravInvariantFunc(t.Context) +// if invariantViolated { +// panic(invariantStr) +// } + +// t.Context.Logger().Info("All invariants successful") +// } + +// // getSubspace returns a param subspace for a given module name. +// func getSubspace(k paramskeeper.Keeper, moduleName string) paramstypes.Subspace { +// subspace, _ := k.GetSubspace(moduleName) +// return subspace +// } + +// // MakeTestCodec creates a legacy amino codec for testing +// func MakeTestCodec() *codec.LegacyAmino { +// cdc := codec.NewLegacyAmino() +// auth.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) +// bank.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) +// staking.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) +// distribution.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) +// sdk.RegisterLegacyAminoCodec(cdc) +// ccodec.RegisterCrypto(cdc) +// params.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc) +// types.RegisterCodec(cdc) +// return cdc +// } + +// // MakeTestMarshaler creates a proto codec for use in testing +// func MakeTestMarshaler() codec.Codec { +// interfaceRegistry := codectypes.NewInterfaceRegistry() +// std.RegisterInterfaces(interfaceRegistry) +// ModuleBasics.RegisterInterfaces(interfaceRegistry) +// types.RegisterInterfaces(interfaceRegistry) +// return codec.NewProtoCodec(interfaceRegistry) +// } + +// func MakeTestEncodingConfig() gravityparams.EncodingConfig { +// encodingConfig := gravityparams.MakeEncodingConfig() +// std.RegisterLegacyAminoCodec(encodingConfig.Amino) +// std.RegisterInterfaces(encodingConfig.InterfaceRegistry) +// ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) +// ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) +// return encodingConfig +// } + +// // MintVouchersFromAir creates new gravity vouchers given erc20tokens +// func MintVouchersFromAir(t *testing.T, ctx sdk.Context, k Keeper, dest sdk.AccAddress, amount types.InternalERC20Token) sdk.Coin { +// coin := amount.GravityCoin() +// vouchers := sdk.Coins{coin} +// err := k.BankKeeper.MintCoins(ctx, types.ModuleName, vouchers) +// require.NoError(t, err) +// err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, dest, vouchers) +// require.NoError(t, err) +// return coin +// } + +// func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey ccrypto.PubKey, amt sdk.Int) *stakingtypes.MsgCreateValidator { +// commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) +// out, err := stakingtypes.NewMsgCreateValidator( +// address, pubKey, sdk.NewCoin("stake", amt), +// stakingtypes.Description{ +// Moniker: "", +// Identity: "", +// Website: "", +// SecurityContact: "", +// Details: "", +// }, commission, sdk.OneInt(), +// ) +// if err != nil { +// panic(err) +// } +// return out +// } + +// func NewTestMsgUnDelegateValidator(address sdk.ValAddress, amt sdk.Int) *stakingtypes.MsgUndelegate { +// msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(address), address, sdk.NewCoin("stake", amt)) +// return msg +// } diff --git a/x/gravity/types/expected_keepers.go b/x/gravity/types/expected_keepers.go index 1a02da20e..9188fd390 100644 --- a/x/gravity/types/expected_keepers.go +++ b/x/gravity/types/expected_keepers.go @@ -3,7 +3,7 @@ package types import ( "time" - "x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" bank "github.com/cosmos/cosmos-sdk/x/bank/types" diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index 495104490..610758cb6 100755 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "testing" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/ODIN-PROTOCOL/odin-core/x/common/testapp" minttypes "github.com/ODIN-PROTOCOL/odin-core/x/mint/types" diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index feaef2c0c..db2a6b968 100755 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/ODIN-PROTOCOL/odin-core/x/common/testapp" "github.com/ODIN-PROTOCOL/odin-core/x/oracle" diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index eb602de41..ebd7472ce 100755 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/ODIN-PROTOCOL/odin-core/pkg/obi" "github.com/ODIN-PROTOCOL/odin-core/x/common/testapp" diff --git a/x/oracle/keeper/reward.go b/x/oracle/keeper/reward.go index db37896e3..e8bdcf507 100644 --- a/x/oracle/keeper/reward.go +++ b/x/oracle/keeper/reward.go @@ -1,7 +1,7 @@ package oraclekeeper import ( - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/oracle/keeper/validator_status.go b/x/oracle/keeper/validator_status.go index e16c69078..b7fa90525 100644 --- a/x/oracle/keeper/validator_status.go +++ b/x/oracle/keeper/validator_status.go @@ -5,7 +5,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" - distr "x/distribution/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 0d4bac082..6b973df86 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -5,7 +5,7 @@ import ( channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - distrtypes "github.com/ODIN-PROTOCOL/odin-core/x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/slashing/migrations/v2/store.go b/x/slashing/migrations/v2/store.go index 13317fc80..f6bcae6dc 100644 --- a/x/slashing/migrations/v2/store.go +++ b/x/slashing/migrations/v2/store.go @@ -1,7 +1,7 @@ package v2 import ( - v2distribution "x/distribution/migrations/v2" + v2distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 66070527e..4662138c8 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -13,8 +13,8 @@ import ( "cosmossdk.io/math" - distributionkeeper "x/distribution/keeper" - distrtypes "x/distribution/types" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" diff --git a/x/slashing/testutil/app_config.go b/x/slashing/testutil/app_config.go index d7fda76ac..0686eba37 100644 --- a/x/slashing/testutil/app_config.go +++ b/x/slashing/testutil/app_config.go @@ -13,7 +13,7 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/slashing" _ "github.com/cosmos/cosmos-sdk/x/staking" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "cosmossdk.io/core/appconfig" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/staking/migrations/v2/store.go b/x/staking/migrations/v2/store.go index 8301aad7c..259f31ed1 100644 --- a/x/staking/migrations/v2/store.go +++ b/x/staking/migrations/v2/store.go @@ -1,7 +1,7 @@ package v2 import ( - v2distribution "x/distribution/migrations/v2" + v2distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 8c2b5b689..921447253 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -25,14 +25,14 @@ import ( moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/staking/types" - distrkeeper "x/distribution/keeper" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" diff --git a/x/staking/testutil/app_config.go b/x/staking/testutil/app_config.go index 6866fa450..9bef2e245 100644 --- a/x/staking/testutil/app_config.go +++ b/x/staking/testutil/app_config.go @@ -13,7 +13,7 @@ import ( _ "github.com/cosmos/cosmos-sdk/x/slashing" _ "github.com/cosmos/cosmos-sdk/x/staking" - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "cosmossdk.io/core/appconfig" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" diff --git a/x/telemetry/keeper/keeper.go b/x/telemetry/keeper/keeper.go index 7a0c37658..859827d68 100644 --- a/x/telemetry/keeper/keeper.go +++ b/x/telemetry/keeper/keeper.go @@ -4,7 +4,7 @@ import ( "sort" "time" - distrkeeper "x/distribution/keeper" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/telemetry/types/expected_keepers.go b/x/telemetry/types/expected_keepers.go index c3bcffee6..af70de5e3 100644 --- a/x/telemetry/types/expected_keepers.go +++ b/x/telemetry/types/expected_keepers.go @@ -1,7 +1,7 @@ package types import ( - distrtypes "x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" )