migrate: add dxns module

1. add bond,auction, nameserivce module
2. update to v0.12.2 ethermint version
3. fix the test cases
4. add gql server
This commit is contained in:
Sai Kumar
2022-04-05 12:39:27 +05:30
parent 4ddc8afd18
commit e90b21bc8e
137 changed files with 56381 additions and 26 deletions
+196
View File
@@ -0,0 +1,196 @@
# Build chain
```bash
# it will create binary in build folder with `ethermintd`
$ make build
```
# Setup Chain
```bash
./build/ethermintd keys add root
./build/ethermintd init test-moniker --chain-id ethermint_9000-1
./build/ethermintd add-genesis-account $(./build/ethermintd keys show root -a) 1000000000000000000aphoton,1000000000000000000stake
./build/ethermintd gentx root 1000000000000000000stake --chain-id ethermint_9000-1
./build/ethermintd collect-gentxs
./build/ethermintd start
```
# Params
```
$ ./build/ethermintd q bond params -o json | jq .
{
"params": {
"max_bond_amount": {
"denom": "stake",
"amount": "100000000000"
}
}
}
```
# Create Bond
```
$ ./build/ethermintd tx bond create 100aphoton --from root --chain-id $(./build/ethermintd status | jq .NodeInfo.network -r)
{"body":{"messages":[{"@type":"/vulcanize.bond.v1beta1.MsgCreateBond","signer":"ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk","coins":[{"denom":"aphoton","amount":"100"}]}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}
confirm transaction before signing and broadcasting [y/N]: y
code: 0
codespace: ""
data: ""
gas_used: "0"
gas_wanted: "0"
height: "0"
info: ""
logs: []
raw_log: '[]'
timestamp: ""
tx: null
txhash: C6D362E11D4C9FB06D620F3CCAF363A69A074297A00E9CAECBDA5BE1CC302EB8
```
# Refill Bond
```
$ ./build/ethermintd tx bond refill c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440 1000aphoton --from root --chain-id $(./build/ethermintd status | jq .NodeInfo.network -r)
{"body":{"messages":[{"@type":"/vulcanize.bond.v1beta1.MsgRefillBond","id":"c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440","signer":"ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk","coins":[{"denom":"aphoton","amount":"1000"}]}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}
confirm transaction before signing and broadcasting [y/N]: y
code: 0
codespace: ""
data: ""
gas_used: "0"
gas_wanted: "0"
height: "0"
info: ""
logs: []
raw_log: '[]'
timestamp: ""
tx: null
txhash: 025B04E2C923EFE2299CD171B40829CB1FE4D1A69DA7563C64AAC3D5C27BDFC9
```
# Withdraw from bond
```
$ ./build/ethermintd tx bond withdraw c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440 1000aphoton --from root --chain-id $(./build/ethermintd status | jq .NodeInfo.network -r)
{"body":{"messages":[{"@type":"/vulcanize.bond.v1beta1.MsgWithdrawBond","id":"c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440","signer":"ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk","coins":[{"denom":"aphoton","amount":"1000"}]}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}
confirm transaction before signing and broadcasting [y/N]: y
code: 0
codespace: ""
data: ""
gas_used: "0"
gas_wanted: "0"
height: "0"
info: ""
logs: []
raw_log: '[]'
timestamp: ""
tx: null
txhash: 7C5E2FE674577CD6BFFF9F92FCCBC61EDFE8F1A00CE29AC84D58FB8F013D2F03
```
# List Bond
```
$ ./build/ethermintd q bond list -o json | jq .
{
"bonds": [
{
"id": "c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440",
"owner": "ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk",
"balance": [
{
"denom": "aphoton",
"amount": "100"
}
]
}
],
"pagination": null
}
```
# Get Bond by Id
```
$ ./build/ethermintd q bond get c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440 -o json | jq .
{
"bond": {
"id": "c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440",
"owner": "ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk",
"balance": [
{
"denom": "aphoton",
"amount": "100"
}
]
}
}
```
# Get Bond Module Balance
```
$ ./build/ethermintd q bond balance -o json | jq .
{
"balance": [
{
"denom": "aphoton",
"amount": "100"
}
]
}
```
# Get Bonds By Owner
```
$ ./build/ethermintd q bond by-owner ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk -o json | jq .
{
"bonds": [
{
"id": "c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440",
"owner": "ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk",
"balance": [
{
"denom": "aphoton",
"amount": "100"
}
]
}
],
"pagination": null
}
```
# Cancel the bond
```
$ ./build/ethermintd tx bond cancel c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440 --from root --chain-id $(./build/ethermintd status | jq .NodeInfo.network -r)
{"body":{"messages":[{"@type":"/vulcanize.bond.v1beta1.MsgCancelBond","id":"c3f7a78c5042d2003880962ba31ff3b01fcf5942960e0bc3ca331f816346a440","signer":"ethm1mfdjngh5jvjs9lqtt9a7y2hlgw8v3syh3hsqzk"}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}
confirm transaction before signing and broadcasting [y/N]: y
code: 0
codespace: ""
data: ""
gas_used: "0"
gas_wanted: "0"
height: "0"
info: ""
logs: []
raw_log: '[]'
timestamp: ""
tx: null
txhash: 06440D0B35A862E3A6783E147F0E1CDD3374870DAE07E471D465E2830DAF7044
```
Note : After the bond create and withdraw bond and cancel bond , account amount needs change as per module
```
$ ./build/ethermintd q bank balances $(./build/ethermintd keys show root -a) -o json | jq .
{
"balances": [
{
"denom": "aphoton",
"amount": "1000000000000000000"
}
],
"pagination": {
"next_key": null,
"total": "0"
}
}
```
+17
View File
@@ -0,0 +1,17 @@
package bond
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tharsis/ethermint/x/bond/keeper"
)
// BeginBlocker will persist the current header and validator set as a historical entry
// and prune the oldest entry based on the HistoricalEntries parameter
func BeginBlocker(ctx sdk.Context, k keeper.Keeper) {
}
// EndBlocker Called every block, update validator set
func EndBlocker(ctx sdk.Context, k keeper.Keeper) []abci.ValidatorUpdate {
return []abci.ValidatorUpdate{}
}
+203
View File
@@ -0,0 +1,203 @@
package cli
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/version"
"github.com/spf13/cobra"
"github.com/tharsis/ethermint/x/bond/types"
)
// GetQueryCmd returns the cli query commands for this module
func GetQueryCmd() *cobra.Command {
bondQueryCmd := &cobra.Command{
Use: types.ModuleName,
Short: "Querying commands for the bond module",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
bondQueryCmd.AddCommand(
GetQueryParamsCmd(),
GetQueryBondLists(),
GetBondByIdCmd(),
GetBondListByOwnerCmd(),
GetBondModuleBalanceCmd(),
)
return bondQueryCmd
}
// GetQueryParamsCmd implements the params query command.
func GetQueryParamsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "params",
Args: cobra.NoArgs,
Short: "Query the current bond parameters information.",
Long: strings.TrimSpace(
fmt.Sprintf(`Query values set as bond parameters.
Example:
$ %s query %s params
`,
version.AppName, types.ModuleName,
),
),
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.Params(cmd.Context(), &types.QueryParamsRequest{})
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetQueryBondLists implements the bond lists query command.
func GetQueryBondLists() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List bonds.",
Long: strings.TrimSpace(
fmt.Sprintf(`Get bond list .
Example:
$ %s query %s list
`,
version.AppName, types.ModuleName,
),
),
Args: cobra.ExactArgs(0),
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.Bonds(cmd.Context(), &types.QueryGetBondsRequest{})
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetBondByIdCmd implements the bond info by id query command.
func GetBondByIdCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "get [bond Id]",
Short: "Get bond.",
Long: strings.TrimSpace(
fmt.Sprintf(`Get bond info by bond id .
Example:
$ %s query bond get {BOND ID}
`,
version.AppName,
),
),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
id := args[0]
res, err := queryClient.GetBondById(cmd.Context(), &types.QueryGetBondByIdRequest{Id: id})
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetBondListByOwnerCmd queries the bond list by owner.
func GetBondListByOwnerCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "by-owner [address]",
Short: "Query bonds by owner.",
Long: strings.TrimSpace(
fmt.Sprintf(`Get bond list by owner.
Example:
$ %s query %s query-by-owner [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
}
queryClient := types.NewQueryClient(clientCtx)
owner := args[0]
res, err := queryClient.GetBondsByOwner(cmd.Context(), &types.QueryGetBondsByOwnerRequest{Owner: owner})
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GetBondModuleBalanceCmd queries the bond module account balance.
func GetBondModuleBalanceCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "balance",
Short: "Get bond module account balance.",
Long: strings.TrimSpace(
fmt.Sprintf(`Get bond module balance.
Example:
$ %s query %s balance
`,
version.AppName, types.ModuleName,
),
),
Args: cobra.ExactArgs(0),
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.GetBondsModuleBalance(cmd.Context(), &types.QueryGetBondModuleBalanceRequest{})
if err != nil {
return err
}
return clientCtx.PrintProto(res)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
+125
View File
@@ -0,0 +1,125 @@
package cli
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
"github.com/tharsis/ethermint/server/flags"
"github.com/tharsis/ethermint/x/bond/types"
)
// NewTxCmd returns a root CLI command handler for all x/bond transaction commands.
func NewTxCmd() *cobra.Command {
bondTxCmd := &cobra.Command{
Use: types.ModuleName,
Short: "bond transaction subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
bondTxCmd.AddCommand(
NewCreateBondCmd(),
RefillBondCmd(),
WithdrawBondCmd(),
CancelBondCmd(),
)
return bondTxCmd
}
// NewCreateBondCmd is the CLI command for creating a bond.
func NewCreateBondCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create [amount]",
Short: "Create bond.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
coin, err := sdk.ParseCoinNormalized(args[0])
if err != nil {
return err
}
msg := types.NewMsgCreateBond(sdk.NewCoins(coin), clientCtx.GetFromAddress())
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlags(cmd)
return cmd
}
// RefillBondCmd is the CLI command for creating a bond.
func RefillBondCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "refill [bond Id] [amount]",
Short: "Refill bond.",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
bondId := args[0]
coin, err := sdk.ParseCoinNormalized(args[1])
if err != nil {
return err
}
msg := types.NewMsgRefillBond(bondId, coin, clientCtx.GetFromAddress())
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlags(cmd)
return cmd
}
// WithdrawBondCmd is the CLI command for withdrawing funds from a bond.
func WithdrawBondCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "withdraw [bond Id] [amount]",
Short: "Withdraw amount from bond.",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
bondId := args[0]
coin, err := sdk.ParseCoinNormalized(args[1])
if err != nil {
return err
}
msg := types.NewMsgWithdrawBond(bondId, coin, clientCtx.GetFromAddress())
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlags(cmd)
return cmd
}
// CancelBondCmd is the CLI command for cancelling a bond.
func CancelBondCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "cancel [bond Id]",
Short: "cancel bond.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
bondId := args[0]
msg := types.NewMsgCancelBond(bondId, clientCtx.GetFromAddress())
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlags(cmd)
return cmd
}
+14
View File
@@ -0,0 +1,14 @@
package testutil
import (
"testing"
"github.com/stretchr/testify/suite"
"github.com/tharsis/ethermint/testutil/network"
)
func TestIntegrationTestSuite(t *testing.T) {
cfg := network.DefaultConfig()
cfg.NumValidators = 1
suite.Run(t, NewIntegrationTestSuite(cfg))
}
+213
View File
@@ -0,0 +1,213 @@
package testutil
import (
"fmt"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/types/rest"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tharsis/ethermint/x/bond/client/cli"
bondtypes "github.com/tharsis/ethermint/x/bond/types"
)
func (s *IntegrationTestSuite) TestGRPCGetBonds() {
val := s.network.Validators[0]
sr := s.Require()
reqUrl := fmt.Sprintf("%s/vulcanize/bond/v1beta1/bonds", val.APIAddress)
testCases := []struct {
name string
url string
expErr bool
errorMsg string
preRun func()
}{
{
"invalid request with headers",
reqUrl + "asdasdas",
true,
"",
func() {
},
},
{
"valid request",
reqUrl,
false,
"",
func() {
s.createBond()
},
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
resp, _ := rest.GetRequest(tc.url)
if tc.expErr {
sr.Contains(string(resp), tc.errorMsg)
} else {
var response bondtypes.QueryGetBondsResponse
err := val.ClientCtx.Codec.UnmarshalJSON(resp, &response)
sr.NoError(err)
sr.NotZero(len(response.GetBonds()))
}
})
}
}
func (s *IntegrationTestSuite) TestGRPCGetParams() {
val := s.network.Validators[0]
sr := s.Require()
reqUrl := fmt.Sprintf("%s/vulcanize/bond/v1beta1/params", val.APIAddress)
resp, err := rest.GetRequest(reqUrl)
s.Require().NoError(err)
var params bondtypes.QueryParamsResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &params)
sr.NoError(err)
sr.Equal(params.GetParams().MaxBondAmount, bondtypes.DefaultParams().MaxBondAmount)
}
func (s *IntegrationTestSuite) TestGRPCGetBondsByOwner() {
val := s.network.Validators[0]
sr := s.Require()
reqUrl := val.APIAddress + "/vulcanize/bond/v1beta1/by-owner/%s"
testCases := []struct {
name string
url string
expErr bool
preRun func()
}{
{
"empty list",
fmt.Sprintf(reqUrl, "asdasd"),
true,
func() {
},
},
{
"valid request",
fmt.Sprintf(reqUrl, s.accountAddress),
false,
func() {
s.createBond()
},
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
if !tc.expErr {
tc.preRun()
}
resp, err := rest.GetRequest(tc.url)
s.Require().NoError(err)
var bonds bondtypes.QueryGetBondsByOwnerResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &bonds)
sr.NoError(err)
if tc.expErr {
sr.Empty(bonds.GetBonds())
} else {
bondsList := bonds.GetBonds()
sr.NotZero(len(bondsList))
sr.Equal(s.accountAddress, bondsList[0].GetOwner())
}
})
}
}
func (s *IntegrationTestSuite) TestGRPCGetBondById() {
val := s.network.Validators[0]
sr := s.Require()
reqUrl := val.APIAddress + "/vulcanize/bond/v1beta1/bonds/%s"
testCases := []struct {
name string
url string
expErr bool
preRun func() string
}{
{
"invalid request",
fmt.Sprintf(reqUrl, "asdadad"),
true,
func() string {
return ""
},
},
{
"valid request",
reqUrl,
false,
func() string {
// creating the bond
s.createBond()
// getting the bonds list and returning the bond-id
clientCtx := val.ClientCtx
cmd := cli.GetQueryBondLists()
args := []string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
}
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args)
sr.NoError(err)
var queryResponse bondtypes.QueryGetBondsResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
// extract bond id from bonds list
bond := queryResponse.GetBonds()[0]
return bond.GetId()
},
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
var bondId string
if !tc.expErr {
bondId = tc.preRun()
tc.url = fmt.Sprintf(reqUrl, bondId)
}
resp, err := rest.GetRequest(tc.url)
s.Require().NoError(err)
var bonds bondtypes.QueryGetBondByIdResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &bonds)
if tc.expErr {
sr.Empty(bonds.GetBond().GetId())
} else {
sr.NoError(err)
sr.NotZero(bonds.GetBond().GetId())
sr.Equal(bonds.GetBond().GetId(), bondId)
}
})
}
}
func (s *IntegrationTestSuite) TestGRPCGetBondModuleBalance() {
val := s.network.Validators[0]
sr := s.Require()
reqUrl := fmt.Sprintf("%s/vulcanize/bond/v1beta1/balance", val.APIAddress)
// creating the bond
s.createBond()
s.Run("valid request", func() {
resp, err := rest.GetRequest(reqUrl)
sr.NoError(err)
var response bondtypes.QueryGetBondModuleBalanceResponse
err = val.ClientCtx.Codec.UnmarshalJSON(resp, &response)
sr.NoError(err)
sr.False(response.GetBalance().IsZero())
})
}
+330
View File
@@ -0,0 +1,330 @@
package testutil
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
"github.com/stretchr/testify/suite"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tharsis/ethermint/testutil/network"
"github.com/tharsis/ethermint/x/bond/client/cli"
"github.com/tharsis/ethermint/x/bond/types"
)
type IntegrationTestSuite struct {
suite.Suite
cfg network.Config
network *network.Network
accountName string
accountAddress string
}
func NewIntegrationTestSuite(cfg network.Config) *IntegrationTestSuite {
return &IntegrationTestSuite{cfg: cfg}
}
func (s *IntegrationTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite")
var err error
s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg)
s.Require().NoError(err)
_, err = s.network.WaitForHeight(1)
s.Require().NoError(err)
s.accountName = "accountName"
// setting up random account
s.createAccountWithBalance(s.accountName)
}
func (s *IntegrationTestSuite) TearDownSuite() {
s.T().Log("tearing down integration test suite")
s.network.Cleanup()
}
func (s *IntegrationTestSuite) TestGetCmdQueryParams() {
val := s.network.Validators[0]
testCases := []struct {
name string
args []string
outputType string
}{
{
"json output",
[]string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)},
"json",
},
}
for _, tc := range testCases {
s.Run(tc.name, func() {
cmd := cli.GetQueryParamsCmd()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
s.Require().NoError(err)
var response types.QueryParamsResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &response)
s.Require().NoError(err)
s.Require().Equal(response.Params.MaxBondAmount, types.DefaultParams().MaxBondAmount)
})
}
}
func (s *IntegrationTestSuite) createAccountWithBalance(accountName string) {
val := s.network.Validators[0]
sr := s.Require()
consPrivKey := ed25519.GenPrivKey()
consPubKeyBz, err := s.cfg.Codec.MarshalInterfaceJSON(consPrivKey.PubKey())
sr.NoError(err)
sr.NotNil(consPubKeyBz)
info, _, err := val.ClientCtx.Keyring.NewMnemonic(accountName, keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1)
sr.NoError(err)
newAddr := sdk.AccAddress(info.GetPubKey().Address())
_, err = banktestutil.MsgSendExec(
val.ClientCtx,
val.Address,
newAddr,
sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(200))),
fmt.Sprintf("--%s", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
)
sr.NoError(err)
s.accountAddress = newAddr.String()
}
func (s *IntegrationTestSuite) createBond() {
val := s.network.Validators[0]
sr := s.Require()
createBondCmd := cli.NewCreateBondCmd()
args := []string{
fmt.Sprintf("10%s", s.cfg.BondDenom),
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
}
out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, createBondCmd, args)
sr.NoError(err)
var d sdk.TxResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &d)
sr.NoError(err)
sr.Zero(d.Code)
err = s.network.WaitForNextBlock()
sr.NoError(err)
}
func (s *IntegrationTestSuite) TestGetQueryBondLists() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
createBond bool
preRun func()
}{
{
"create and get bond lists",
[]string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)},
true,
func() {
s.createBond()
},
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
if tc.createBond {
tc.preRun()
}
cmd := cli.GetQueryBondLists()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
sr.NoError(err)
var queryResponse types.QueryGetBondsResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
sr.NotZero(len(queryResponse.GetBonds()))
})
}
}
func (s *IntegrationTestSuite) TestGetQueryBondById() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
err bool
preRun func() string
}{
{
"invalid bond id",
[]string{
fmt.Sprint("not_found_bond_id"),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
func() string {
return ""
},
},
{
"create and get bond by id",
[]string{fmt.Sprintf("--%s=json", tmcli.OutputFlag)},
false,
func() string {
// creating the bond
s.createBond()
// getting the bonds list and returning the bond-id
clientCtx := val.ClientCtx
cmd := cli.GetQueryBondLists()
args := []string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
}
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args)
sr.NoError(err)
var queryResponse types.QueryGetBondsResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
// extract bond id from bonds list
bond := queryResponse.GetBonds()[0]
return bond.GetId()
},
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
if !tc.err {
bondId := tc.preRun()
tc.args = append([]string{bondId}, tc.args...)
}
cmd := cli.GetBondByIdCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
sr.NoError(err)
var queryResponse types.QueryGetBondByIdResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
if tc.err {
sr.Zero(len(queryResponse.GetBond().GetId()))
} else {
sr.NotZero(len(queryResponse.GetBond().GetId()))
sr.Equal(s.accountAddress, queryResponse.GetBond().GetOwner())
}
})
}
}
func (s *IntegrationTestSuite) TestGetQueryBondListsByOwner() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
err bool
preRun func()
}{
{
"invalid owner address",
[]string{
fmt.Sprint("not_found_bond_id"),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
func() {
},
},
{
"get bond lists by owner address",
[]string{
fmt.Sprint(s.accountAddress),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
func() {
s.createBond()
},
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
if !tc.err {
tc.preRun()
}
cmd := cli.GetBondListByOwnerCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
sr.NoError(err)
var queryResponse types.QueryGetBondsByOwnerResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
if tc.err {
sr.Zero(len(queryResponse.GetBonds()))
} else {
sr.NotZero(len(queryResponse.GetBonds()))
sr.Equal(s.accountAddress, queryResponse.GetBonds()[0].GetOwner())
}
})
}
}
func (s *IntegrationTestSuite) TestGetQueryBondModuleBalance() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
err bool
preRun func()
}{
{
"get bond module balance",
[]string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
func() {
s.createBond()
},
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
if !tc.err {
tc.preRun()
}
cmd := cli.GetBondModuleBalanceCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
sr.NoError(err)
var queryResponse types.QueryGetBondModuleBalanceResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
sr.False(queryResponse.GetBalance().IsZero())
})
}
}
+317
View File
@@ -0,0 +1,317 @@
package testutil
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client/flags"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
sdk "github.com/cosmos/cosmos-sdk/types"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tharsis/ethermint/x/bond/client/cli"
"github.com/tharsis/ethermint/x/bond/types"
)
func (s *IntegrationTestSuite) TestTxCreateBond() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
err bool
}{
{
"without deposit",
[]string{
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
true,
},
{
"create bond",
[]string{
fmt.Sprintf("10%s", s.cfg.BondDenom),
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
false,
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
cmd := cli.NewCreateBondCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.err {
sr.Error(err)
} else {
sr.NoError(err)
var d sdk.TxResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &d)
sr.Nil(err)
sr.NoError(err)
sr.Zero(d.Code)
}
})
}
}
func (s *IntegrationTestSuite) TestTxRefillBond() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
getBondId bool
err bool
}{
{
"without refill amount and bond id",
[]string{
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
false,
true,
},
{
"refill bond",
[]string{
fmt.Sprintf("10%s", s.cfg.BondDenom),
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
true,
false,
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
cmd := cli.RefillBondCmd()
if tc.getBondId {
cmd := cli.GetQueryBondLists()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondsResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
// extract bond id from bonds list
bond := queryResponse.GetBonds()[0]
tc.args = append([]string{bond.GetId()}, tc.args...)
}
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.err {
sr.Error(err)
} else {
sr.NoError(err)
var d sdk.TxResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &d)
sr.NoError(err)
sr.Zero(d.Code)
// checking the balance of bond
cmd := cli.GetBondByIdCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf(tc.args[0]),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondByIdResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
sr.True(queryResponse.GetBond().GetBalance().IsEqual(
sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(20)))))
}
})
}
}
func (s *IntegrationTestSuite) TestTxWithdrawAmountFromBond() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
getBondId bool
err bool
}{
{
"without withdraw amount and bond id",
[]string{
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
false,
true,
},
{
"withdraw amount from bond",
[]string{
fmt.Sprintf("10%s", s.cfg.BondDenom),
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
true,
false,
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
cmd := cli.WithdrawBondCmd()
if tc.getBondId {
cmd := cli.GetQueryBondLists()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondsResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
// extract bond id from bonds list
bond := queryResponse.GetBonds()[0]
tc.args = append([]string{bond.GetId()}, tc.args...)
}
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.err {
sr.Error(err)
} else {
sr.NoError(err)
var d sdk.TxResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &d)
sr.NoError(err)
sr.Zero(d.Code)
// checking the balance of bond
cmd := cli.GetBondByIdCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf(tc.args[0]),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondByIdResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
sr.True(queryResponse.GetBond().GetBalance().IsEqual(
sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)))))
}
})
}
}
func (s *IntegrationTestSuite) TestTxCancelBond() {
val := s.network.Validators[0]
sr := s.Require()
testCases := []struct {
name string
args []string
getBondId bool
err bool
}{
{
"without bond id",
[]string{
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
false,
true,
},
{
"cancel bond",
[]string{
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.accountName),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, fmt.Sprintf("3%s", s.cfg.BondDenom)),
},
true,
false,
},
}
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.name), func() {
clientCtx := val.ClientCtx
cmd := cli.CancelBondCmd()
if tc.getBondId {
cmd := cli.GetQueryBondLists()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondsResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
// extract bond id from bonds list
bond := queryResponse.GetBonds()[0]
tc.args = append([]string{bond.GetId()}, tc.args...)
}
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.err {
sr.Error(err)
} else {
sr.NoError(err)
var d sdk.TxResponse
err = val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &d)
sr.NoError(err)
sr.Zero(d.Code)
// checking the bond exists or not after cancel
cmd := cli.GetBondByIdCmd()
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{
fmt.Sprintf(tc.args[0]),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
})
sr.NoError(err)
var queryResponse types.QueryGetBondByIdResponse
err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), &queryResponse)
sr.NoError(err)
sr.Zero(queryResponse.GetBond().GetId())
}
})
}
}
+40
View File
@@ -0,0 +1,40 @@
package bond
import (
sdk "github.com/cosmos/cosmos-sdk/types"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tharsis/ethermint/x/bond/keeper"
"github.com/tharsis/ethermint/x/bond/types"
)
// InitGenesis initializes genesis state based on exported genesis
func InitGenesis(
ctx sdk.Context,
k keeper.Keeper, data types.GenesisState) []abci.ValidatorUpdate {
k.SetParams(ctx, data.Params)
for _, bond := range data.Bonds {
k.SaveBond(ctx, bond)
}
return []abci.ValidatorUpdate{}
}
// ExportGenesis - output genesis parameters
func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) types.GenesisState {
params := keeper.GetParams(ctx)
bonds := keeper.ListBonds(ctx)
return types.GenesisState{Params: params, Bonds: bonds}
}
// ValidateGenesis - validating the genesis data
func ValidateGenesis(data types.GenesisState) error {
err := data.Params.Validate()
if err != nil {
return err
}
return nil
}
+53
View File
@@ -0,0 +1,53 @@
package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/tharsis/ethermint/x/bond/types"
)
type Querier struct {
Keeper
}
var _ types.QueryServer = Querier{}
func (q Querier) Bonds(c context.Context, _ *types.QueryGetBondsRequest) (*types.QueryGetBondsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
resp := q.Keeper.ListBonds(ctx)
return &types.QueryGetBondsResponse{Bonds: resp}, nil
}
func (q Querier) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
params := q.Keeper.GetParams(ctx)
return &types.QueryParamsResponse{Params: &params}, nil
}
func (q Querier) GetBondById(c context.Context, req *types.QueryGetBondByIdRequest) (*types.QueryGetBondByIdResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
bondId := req.GetId()
if len(bondId) == 0 {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "bond id required")
}
bond := q.Keeper.GetBond(ctx, req.GetId())
return &types.QueryGetBondByIdResponse{Bond: &bond}, nil
}
func (q Querier) GetBondsByOwner(c context.Context, req *types.QueryGetBondsByOwnerRequest) (*types.QueryGetBondsByOwnerResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
owner := req.GetOwner()
if len(owner) == 0 {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "owner id required")
}
bonds := q.Keeper.QueryBondsByOwner(ctx, owner)
return &types.QueryGetBondsByOwnerResponse{Bonds: bonds}, nil
}
func (q Querier) GetBondsModuleBalance(c context.Context, _ *types.QueryGetBondModuleBalanceRequest) (*types.QueryGetBondModuleBalanceResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
balance := q.Keeper.GetBondModuleBalances(ctx)
return &types.QueryGetBondModuleBalanceResponse{Balance: balance}, nil
}
+221
View File
@@ -0,0 +1,221 @@
package keeper_test
import (
"context"
"fmt"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tharsis/ethermint/app"
"github.com/tharsis/ethermint/x/bond/types"
)
func (suite *KeeperTestSuite) TestGrpcQueryBondsList() {
grpcClient, ctx, k := suite.queryClient, suite.ctx, suite.app.BondKeeper
testCases := []struct {
msg string
req *types.QueryGetBondsRequest
resp *types.QueryGetBondsResponse
noOfBonds int
createBonds bool
}{
{
"empty request",
&types.QueryGetBondsRequest{},
&types.QueryGetBondsResponse{},
0,
false,
},
{
"Get Bonds",
&types.QueryGetBondsRequest{},
&types.QueryGetBondsResponse{},
1,
true,
},
}
for _, test := range testCases {
suite.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
account := app.CreateRandomAccounts(1)[0]
err := simapp.FundAccount(suite.app.BankKeeper, ctx, account, sdk.NewCoins(sdk.Coin{
Denom: sdk.DefaultBondDenom,
Amount: sdk.NewInt(1000),
}))
_, err = k.CreateBond(ctx, account, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))))
suite.Require().NoError(err)
}
resp, _ := grpcClient.Bonds(context.Background(), test.req)
suite.Require().Equal(test.noOfBonds, len(resp.GetBonds()))
})
}
}
func (suite *KeeperTestSuite) TestGrpcQueryParams() {
grpcClient := suite.queryClient
testCases := []struct {
msg string
req *types.QueryParamsRequest
}{
{
"Get Params",
&types.QueryParamsRequest{},
},
}
for _, test := range testCases {
suite.Run(fmt.Sprintf("Case %s ", test.msg), func() {
resp, _ := grpcClient.Params(context.Background(), test.req)
suite.Require().Equal(resp.GetParams().MaxBondAmount, types.DefaultParams().MaxBondAmount)
})
}
}
func (suite *KeeperTestSuite) TestGrpcQueryBondBondId() {
grpcClient, ctx, k, suiteRequire := suite.queryClient, suite.ctx, suite.app.BondKeeper, suite.Require()
testCases := []struct {
msg string
req *types.QueryGetBondByIdRequest
createBonds bool
errResponse bool
bondId string
}{
{
"empty request",
&types.QueryGetBondByIdRequest{},
false,
true,
"",
},
{
"Get Bond By ID",
&types.QueryGetBondByIdRequest{},
true,
false,
"",
},
}
for _, test := range testCases {
suite.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
account := app.CreateRandomAccounts(1)[0]
err := simapp.FundAccount(suite.app.BankKeeper, ctx, account, sdk.NewCoins(sdk.Coin{
Denom: sdk.DefaultBondDenom,
Amount: sdk.NewInt(1000),
}))
bond, err := k.CreateBond(ctx, account, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))))
suiteRequire.NoError(err)
test.req.Id = bond.Id
}
resp, err := grpcClient.GetBondById(context.Background(), test.req)
if !test.errResponse {
suiteRequire.Nil(err)
suiteRequire.NotNil(resp.GetBond())
suiteRequire.Equal(test.req.Id, resp.GetBond().GetId())
} else {
suiteRequire.NotNil(err)
suiteRequire.Error(err)
}
})
}
}
func (suite *KeeperTestSuite) TestGrpcGetBondsByOwner() {
grpcClient, ctx, k, suiteRequire := suite.queryClient, suite.ctx, suite.app.BondKeeper, suite.Require()
testCases := []struct {
msg string
req *types.QueryGetBondsByOwnerRequest
noOfBonds int
createBonds bool
errResponse bool
bondId string
}{
{
"empty request",
&types.QueryGetBondsByOwnerRequest{},
0,
false,
true,
"",
},
{
"Get Bond By Owner",
&types.QueryGetBondsByOwnerRequest{},
1,
true,
false,
"",
},
}
for _, test := range testCases {
suite.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
account := app.CreateRandomAccounts(1)[0]
_ = simapp.FundAccount(suite.app.BankKeeper, ctx, account, sdk.NewCoins(sdk.Coin{
Denom: sdk.DefaultBondDenom,
Amount: sdk.NewInt(1000),
}))
_, err := k.CreateBond(ctx, account, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))))
suiteRequire.NoError(err)
test.req.Owner = account.String()
}
resp, err := grpcClient.GetBondsByOwner(context.Background(), test.req)
if !test.errResponse {
suiteRequire.Nil(err)
suiteRequire.NotNil(resp.GetBonds())
suiteRequire.Equal(test.noOfBonds, len(resp.GetBonds()))
} else {
suiteRequire.NotNil(err)
suiteRequire.Error(err)
}
})
}
}
func (suite *KeeperTestSuite) TestGrpcGetModuleBalance() {
grpcClient, ctx, k, suiteRequire := suite.queryClient, suite.ctx, suite.app.BondKeeper, suite.Require()
testCases := []struct {
msg string
req *types.QueryGetBondModuleBalanceRequest
noOfBonds int
createBonds bool
errResponse bool
}{
{
"empty request",
&types.QueryGetBondModuleBalanceRequest{},
0,
true,
false,
},
}
for _, test := range testCases {
suite.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
account := app.CreateRandomAccounts(1)[0]
_ = simapp.FundAccount(suite.app.BankKeeper, ctx, account, sdk.NewCoins(sdk.Coin{
Denom: sdk.DefaultBondDenom,
Amount: sdk.NewInt(1000),
}))
_, err := k.CreateBond(ctx, account, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))))
suiteRequire.NoError(err)
}
resp, err := grpcClient.GetBondsModuleBalance(context.Background(), test.req)
if !test.errResponse {
suiteRequire.Nil(err)
suiteRequire.NotNil(resp.GetBalance())
suiteRequire.Equal(resp.GetBalance(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))))
} else {
suiteRequire.NotNil(err)
suiteRequire.Error(err)
}
})
}
}
+37
View File
@@ -0,0 +1,37 @@
package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tharsis/ethermint/x/bond/types"
)
// RegisterInvariants registers all bond invariants
func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) {
ir.RegisterRoute(types.ModuleName, "module-account", ModuleAccountInvariant(k))
}
// ModuleAccountInvariant checks that the 'bond' module account balance is non-negative.
func ModuleAccountInvariant(k Keeper) sdk.Invariant {
return func(ctx sdk.Context) (string, bool) {
moduleAddress := k.accountKeeper.GetModuleAddress(types.ModuleName)
balances := k.bankKeeper.GetAllBalances(ctx, moduleAddress)
for _, balance := range balances {
if balance.IsNegative() {
return sdk.FormatInvariant(
types.ModuleName,
"module-account",
fmt.Sprintf("Module account '%s' has negative balance.", types.ModuleName)),
true
}
}
return "", false
}
}
// AllInvariants runs all invariants of the bonds module.
func AllInvariants(k Keeper) sdk.Invariant {
return func(ctx sdk.Context) (string, bool) {
return ModuleAccountInvariant(k)(ctx)
}
}
+355
View File
@@ -0,0 +1,355 @@
package keeper
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
auth "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bank "github.com/cosmos/cosmos-sdk/x/bank/keeper"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/tharsis/ethermint/x/bond/types"
)
// prefixIDToBondIndex is the prefix for ID -> Bond index in the KVStore.
// Note: This is the primary index in the system.
// Note: Golang doesn't support const arrays.
var prefixIDToBondIndex = []byte{0x00}
// prefixOwnerToBondsIndex is the prefix for the Owner -> [Bond] index in the KVStore.
var prefixOwnerToBondsIndex = []byte{0x01}
// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine
type Keeper struct {
accountKeeper auth.AccountKeeper
bankKeeper bank.Keeper
// Track bond usage in other cosmos-sdk modules (more like a usage tracker).
usageKeepers []types.BondUsageKeeper
storeKey sdk.StoreKey
cdc codec.BinaryCodec
paramSubspace paramtypes.Subspace
}
// NewKeeper creates new instances of the bond Keeper
func NewKeeper(cdc codec.BinaryCodec, accountKeeper auth.AccountKeeper, bankKeeper bank.Keeper, usageKeepers []types.BondUsageKeeper, storeKey sdk.StoreKey, ps paramtypes.Subspace) Keeper {
// set KeyTable if it has not already been set
if !ps.HasKeyTable() {
ps = ps.WithKeyTable(types.ParamKeyTable())
}
return Keeper{
accountKeeper: accountKeeper,
bankKeeper: bankKeeper,
storeKey: storeKey,
cdc: cdc,
usageKeepers: usageKeepers,
paramSubspace: ps,
}
}
// Generates Bond ID -> Bond index key.
func getBondIndexKey(id string) []byte {
return append(prefixIDToBondIndex, []byte(id)...)
}
// Generates Owner -> Bonds index key.
func getOwnerToBondsIndexKey(owner string, bondID string) []byte {
return append(append(prefixOwnerToBondsIndex, []byte(owner)...), []byte(bondID)...)
}
// BondID simplifies generation of bond IDs.
type BondID struct {
Address sdk.Address
AccNum uint64
Sequence uint64
}
// Generate creates the bond ID.
func (bondID BondID) Generate() string {
hasher := sha256.New()
str := fmt.Sprintf("%s:%d:%d", bondID.Address.String(), bondID.AccNum, bondID.Sequence)
hasher.Write([]byte(str))
return hex.EncodeToString(hasher.Sum(nil))
}
// MatchBonds - get all matching bonds.
func (k Keeper) MatchBonds(ctx sdk.Context, matchFn func(*types.Bond) bool) []*types.Bond {
var bonds []*types.Bond
store := ctx.KVStore(k.storeKey)
itr := sdk.KVStorePrefixIterator(store, prefixIDToBondIndex)
defer itr.Close()
for ; itr.Valid(); itr.Next() {
bz := store.Get(itr.Key())
if bz != nil {
var obj types.Bond
k.cdc.MustUnmarshal(bz, &obj)
if matchFn(&obj) {
bonds = append(bonds, &obj)
}
}
}
return bonds
}
// CreateBond creates a new bond.
func (k Keeper) CreateBond(ctx sdk.Context, ownerAddress sdk.AccAddress, coins sdk.Coins) (*types.Bond, error) {
// Check if account has funds.
for _, coin := range coins {
balance := k.bankKeeper.HasBalance(ctx, ownerAddress, coin)
if !balance {
return nil, sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "failed to create bond; Insufficient funds")
}
}
// Generate bond ID.
account := k.accountKeeper.GetAccount(ctx, ownerAddress)
bondID := BondID{
Address: ownerAddress,
AccNum: account.GetAccountNumber(),
Sequence: account.GetSequence(),
}.Generate()
maxBondAmount, err := k.getMaxBondAmount(ctx)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Invalid max bond amount.")
}
bond := types.Bond{Id: bondID, Owner: ownerAddress.String(), Balance: coins}
if bond.Balance.IsAnyGT(maxBondAmount) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Max bond amount exceeded.")
}
// Move funds into the bond account module.
err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, ownerAddress, types.ModuleName, bond.Balance)
if err != nil {
return nil, err
}
// Save bond in store.
k.SaveBond(ctx, &bond)
return &bond, nil
}
// SaveBond - saves a bond to the store.
func (k Keeper) SaveBond(ctx sdk.Context, bond *types.Bond) {
store := ctx.KVStore(k.storeKey)
// Bond ID -> Bond index.
store.Set(getBondIndexKey(bond.Id), k.cdc.MustMarshal(bond))
// Owner -> [Bond] index.
store.Set(getOwnerToBondsIndexKey(bond.Owner, bond.Id), []byte{})
}
// HasBond - checks if a bond by the given ID exists.
func (k Keeper) HasBond(ctx sdk.Context, id string) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(getBondIndexKey(id))
}
// GetBond - gets a record from the store.
func (k Keeper) GetBond(ctx sdk.Context, id string) types.Bond {
store := ctx.KVStore(k.storeKey)
bz := store.Get(getBondIndexKey(id))
var obj types.Bond
k.cdc.MustUnmarshal(bz, &obj)
return obj
}
// DeleteBond - deletes the bond.
func (k Keeper) DeleteBond(ctx sdk.Context, bond types.Bond) {
store := ctx.KVStore(k.storeKey)
store.Delete(getBondIndexKey(bond.Id))
store.Delete(getOwnerToBondsIndexKey(bond.Owner, bond.Id))
}
// ListBonds - get all bonds.
func (k Keeper) ListBonds(ctx sdk.Context) []*types.Bond {
var bonds []*types.Bond
store := ctx.KVStore(k.storeKey)
itr := sdk.KVStorePrefixIterator(store, prefixIDToBondIndex)
defer itr.Close()
for ; itr.Valid(); itr.Next() {
bz := store.Get(itr.Key())
if bz != nil {
var obj types.Bond
k.cdc.MustUnmarshal(bz, &obj)
bonds = append(bonds, &obj)
}
}
return bonds
}
// QueryBondsByOwner - query bonds by owner.
func (k Keeper) QueryBondsByOwner(ctx sdk.Context, ownerAddress string) []types.Bond {
var bonds []types.Bond
ownerPrefix := append(prefixOwnerToBondsIndex, []byte(ownerAddress)...)
store := ctx.KVStore(k.storeKey)
itr := sdk.KVStorePrefixIterator(store, ownerPrefix)
defer itr.Close()
for ; itr.Valid(); itr.Next() {
bondID := itr.Key()[len(ownerPrefix):]
bz := store.Get(append(prefixIDToBondIndex, bondID...))
if bz != nil {
var obj types.Bond
k.cdc.MustUnmarshal(bz, &obj)
bonds = append(bonds, obj)
}
}
return bonds
}
// RefillBond refills an existing bond.
func (k Keeper) RefillBond(ctx sdk.Context, id string, ownerAddress sdk.AccAddress, coins sdk.Coins) (*types.Bond, error) {
if !k.HasBond(ctx, id) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Bond not found.")
}
bond := k.GetBond(ctx, id)
if bond.Owner != ownerAddress.String() {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Bond owner mismatch.")
}
// Check if account has funds.
for _, coin := range coins {
if !k.bankKeeper.HasBalance(ctx, ownerAddress, coin) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "Insufficient funds.")
}
}
maxBondAmount, err := k.getMaxBondAmount(ctx)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Invalid max bond amount.")
}
updatedBalance := bond.Balance.Add(coins...)
if updatedBalance.IsAnyGT(maxBondAmount) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Max bond amount exceeded.")
}
// Move funds into the bond account module.
err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, ownerAddress, types.ModuleName, coins)
if err != nil {
return nil, err
}
// Update bond balance and save.
bond.Balance = updatedBalance
k.SaveBond(ctx, &bond)
return &bond, nil
}
// WithdrawBond withdraws funds from a bond.
func (k Keeper) WithdrawBond(ctx sdk.Context, id string, ownerAddress sdk.AccAddress, coins sdk.Coins) (*types.Bond, error) {
if !k.HasBond(ctx, id) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Bond not found.")
}
bond := k.GetBond(ctx, id)
if bond.Owner != ownerAddress.String() {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Bond owner mismatch.")
}
updatedBalance, isNeg := bond.Balance.SafeSub(coins)
if isNeg {
return nil, sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "Insufficient bond balance.")
}
// Move funds from the bond into the account.
err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, ownerAddress, coins)
if err != nil {
return nil, err
}
// Update bond balance and save.
bond.Balance = updatedBalance
k.SaveBond(ctx, &bond)
return &bond, nil
}
// CancelBond cancels a bond, returning funds to the owner.
func (k Keeper) CancelBond(ctx sdk.Context, id string, ownerAddress sdk.AccAddress) (*types.Bond, error) {
if !k.HasBond(ctx, id) {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Bond not found.")
}
bond := k.GetBond(ctx, id)
if bond.Owner != ownerAddress.String() {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Bond owner mismatch.")
}
// Check if bond is used in other modules.
for _, usageKeeper := range k.usageKeepers {
if usageKeeper.UsesBond(ctx, id) {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, fmt.Sprintf("Bond in use by the '%s' module.", usageKeeper.ModuleName()))
}
}
// Move funds from the bond into the account.
err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, ownerAddress, bond.Balance)
if err != nil {
return nil, err
}
k.DeleteBond(ctx, bond)
return &bond, nil
}
func (k Keeper) getMaxBondAmount(ctx sdk.Context) (sdk.Coins, error) {
params := k.GetParams(ctx)
maxBondAmount := params.MaxBondAmount
return sdk.NewCoins(maxBondAmount), nil
}
// GetBondModuleBalances gets the bond module account(s) balances.
func (k Keeper) GetBondModuleBalances(ctx sdk.Context) sdk.Coins {
moduleAddress := k.accountKeeper.GetModuleAddress(types.ModuleName)
balances := k.bankKeeper.GetAllBalances(ctx, moduleAddress)
return balances
}
// TransferCoinsToModuleAccount moves funds from the bonds module account to another module account.
func (k Keeper) TransferCoinsToModuleAccount(ctx sdk.Context, id, moduleAccount string, coins sdk.Coins) error {
if !k.HasBond(ctx, id) {
return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "Bond not found.")
}
bondObj := k.GetBond(ctx, id)
// Deduct rent from bond.
updatedBalance, isNeg := bondObj.Balance.SafeSub(coins)
if isNeg {
// Check if bond has sufficient funds.
return sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "Insufficient funds.")
}
// Move funds from bond module to record rent module.
err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, moduleAccount, coins)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Error transferring funds.")
}
// Update bond balance.
bondObj.Balance = updatedBalance
k.SaveBond(ctx, &bondObj)
return nil
}
+52
View File
@@ -0,0 +1,52 @@
package keeper_test
import (
"testing"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tharsis/ethermint/app"
bondkeeper "github.com/tharsis/ethermint/x/bond/keeper"
"github.com/tharsis/ethermint/x/bond/types"
)
type KeeperTestSuite struct {
suite.Suite
app *app.EthermintApp
ctx sdk.Context
queryClient types.QueryClient
}
func (suite *KeeperTestSuite) SetupTest() {
testApp := app.Setup(false, func(ea *app.EthermintApp, genesis simapp.GenesisState) simapp.GenesisState {
return genesis
})
ctx := testApp.BaseApp.NewContext(false, tmproto.Header{})
querier := bondkeeper.Querier{Keeper: testApp.BondKeeper}
queryHelper := baseapp.NewQueryServerTestHelper(ctx, testApp.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, querier)
queryClient := types.NewQueryClient(queryHelper)
suite.app, suite.ctx, suite.queryClient = testApp, ctx, queryClient
}
func TestParams(t *testing.T) {
testApp := app.Setup(false, func(ea *app.EthermintApp, genesis simapp.GenesisState) simapp.GenesisState {
return genesis
})
ctx := testApp.BaseApp.NewContext(false, tmproto.Header{})
expParams := types.DefaultParams()
params := testApp.BondKeeper.GetParams(ctx)
require.Equal(t, expParams.MaxBondAmount, params.MaxBondAmount)
}
func TestKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}
+130
View File
@@ -0,0 +1,130 @@
package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tharsis/ethermint/x/bond/types"
)
type msgServer struct {
Keeper
}
// NewMsgServerImpl returns an implementation of the bond MsgServer interface for the provided Keeper.
func NewMsgServerImpl(keeper Keeper) types.MsgServer {
return &msgServer{Keeper: keeper}
}
var _ types.MsgServer = msgServer{}
func (k msgServer) CreateBond(c context.Context, msg *types.MsgCreateBond) (*types.MsgCreateBondResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
signerAddress, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
return nil, err
}
_, err = k.Keeper.CreateBond(ctx, signerAddress, msg.Coins)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateBond,
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Coins.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
),
})
return &types.MsgCreateBondResponse{}, nil
}
func (k msgServer) RefillBond(c context.Context, msg *types.MsgRefillBond) (*types.MsgRefillBondResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
signerAddress, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
return nil, err
}
_, err = k.Keeper.RefillBond(ctx, msg.Id, signerAddress, msg.Coins)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeRefillBond,
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
sdk.NewAttribute(types.AttributeKeyBondId, msg.Id),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Coins.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
),
})
return &types.MsgRefillBondResponse{}, nil
}
func (k msgServer) WithdrawBond(c context.Context, msg *types.MsgWithdrawBond) (*types.MsgWithdrawBondResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
signerAddress, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
return nil, err
}
_, err = k.Keeper.WithdrawBond(ctx, msg.Id, signerAddress, msg.Coins)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeWithdrawBond,
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
sdk.NewAttribute(types.AttributeKeyBondId, msg.Id),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Coins.String()),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
),
})
return &types.MsgWithdrawBondResponse{}, nil
}
func (k msgServer) CancelBond(c context.Context, msg *types.MsgCancelBond) (*types.MsgCancelBondResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
signerAddress, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
return nil, err
}
_, err = k.Keeper.CancelBond(ctx, msg.Id, signerAddress)
if err != nil {
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCancelBond,
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
sdk.NewAttribute(types.AttributeKeyBondId, msg.Id),
),
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(types.AttributeKeySigner, msg.Signer),
),
})
return &types.MsgCancelBondResponse{}, nil
}
+23
View File
@@ -0,0 +1,23 @@
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tharsis/ethermint/x/bond/types"
)
// GetMaxBondAmount max bond amount
func (k Keeper) GetMaxBondAmount(ctx sdk.Context) (res sdk.Coin) {
k.paramSubspace.Get(ctx, types.ParamStoreKeyMaxBondAmount, &res)
return
}
// GetParams - Get all parameter as types.Params.
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
getMaxBondAmount := k.GetMaxBondAmount(ctx)
return types.Params{MaxBondAmount: getMaxBondAmount}
}
// SetParams - set the params.
func (k Keeper) SetParams(ctx sdk.Context, params types.Params) {
k.paramSubspace.SetParamSet(ctx, &params)
}
+135
View File
@@ -0,0 +1,135 @@
package bond
import (
"context"
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"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"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tharsis/ethermint/x/bond/client/cli"
"github.com/tharsis/ethermint/x/bond/keeper"
"github.com/tharsis/ethermint/x/bond/types"
)
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
)
// AppModuleBasic defines the basic application module used by the staking module.
type AppModuleBasic struct {
cdc codec.Codec
}
func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) {
types.RegisterLegacyAminoCodec(amino)
}
func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(registry)
}
func (b AppModuleBasic) DefaultGenesis(jsonCodec codec.JSONCodec) json.RawMessage {
return jsonCodec.MustMarshalJSON(types.DefaultGenesisState())
}
func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, message json.RawMessage) error {
var data types.GenesisState
if err := cdc.UnmarshalJSON(message, &data); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return ValidateGenesis(data)
}
func (b AppModuleBasic) RegisterRESTRoutes(context client.Context, router *mux.Router) {
}
func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, serveMux *runtime.ServeMux) {
err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx))
if err != nil {
panic(err)
}
}
func (b AppModuleBasic) GetTxCmd() *cobra.Command {
return cli.NewTxCmd()
}
func (b AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
// Name returns the staking module's name.
func (AppModuleBasic) Name() string {
return types.ModuleName
}
type AppModule struct {
AppModuleBasic
keeper keeper.Keeper
}
// NewAppModule creates a new AppModule Object
func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{cdc: cdc},
keeper: keeper,
}
}
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(message, &genesisState)
return InitGenesis(ctx, am.keeper, genesisState)
}
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(&gs)
}
func (am AppModule) RegisterInvariants(registry sdk.InvariantRegistry) {
keeper.RegisterInvariants(registry, am.keeper)
}
func (am AppModule) Route() sdk.Route {
return sdk.Route{}
}
func (am AppModule) QuerierRoute() string {
return types.QuerierRoute
}
func (am AppModule) LegacyQuerierHandler(amino *codec.LegacyAmino) sdk.Querier {
return nil
}
func (am AppModule) RegisterServices(cfg module.Configurator) {
querier := keeper.Querier{Keeper: am.keeper}
types.RegisterQueryServer(cfg.QueryServer(), querier)
msgServer := keeper.NewMsgServerImpl(am.keeper)
types.RegisterMsgServer(cfg.MsgServer(), msgServer)
}
func (am AppModule) ConsensusVersion() uint64 {
return 1
}
func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {
BeginBlocker(ctx, am.keeper)
}
func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate {
return EndBlocker(ctx, am.keeper)
}
+27
View File
@@ -0,0 +1,27 @@
package bond_test
import (
"testing"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/stretchr/testify/require"
abcitypes "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
app "github.com/tharsis/ethermint/app"
bondtypes "github.com/tharsis/ethermint/x/bond/types"
)
func TestItCreatesModuleAccountOnInitBlock(t *testing.T) {
app := app.Setup(false, func(ea *app.EthermintApp, genesis simapp.GenesisState) simapp.GenesisState {
return genesis
})
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
app.InitChain(abcitypes.RequestInitChain{
AppStateBytes: []byte("{}"),
ChainId: "test-chain-id",
})
acc := app.AccountKeeper.GetModuleAccount(ctx, bondtypes.ModuleName)
require.NotNil(t, acc)
}
+620
View File
@@ -0,0 +1,620 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: vulcanize/bond/v1beta1/bond.proto
package types
import (
fmt "fmt"
github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"
types "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/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 bond module parameters
type Params struct {
// max_bond_amount is maximum amount to bond
MaxBondAmount types.Coin `protobuf:"bytes,1,opt,name=max_bond_amount,json=maxBondAmount,proto3" json:"max_bond_amount" json:"max_bond_amount" yaml:"max_bond_amount"`
}
func (m *Params) Reset() { *m = Params{} }
func (m *Params) String() string { return proto.CompactTextString(m) }
func (*Params) ProtoMessage() {}
func (*Params) Descriptor() ([]byte, []int) {
return fileDescriptor_ff3ef02fadb61511, []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) GetMaxBondAmount() types.Coin {
if m != nil {
return m.MaxBondAmount
}
return types.Coin{}
}
// Bond represents funds deposited by an account for record rent payments.
type Bond struct {
// id is unique identifier of the bond
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
// owner of the bond
Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"`
// balance of the bond
Balance github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=balance,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"balance" json:"balance" yaml:"balance"`
}
func (m *Bond) Reset() { *m = Bond{} }
func (m *Bond) String() string { return proto.CompactTextString(m) }
func (*Bond) ProtoMessage() {}
func (*Bond) Descriptor() ([]byte, []int) {
return fileDescriptor_ff3ef02fadb61511, []int{1}
}
func (m *Bond) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Bond) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Bond.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 *Bond) XXX_Merge(src proto.Message) {
xxx_messageInfo_Bond.Merge(m, src)
}
func (m *Bond) XXX_Size() int {
return m.Size()
}
func (m *Bond) XXX_DiscardUnknown() {
xxx_messageInfo_Bond.DiscardUnknown(m)
}
var xxx_messageInfo_Bond proto.InternalMessageInfo
func (m *Bond) GetId() string {
if m != nil {
return m.Id
}
return ""
}
func (m *Bond) GetOwner() string {
if m != nil {
return m.Owner
}
return ""
}
func (m *Bond) GetBalance() github_com_cosmos_cosmos_sdk_types.Coins {
if m != nil {
return m.Balance
}
return nil
}
func init() {
proto.RegisterType((*Params)(nil), "vulcanize.bond.v1beta1.Params")
proto.RegisterType((*Bond)(nil), "vulcanize.bond.v1beta1.Bond")
}
func init() { proto.RegisterFile("vulcanize/bond/v1beta1/bond.proto", fileDescriptor_ff3ef02fadb61511) }
var fileDescriptor_ff3ef02fadb61511 = []byte{
// 344 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0xc1, 0x4e, 0x32, 0x31,
0x14, 0x85, 0xa7, 0xf0, 0xff, 0x18, 0xc7, 0xa8, 0xc9, 0x84, 0x18, 0x24, 0xb1, 0x20, 0x2b, 0x5c,
0x30, 0x0d, 0x1a, 0x37, 0xee, 0x84, 0x17, 0x50, 0x96, 0x6e, 0x48, 0x67, 0xa6, 0x81, 0x2a, 0xed,
0x25, 0xd3, 0x82, 0x83, 0x4b, 0x17, 0xae, 0x7d, 0x0e, 0xf7, 0xbe, 0x03, 0x4b, 0x96, 0xae, 0xd0,
0xc0, 0x1b, 0xf8, 0x04, 0x66, 0xda, 0x19, 0x62, 0x34, 0x71, 0xd5, 0x9e, 0xdb, 0x73, 0xbf, 0x7b,
0xd2, 0xeb, 0x1e, 0x4f, 0x27, 0xa3, 0x90, 0x4a, 0xfe, 0xc0, 0x48, 0x00, 0x32, 0x22, 0xd3, 0x76,
0xc0, 0x34, 0x6d, 0x1b, 0xe1, 0x8f, 0x63, 0xd0, 0xe0, 0x1d, 0x6c, 0x2c, 0xbe, 0xa9, 0x66, 0x96,
0x6a, 0x79, 0x00, 0x03, 0x30, 0x16, 0x92, 0xde, 0xac, 0xbb, 0x8a, 0x43, 0x50, 0x02, 0x14, 0x09,
0xa8, 0x62, 0x1b, 0x5a, 0x08, 0x5c, 0xda, 0xf7, 0xc6, 0x23, 0x72, 0x4b, 0x57, 0x34, 0xa6, 0x42,
0x79, 0x89, 0xbb, 0x2f, 0x68, 0xd2, 0x4f, 0xa1, 0x7d, 0x2a, 0x60, 0x22, 0x75, 0x05, 0xd5, 0x51,
0x73, 0xe7, 0xf4, 0xd0, 0xb7, 0x10, 0x3f, 0x85, 0xe4, 0xf3, 0xfc, 0x2e, 0x70, 0xd9, 0x39, 0x9f,
0x2f, 0x6b, 0xce, 0xe7, 0xb2, 0xd6, 0xba, 0x55, 0x20, 0x2f, 0x1a, 0x3f, 0xfa, 0x1b, 0xf5, 0x19,
0x15, 0xa3, 0xdf, 0xe5, 0xde, 0xae, 0xa0, 0x49, 0x07, 0x64, 0x74, 0x69, 0xf5, 0x2b, 0x72, 0xff,
0xa5, 0xd2, 0xdb, 0x73, 0x0b, 0x3c, 0x32, 0x53, 0xb7, 0x7b, 0x05, 0x1e, 0x79, 0x65, 0xf7, 0x3f,
0xdc, 0x4b, 0x16, 0x57, 0x0a, 0xa6, 0x64, 0x85, 0xf7, 0x84, 0xdc, 0xad, 0x80, 0x8e, 0xa8, 0x0c,
0x59, 0xa5, 0x58, 0x2f, 0xfe, 0x9d, 0xf0, 0x3a, 0x4b, 0x78, 0x64, 0x13, 0x66, 0x7d, 0x79, 0xb2,
0x5c, 0xbe, 0xbc, 0xd7, 0x9a, 0x03, 0xae, 0x87, 0x93, 0xc0, 0x0f, 0x41, 0x90, 0xec, 0xd3, 0xec,
0xd1, 0x52, 0xd1, 0x1d, 0xd1, 0xb3, 0x31, 0x53, 0x86, 0xa8, 0x7a, 0xf9, 0xf0, 0x4e, 0x77, 0xbe,
0xc2, 0x68, 0xb1, 0xc2, 0xe8, 0x63, 0x85, 0xd1, 0xf3, 0x1a, 0x3b, 0x8b, 0x35, 0x76, 0xde, 0xd6,
0xd8, 0xb9, 0x39, 0xf9, 0x06, 0xd3, 0x43, 0x1a, 0x2b, 0xae, 0x08, 0xd3, 0x43, 0x16, 0x0b, 0x2e,
0x35, 0x49, 0xec, 0x72, 0x0d, 0x33, 0x28, 0x99, 0x45, 0x9c, 0x7d, 0x05, 0x00, 0x00, 0xff, 0xff,
0x45, 0xf7, 0x5e, 0x13, 0xfb, 0x01, 0x00, 0x00,
}
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
{
size, err := m.MaxBondAmount.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintBond(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *Bond) 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 *Bond) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Bond) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Balance) > 0 {
for iNdEx := len(m.Balance) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Balance[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintBond(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if len(m.Owner) > 0 {
i -= len(m.Owner)
copy(dAtA[i:], m.Owner)
i = encodeVarintBond(dAtA, i, uint64(len(m.Owner)))
i--
dAtA[i] = 0x12
}
if len(m.Id) > 0 {
i -= len(m.Id)
copy(dAtA[i:], m.Id)
i = encodeVarintBond(dAtA, i, uint64(len(m.Id)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintBond(dAtA []byte, offset int, v uint64) int {
offset -= sovBond(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.MaxBondAmount.Size()
n += 1 + l + sovBond(uint64(l))
return n
}
func (m *Bond) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Id)
if l > 0 {
n += 1 + l + sovBond(uint64(l))
}
l = len(m.Owner)
if l > 0 {
n += 1 + l + sovBond(uint64(l))
}
if len(m.Balance) > 0 {
for _, e := range m.Balance {
l = e.Size()
n += 1 + l + sovBond(uint64(l))
}
}
return n
}
func sovBond(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozBond(x uint64) (n int) {
return sovBond(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 ErrIntOverflowBond
}
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 MaxBondAmount", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowBond
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthBond
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthBond
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.MaxBondAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipBond(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthBond
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Bond) 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 ErrIntOverflowBond
}
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: Bond: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Bond: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowBond
}
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 ErrInvalidLengthBond
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthBond
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Id = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowBond
}
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 ErrInvalidLengthBond
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthBond
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Owner = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
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 ErrIntOverflowBond
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthBond
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthBond
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Balance = append(m.Balance, types.Coin{})
if err := m.Balance[len(m.Balance)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipBond(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthBond
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipBond(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, ErrIntOverflowBond
}
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, ErrIntOverflowBond
}
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, ErrIntOverflowBond
}
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, ErrInvalidLengthBond
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupBond
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthBond
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthBond = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowBond = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupBond = fmt.Errorf("proto: unexpected end of group")
)
+39
View File
@@ -0,0 +1,39 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
"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"
)
// RegisterLegacyAminoCodec registers the necessary x/bond interfaces and concrete types
// on the provided LegacyAmino codec. These types are used for Amino JSON serialization.
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgCreateBond{}, "bond/MsgCreateBond", nil)
cdc.RegisterConcrete(&MsgRefillBond{}, "bond/MsgRefillBond", nil)
cdc.RegisterConcrete(&MsgWithdrawBond{}, "bond/MsgWithdrawBond", nil)
cdc.RegisterConcrete(&MsgCancelBond{}, "bond/MsgCancelBond", nil)
}
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgCreateBond{},
&MsgRefillBond{},
&MsgCancelBond{},
&MsgWithdrawBond{},
)
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
var (
amino = codec.NewLegacyAmino()
ModuleCdc = codec.NewAminoCodec(amino)
)
func init() {
RegisterLegacyAminoCodec(amino)
cryptocodec.RegisterCrypto(amino)
amino.Seal()
}
+15
View File
@@ -0,0 +1,15 @@
package types
// bond module event types
const (
EventTypeCreateBond = "crate_bond"
EventTypeRefillBond = "refill_bond"
EventTypeCancelBond = "cancel_bond"
EventTypeWithdrawBond = "withdraw_bond"
AttributeKeySigner = "signer"
AttributeKeyAmount = "amount"
AttributeKeyBondId = "bond_id"
AttributeValueCategory = ModuleName
)
+12
View File
@@ -0,0 +1,12 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// BondUsageKeeper keep track of bond usage in other modules.
// Used to, for example, prevent deletion of a bond that's in use.
type BondUsageKeeper interface {
ModuleName() string
UsesBond(ctx sdk.Context, bondId string) bool
}
+9
View File
@@ -0,0 +1,9 @@
package types
// DefaultGenesisState sets default evm genesis state with empty accounts and default params and
// chain config values.
func DefaultGenesisState() *GenesisState {
return &GenesisState{
Params: DefaultParams(),
}
}
+391
View File
@@ -0,0 +1,391 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: vulcanize/bond/v1beta1/genesis.proto
package types
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/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 bond 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"`
// bonds defines all the bonds
Bonds []*Bond `protobuf:"bytes,2,rep,name=bonds,proto3" json:"bonds,omitempty" json:"bonds" yaml:"bonds"`
}
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_f9582eb9edb1dcdf, []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) GetBonds() []*Bond {
if m != nil {
return m.Bonds
}
return nil
}
func init() {
proto.RegisterType((*GenesisState)(nil), "vulcanize.bond.v1beta1.GenesisState")
}
func init() {
proto.RegisterFile("vulcanize/bond/v1beta1/genesis.proto", fileDescriptor_f9582eb9edb1dcdf)
}
var fileDescriptor_f9582eb9edb1dcdf = []byte{
// 259 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x29, 0x2b, 0xcd, 0x49,
0x4e, 0xcc, 0xcb, 0xac, 0x4a, 0xd5, 0x4f, 0xca, 0xcf, 0x4b, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d,
0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9,
0x17, 0x12, 0x83, 0xab, 0xd2, 0x03, 0xa9, 0xd2, 0x83, 0xaa, 0x92, 0x12, 0x49, 0xcf, 0x4f, 0xcf,
0x07, 0x2b, 0xd1, 0x07, 0xb1, 0x20, 0xaa, 0xa5, 0x14, 0x71, 0x98, 0x09, 0xd6, 0x0a, 0x56, 0xa2,
0x34, 0x9f, 0x91, 0x8b, 0xc7, 0x1d, 0x62, 0x45, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x0d, 0x17,
0x5b, 0x41, 0x62, 0x51, 0x62, 0x6e, 0xb1, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x9c, 0x1e,
0x76, 0x2b, 0xf5, 0x02, 0xc0, 0xaa, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x82, 0xea, 0x11,
0x0a, 0xe4, 0x62, 0x05, 0x29, 0x2a, 0x96, 0x60, 0x52, 0x60, 0xd6, 0xe0, 0x36, 0x92, 0xc1, 0xa5,
0xd9, 0x29, 0x3f, 0x2f, 0xc5, 0x49, 0xf6, 0xd3, 0x3d, 0x79, 0xc9, 0xac, 0xe2, 0xfc, 0x3c, 0x2b,
0x25, 0xb0, 0x26, 0x25, 0x85, 0xca, 0xc4, 0xdc, 0x1c, 0x18, 0x27, 0x08, 0x62, 0x92, 0x93, 0xf3,
0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c,
0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x69, 0xa6, 0x67, 0x96, 0x64, 0x94,
0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x97, 0x64, 0x24, 0x16, 0x15, 0x67, 0x16, 0xeb, 0xa7, 0x96,
0x64, 0xa4, 0x16, 0xe5, 0x66, 0xe6, 0x95, 0xe8, 0x57, 0x40, 0xfc, 0x5c, 0x52, 0x59, 0x90, 0x5a,
0x9c, 0xc4, 0x06, 0xf6, 0xad, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xaa, 0xe9, 0x23, 0x03, 0x66,
0x01, 0x00, 0x00,
}
func (m *GenesisState) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Bonds) > 0 {
for iNdEx := len(m.Bonds) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Bonds[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 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.Bonds) > 0 {
for _, e := range m.Bonds {
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 Bonds", 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.Bonds = append(m.Bonds, &Bond{})
if err := m.Bonds[len(m.Bonds)-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")
)
+15
View File
@@ -0,0 +1,15 @@
package types
const (
// ModuleName is the name of the staking module
ModuleName = "bond"
// StoreKey is the string store representation
StoreKey = ModuleName
// QuerierRoute is the querier route for the staking module
QuerierRoute = ModuleName
// RouterKey is the msg router key for the staking module
RouterKey = ModuleName
)
+143
View File
@@ -0,0 +1,143 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var (
_ sdk.Msg = &MsgCreateBond{}
_ sdk.Msg = &MsgRefillBond{}
_ sdk.Msg = &MsgWithdrawBond{}
_ sdk.Msg = &MsgCancelBond{}
)
// NewMsgCreateBond is the constructor function for MsgCreateBond.
func NewMsgCreateBond(coins sdk.Coins, signer sdk.AccAddress) MsgCreateBond {
return MsgCreateBond{
Coins: coins,
Signer: signer.String(),
}
}
// Route Implements Msg.
func (msg MsgCreateBond) Route() string { return RouterKey }
// Type Implements Msg.
func (msg MsgCreateBond) Type() string { return "create" }
func (msg MsgCreateBond) ValidateBasic() error {
if len(msg.Signer) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Signer)
}
if len(msg.Coins) == 0 || !msg.Coins.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "Invalid amount.")
}
return nil
}
func (msg MsgCreateBond) GetSigners() []sdk.AccAddress {
accAddr, _ := sdk.AccAddressFromBech32(msg.Signer)
return []sdk.AccAddress{accAddr}
}
// GetSignBytes gets the sign bytes for the msg MsgCreateBond
func (msg MsgCreateBond) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(&msg)
return sdk.MustSortJSON(bz)
}
// NewMsgRefillBond is the constructor function for MsgRefillBond.
func NewMsgRefillBond(id string, amount sdk.Coin, signer sdk.AccAddress) MsgRefillBond {
return MsgRefillBond{
Id: id,
Coins: sdk.NewCoins(amount),
Signer: signer.String(),
}
}
func (msg MsgRefillBond) ValidateBasic() error {
if len(msg.Id) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, msg.Id)
}
if len(msg.Signer) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Signer)
}
if len(msg.Coins) == 0 || !msg.Coins.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "Invalid amount.")
}
return nil
}
func (msg MsgRefillBond) GetSigners() []sdk.AccAddress {
accAddr, _ := sdk.AccAddressFromBech32(msg.Signer)
return []sdk.AccAddress{accAddr}
}
// GetSignBytes gets the sign bytes for the msg MsgCreateBond
func (msg MsgRefillBond) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(&msg)
return sdk.MustSortJSON(bz)
}
// NewMsgWithdrawBond is the constructor function for NewMsgWithdrawBond.
func NewMsgWithdrawBond(id string, amount sdk.Coin, signer sdk.AccAddress) MsgWithdrawBond {
return MsgWithdrawBond{
Id: id,
Coins: sdk.NewCoins(amount),
Signer: signer.String(),
}
}
func (msg MsgWithdrawBond) ValidateBasic() error {
if len(msg.Id) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, msg.Id)
}
if len(msg.Signer) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Signer)
}
if len(msg.Coins) == 0 || !msg.Coins.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "Invalid amount.")
}
return nil
}
func (msg MsgWithdrawBond) GetSigners() []sdk.AccAddress {
accAddr, _ := sdk.AccAddressFromBech32(msg.Signer)
return []sdk.AccAddress{accAddr}
}
// GetSignBytes gets the sign bytes for the msg MsgCreateBond
func (msg MsgWithdrawBond) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(&msg)
return sdk.MustSortJSON(bz)
}
// NewMsgCancelBond is the constructor function for CalcelBond.
func NewMsgCancelBond(id string, signer sdk.AccAddress) MsgCancelBond {
return MsgCancelBond{
Id: id,
Signer: signer.String(),
}
}
func (msg MsgCancelBond) ValidateBasic() error {
if len(msg.Id) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, msg.Id)
}
if len(msg.Signer) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Signer)
}
return nil
}
func (msg MsgCancelBond) GetSigners() []sdk.AccAddress {
accAddr, _ := sdk.AccAddressFromBech32(msg.Signer)
return []sdk.AccAddress{accAddr}
}
// GetSignBytes gets the sign bytes for the msg MsgCreateBond
func (msg MsgCancelBond) GetSignBytes() []byte {
bz := ModuleCdc.MustMarshalJSON(&msg)
return sdk.MustSortJSON(bz)
}
+64
View File
@@ -0,0 +1,64 @@
package types
import (
"errors"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
var _ paramtypes.ParamSet = &Params{}
// Default parameter values.
var (
DefaultMaxBondAmountTokens = sdk.NewInt(100000000000)
)
// Parameter keys
var (
ParamStoreKeyMaxBondAmount = []byte("MaxBondAmount")
)
// ParamKeyTable ParamTable for staking module
func ParamKeyTable() paramtypes.KeyTable {
return paramtypes.NewKeyTable().RegisterParamSet(&Params{})
}
func NewParams(maxBondAmount sdk.Coin) Params {
return Params{MaxBondAmount: maxBondAmount}
}
// DefaultParams returns default evm parameters
// ExtraEIPs is empty to prevent overriding the latest hard fork instruction set
func DefaultParams() Params {
return NewParams(sdk.NewCoin(sdk.DefaultBondDenom, DefaultMaxBondAmountTokens))
}
// ParamSetPairs returns the parameter set pairs.
func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs {
return paramtypes.ParamSetPairs{
paramtypes.NewParamSetPair(ParamStoreKeyMaxBondAmount, &p.MaxBondAmount, validateMaxBondAmount),
}
}
func validateMaxBondAmount(i interface{}) error {
v, ok := i.(sdk.Coin)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v.Amount.IsNegative() {
return errors.New("max bond amount must be positive")
}
return nil
}
// Validate checks that the parameters have valid values.
func (p Params) Validate() error {
if err := validateMaxBondAmount(p.MaxBondAmount); err != nil {
return err
}
return nil
}
+2280
View File
File diff suppressed because it is too large Load Diff
+504
View File
@@ -0,0 +1,504 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: vulcanize/bond/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/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
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
}
var (
filter_Query_Bonds_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Query_Bonds_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondsRequest
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_Bonds_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Bonds(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_Bonds_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondsRequest
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_Bonds_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Bonds(ctx, &protoReq)
return msg, metadata, err
}
func request_Query_GetBondById_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondByIdRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["id"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
}
protoReq.Id, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err)
}
msg, err := client.GetBondById(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_GetBondById_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondByIdRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["id"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
}
protoReq.Id, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err)
}
msg, err := server.GetBondById(ctx, &protoReq)
return msg, metadata, err
}
var (
filter_Query_GetBondsByOwner_0 = &utilities.DoubleArray{Encoding: map[string]int{"owner": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}
)
func request_Query_GetBondsByOwner_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondsByOwnerRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["owner"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner")
}
protoReq.Owner, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", 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_GetBondsByOwner_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.GetBondsByOwner(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_GetBondsByOwner_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondsByOwnerRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["owner"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner")
}
protoReq.Owner, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", 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_GetBondsByOwner_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.GetBondsByOwner(ctx, &protoReq)
return msg, metadata, err
}
func request_Query_GetBondsModuleBalance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondModuleBalanceRequest
var metadata runtime.ServerMetadata
msg, err := client.GetBondsModuleBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_GetBondsModuleBalance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryGetBondModuleBalanceRequest
var metadata runtime.ServerMetadata
msg, err := server.GetBondsModuleBalance(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 (such as grpc.SendHeader, etc) 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()
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)
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_Bonds_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.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_Query_Bonds_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_Bonds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondById_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.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_Query_GetBondById_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_GetBondById_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondsByOwner_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.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_Query_GetBondsByOwner_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_GetBondsByOwner_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondsModuleBalance_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.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_Query_GetBondsModuleBalance_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_GetBondsModuleBalance_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_Bonds_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_Bonds_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_Bonds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondById_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_GetBondById_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_GetBondById_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondsByOwner_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_GetBondsByOwner_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_GetBondsByOwner_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_GetBondsModuleBalance_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_GetBondsModuleBalance_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_GetBondsModuleBalance_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{"vulcanize", "bond", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_Bonds_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"vulcanize", "bond", "v1beta1", "bonds"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetBondById_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"vulcanize", "bond", "v1beta1", "bonds", "id"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetBondsByOwner_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"vulcanize", "bond", "v1beta1", "by-owner", "owner"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetBondsModuleBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"vulcanize", "bond", "v1beta1", "balance"}, "", runtime.AssumeColonVerbOpt(true)))
)
var (
forward_Query_Params_0 = runtime.ForwardResponseMessage
forward_Query_Bonds_0 = runtime.ForwardResponseMessage
forward_Query_GetBondById_0 = runtime.ForwardResponseMessage
forward_Query_GetBondsByOwner_0 = runtime.ForwardResponseMessage
forward_Query_GetBondsModuleBalance_0 = runtime.ForwardResponseMessage
)
+1921
View File
File diff suppressed because it is too large Load Diff