├── .gitignore ├── .golangci.yml ├── Dockerfile ├── Makefile ├── README.md ├── app ├── add_prefixes.go ├── app.go ├── app_test.go ├── config.go ├── encoding.go ├── export.go ├── genesis.go ├── params │ ├── amino.go │ ├── config.go │ ├── encoding.go │ └── proto.go ├── types.go └── wasm_wrapper.go ├── bash.exe.stackdump ├── cmd ├── statesetcli │ └── main.go └── statesetd │ ├── cmd │ ├── airdrop.go │ ├── bech32.go │ ├── genaccounts.go │ ├── genesis.go │ ├── init.go │ └── root.go │ └── main.go ├── config.yml ├── contrib └── devtools │ ├── Makefile │ └── proto-tools-installer.sh ├── docker-compose.yml ├── go.mod ├── go.sum ├── internal └── tools │ └── tools.go ├── math ├── math.go └── math_test.go ├── networks └── local │ ├── Makefile │ └── statesetdnode │ ├── Dockerfile │ └── wrapper.sh ├── ops └── statesetd.service ├── proto └── stateset │ ├── agreement │ └── v1beta1 │ │ ├── agreement.proto │ │ ├── events.proto │ │ ├── genesis.proto │ │ ├── packet.proto │ │ ├── query.proto │ │ ├── sentAgreement.proto │ │ ├── timedoutAgreement.proto │ │ └── tx.proto │ ├── did │ └── v1beta1 │ │ ├── did.proto │ │ ├── diddoc.proto │ │ ├── genesis.proto │ │ ├── query.proto │ │ └── tx.proto │ ├── ibc │ ├── applications │ │ ├── account │ │ │ ├── account.proto │ │ │ ├── genesis.proto │ │ │ ├── query.proto │ │ │ └── types.proto │ │ ├── ibcdex │ │ │ └── v1alpha1 │ │ │ │ ├── buyOrderBook.proto │ │ │ │ ├── genesis.proto │ │ │ │ ├── packet.proto │ │ │ │ ├── sellOrderBook.proto │ │ │ │ └── tx.proto │ │ └── transfer │ │ │ └── v1 │ │ │ ├── genesis.proto │ │ │ ├── query.proto │ │ │ ├── transfer.proto │ │ │ └── tx.proto │ └── core │ │ ├── channel │ │ └── v1 │ │ │ ├── channel.proto │ │ │ ├── genesis.proto │ │ │ ├── query.proto │ │ │ └── tx.proto │ │ ├── client │ │ └── v1 │ │ │ ├── client.proto │ │ │ ├── genesis.proto │ │ │ ├── query.proto │ │ │ └── tx.proto │ │ ├── commitment │ │ └── v1 │ │ │ └── commitment.proto │ │ ├── connection │ │ └── v1 │ │ │ ├── connection.proto │ │ │ ├── genesis.proto │ │ │ ├── query.proto │ │ │ └── tx.proto │ │ └── types │ │ └── v1 │ │ └── genesis.proto │ ├── invoice │ └── v1beta1 │ │ ├── events.proto │ │ ├── genesis.proto │ │ ├── invoice.proto │ │ ├── packet.proto │ │ ├── query.proto │ │ ├── sentInvoice.proto │ │ ├── timedoutInvoice.proto │ │ └── tx.proto │ ├── params │ ├── params.proto │ └── query.proto │ ├── purchaseorder │ └── v1beta1 │ │ ├── events.proto │ │ ├── genesis.proto │ │ ├── packet.proto │ │ ├── purchaseorder.proto │ │ ├── query.proto │ │ ├── sentPurchaseOrder.proto │ │ ├── timedoutPurchaseOrder.proto │ │ └── tx.proto │ ├── staking │ ├── genesis.proto │ └── query.proto │ └── wasm │ └── v1beta1 │ ├── genesis.proto │ ├── query.proto │ ├── tx.proto │ └── wasm.proto ├── scripts └── protocgen ├── startnode.sh ├── stateset-blockchain.png ├── stateset.md ├── types ├── address.go ├── conn.go ├── context.go ├── id.go ├── types.go └── util │ ├── address.go │ └── blocks.go └── x ├── README.md ├── agreement ├── client │ ├── cli │ │ ├── query.go │ │ ├── querySentAgreeement.go │ │ ├── queryTimedoutAgreement.go │ │ ├── tx.go │ │ └── tx_ibcAgreement.go │ └── rest │ │ ├── query.go │ │ ├── rest.go │ │ └── tx.go ├── genesis.go ├── handler │ └── handler.go ├── keeper │ ├── grpc_query_agreement.go │ ├── grpc_query_sentAgreement.go │ ├── grpc_query_timedoutAgreement.go │ ├── ibc.go │ ├── ibcAgreement.go │ ├── keeper.go │ ├── keeper_test.go │ ├── msg_server.go │ ├── msg_server_activate_agreement.go │ ├── msg_server_create_agreement.go │ ├── msg_server_ibcAgreement.go │ ├── msg_server_renew_agreement.go │ ├── msg_server_terminate_agreement.go │ ├── msg_server_test.go │ ├── sentAgreeement.go │ ├── sentAgreement_test.go │ ├── timedoutAgreement.go │ └── timedoutAgreement_test.go ├── module.go ├── module_ibc.go ├── querier.go └── types │ ├── codec.go │ ├── errors.go │ ├── events.go │ ├── events_ibc.go │ ├── expected_keeper_ibc.go │ ├── expected_keepers.go │ ├── genesis.go │ ├── hooks.go │ ├── keys.go │ ├── msg.go │ ├── packet_ibcAgreement.go │ └── types.go ├── common ├── coin_test.go ├── const.go ├── errors.go ├── monitor │ ├── config.go │ ├── order.go │ └── stream.go ├── perf │ └── performance.go ├── proto │ ├── keeper.go │ ├── keeper_test.go │ ├── keys.go │ └── test_common.go ├── rest_v2.go ├── sample_sys_test.go ├── syscoin_test.go ├── syscoins_test.go ├── types.go ├── util.go ├── util_test.go └── version │ └── version.go ├── did ├── auth.go ├── exported │ └── did.go ├── genesis.go ├── handler.go ├── keeper │ ├── grpc_query.go │ ├── keeper.go │ └── querier.go ├── module.go └── types │ ├── codec.go │ ├── error.go │ ├── events.go │ ├── genesis.go │ ├── keys.go │ ├── msgs.go │ └── types.go ├── ibc ├── applications │ ├── ibcdex │ │ ├── client │ │ │ ├── cli │ │ │ │ ├── query.go │ │ │ │ ├── queryBuyOrderBook.go │ │ │ │ ├── querySellOrderBook.go │ │ │ │ ├── tx.go │ │ │ │ ├── txCancelBuyOrder.go │ │ │ │ ├── txCancelSellOrder.go │ │ │ │ ├── tx_CreatePair.go │ │ │ │ ├── tx_SellOrder.go │ │ │ │ └── tx_buyOrder.go │ │ │ └── rest │ │ │ │ └── rest.go │ │ ├── genesis.go │ │ ├── handler.go │ │ ├── keeper │ │ │ ├── buyOrder.go │ │ │ ├── buyOrderBook.go │ │ │ ├── createPair.go │ │ │ ├── grpc_query.go │ │ │ ├── grpc_query_buyOrderBook.go │ │ │ ├── grpc_query_sellOrderBook.go │ │ │ ├── ibc.go │ │ │ ├── keeper.go │ │ │ ├── msg_server.go │ │ │ ├── msg_server_buyOrder.go │ │ │ ├── msg_server_cancelBuyOrder.go │ │ │ ├── msg_server_cancelSellOrder.go │ │ │ ├── msg_server_createPair.go │ │ │ ├── msg_server_sellOrder.go │ │ │ ├── query.go │ │ │ ├── sellOrder.go │ │ │ └── sellOrderBook.go │ │ ├── module.go │ │ ├── module_ibc.go │ │ └── types │ │ │ ├── codec.go │ │ │ ├── errors.go │ │ │ ├── events_ibc.go │ │ │ ├── genesis.go │ │ │ ├── keys.go │ │ │ ├── message_cancelBuyOrder.go │ │ │ ├── message_cancelSellOrder.go │ │ │ ├── messages_buyOrder.go │ │ │ ├── messages_createPair.go │ │ │ ├── messages_sellOrder.go │ │ │ ├── packet_buyOrder.go │ │ │ ├── packet_createPair.go │ │ │ ├── packet_sellOrder.go │ │ │ └── types.go │ └── transfer │ │ ├── client │ │ └── cli │ │ │ ├── cli.go │ │ │ ├── query.go │ │ │ └── tx.go │ │ ├── handler.go │ │ ├── handler_test.go │ │ ├── keeper │ │ ├── encoding.go │ │ ├── genesis.go │ │ ├── grpc_query.go │ │ ├── keeper.go │ │ ├── msg_server.go │ │ ├── params.go │ │ └── relay.go │ │ ├── module.go │ │ ├── module_test.go │ │ └── types │ │ ├── codec.go │ │ ├── coin.go │ │ ├── errors.go │ │ ├── events.go │ │ ├── expected_keepers.go │ │ ├── genesis.go │ │ ├── keys.go │ │ ├── msgs.go │ │ ├── packet.go │ │ ├── params.go │ │ └── trace.go └── core │ ├── genesis.go │ ├── handler.go │ ├── keeper │ ├── grpc_query.go │ ├── keeper.go │ └── msg_server.go │ ├── module.go │ └── types │ ├── codec.go │ ├── genesis.go │ └── query.go ├── invoice ├── client │ ├── cli │ │ ├── query.go │ │ └── tx.go │ └── rest │ │ ├── query.go │ │ ├── rest.go │ │ └── tx.go ├── genesis.go ├── handler │ └── handler.go ├── keeper │ ├── grpc_query.go │ ├── grpc_query_invoice.go │ ├── grpc_query_sentInvoice.go │ ├── grpc_timedoutInvoice.go │ ├── ibc.go │ ├── ibcInvoice.go │ ├── keeper.go │ ├── msg_server.go │ ├── msg_server_cancel_invoice.go │ ├── msg_server_create_invoice.go │ ├── msg_server_factor_invoice.go │ ├── sent_invoice.go │ └── timedOutInvoice.go ├── module.go ├── params.go ├── querier.go └── types │ ├── codec.go │ ├── errors.go │ ├── events.go │ ├── events_ibc.go │ ├── expected_keeper_ibc.go │ ├── expected_keepers.go │ ├── hooks.go │ ├── keys.go │ ├── msg.go │ └── types.go ├── purchaseorder ├── client │ ├── cli │ │ ├── query.go │ │ ├── querySentPurchaseOrder.go │ │ ├── queryTimedoutPurhcaseOrder.go │ │ ├── tx.go │ │ └── tx_ibcPurchaseOrder.go │ └── rest │ │ ├── query.go │ │ ├── rest.go │ │ └── tx.go ├── genesis.go ├── handler │ └── handler.go ├── keeper │ ├── grpc_query.go │ ├── grpc_query_purchaseorder.go │ ├── grpc_query_sentPurchaseOrder.go │ ├── grpc_timedoutPurchaseOrder.go │ ├── ibc.go │ ├── ibcPurchaseOrder.go │ ├── keeper.go │ ├── msg_server.go │ ├── msg_server_cancel_purchaseorder.go │ ├── msg_server_complete_purchaseorder.go │ ├── msg_server_create_purchaseorder.go │ ├── msg_server_finance_purchaseorder.go │ ├── msg_server_ibcPurchaseOrder.go │ ├── sentPurchaseOrder.go │ └── timedoutPurchaseOrder.go ├── module.go ├── params.go ├── querier.go └── types │ ├── codec.go │ ├── errors.go │ ├── events.go │ ├── events_ibc.go │ ├── expected_keeper_ibc.go │ ├── expected_keepers.go │ ├── genesis.go │ ├── hooks.go │ ├── key.go │ ├── msg.go │ ├── packet_ibcPurchaseOrder.go │ └── types.go └── wasm ├── abci.go ├── alias.go ├── client ├── query.go └── tx.go ├── config ├── config.go └── toml.go ├── exported └── alias.go ├── genesis.go ├── handler.go ├── internal ├── keeper │ ├── api.go │ ├── connector.go │ ├── contract.go │ ├── ioutil.go │ ├── keeper.go │ ├── params.go │ └── test_utils.go └── types │ ├── codec.go │ ├── connector.go │ ├── contract.go │ ├── errors.go │ ├── events.go │ ├── expected_keeper.go │ ├── genesis.go │ ├── keys.go │ ├── msg.go │ ├── msg_binding.go │ ├── params.go │ ├── querier.go │ └── query_binding.go ├── module.go ├── rest ├── query.go ├── rest.go └── tx.go └── utils └── utils.go /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters: 2 | enable: 3 | - bodyclose 4 | - deadcode 5 | - depguard 6 | - dogsled 7 | - dupl 8 | - errcheck 9 | # - funlen 10 | # - gochecknoglobals 11 | # - gochecknoinits 12 | - goconst 13 | - gocritic 14 | # - gocyclo 15 | # - godox 16 | - gofmt 17 | - goimports 18 | - golint 19 | - gosec 20 | - gosimple 21 | - govet 22 | - ineffassign 23 | - interfacer 24 | - lll 25 | - misspell 26 | # - maligned 27 | - nakedret 28 | - prealloc 29 | - scopelint 30 | - staticcheck 31 | - structcheck 32 | - stylecheck 33 | - typecheck 34 | - unconvert 35 | # - unparam 36 | - unused 37 | - varcheck 38 | # - whitespace 39 | # - wsl 40 | # - gocognit 41 | 42 | linters-settings: 43 | govet: 44 | check-shadowing: true 45 | errcheck: 46 | # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; 47 | # default is false: such cases aren't reported by default. 48 | check-blank: true 49 | golint: 50 | # minimal confidence for issues, default is 0.8 51 | min-confidence: 0 52 | prealloc: 53 | # XXX: we don't recommend using this linter before doing performance profiling. 54 | # For most programs usage of prealloc will be a premature optimization. 55 | 56 | # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. 57 | # True by default. 58 | simple: false 59 | range-loops: true # Report preallocation suggestions on range loops, true by default 60 | for-loops: true # Report preallocation suggestions on for loops, false by default 61 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS build-env 2 | 3 | # Set up dependencies 4 | ENV PACKAGES curl make git libc-dev bash gcc linux-headers eudev-dev python3 5 | 6 | # Set working directory for the build 7 | WORKDIR /go/src/github.com/stateset/stateset-blockchain 8 | 9 | # Add source files 10 | COPY . . 11 | 12 | # Install minimum necessary dependencies, build Cosmos SDK, remove packages 13 | RUN apk add --no-cache $PACKAGES && \ 14 | make install 15 | 16 | # Final image 17 | FROM alpine:edge 18 | 19 | ENV stateset /stateset 20 | 21 | # Install ca-certificates 22 | RUN apk add --update ca-certificates 23 | 24 | RUN addgroup stateset && \ 25 | adduser -S -G stateset stateset -h "$STATESET" 26 | 27 | USER stateset 28 | 29 | WORKDIR $STATESET 30 | 31 | # Copy over binaries from the build-env 32 | COPY --from=build-env /go/bin/statesetd /usr/bin/statesetd 33 | 34 | # Run statesetd by default, omit entrypoint to ease using container with statesetcli 35 | CMD ["statesetd"] -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PACKAGES=$(shell go list ./... | grep -v '/simulation') 2 | 3 | VERSION := $(shell echo $(shell git describe --tags)) 4 | COMMIT := $(shell git log -1 --format='%H') 5 | 6 | ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=Stateset \ 7 | -X github.com/cosmos/cosmos-sdk/version.ServerName=statesetd \ 8 | -X github.com/cosmos/cosmos-sdk/version.ClientName=statesetcli \ 9 | -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ 10 | -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) 11 | 12 | BUILD_FLAGS := -ldflags '$(ldflags)' 13 | 14 | all: install 15 | 16 | install: go.sum 17 | go install -mod=readonly $(BUILD_FLAGS) ./cmd/statesetd 18 | go install -mod=readonly $(BUILD_FLAGS) ./cmd/statesetcli 19 | 20 | go.sum: go.mod 21 | @echo "--> Ensure dependencies have not been modified" 22 | GO111MODULE=on go mod verify -------------------------------------------------------------------------------- /app/add_prefixes.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | ) 8 | 9 | const ( 10 | // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address 11 | Bech32PrefixAccAddr = "stateset" 12 | // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key 13 | Bech32PrefixAccPub = "statesetpub" 14 | // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address 15 | Bech32PrefixValAddr = "statesetvaloper" 16 | // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key 17 | Bech32PrefixValPub = "statesetvaloperpub" 18 | // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address 19 | Bech32PrefixConsAddr = "statesetvalcons" 20 | // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key 21 | Bech32PrefixConsPub = "statesetvalconspub" 22 | ) 23 | 24 | func init() { 25 | config := sdk.GetConfig() 26 | config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) 27 | config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) 28 | config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) 29 | config.SetAddressVerifier(func(bytes []byte) error { 30 | n := len(bytes) 31 | if (n != 0) && (n <= address.MaxAddrLen) { 32 | return nil 33 | } 34 | return fmt.Errorf("unexpected address length %d", n) 35 | }) 36 | config.Seal() 37 | } 38 | -------------------------------------------------------------------------------- /app/app_test.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "testing" 7 | 8 | "github.com/cosmos/cosmos-sdk/simapp" 9 | "github.com/stretchr/testify/require" 10 | abci "github.com/tendermint/tendermint/abci/types" 11 | "github.com/tendermint/tendermint/libs/log" 12 | dbm "github.com/tendermint/tm-db" 13 | ) 14 | 15 | func TestSimAppExportAndBlockedAddrs(t *testing.T) { 16 | encCfg := MakeEncodingConfig() 17 | db := dbm.NewMemDB() 18 | app := NewStatesetApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg, simapp.EmptyAppOptions{}) 19 | 20 | for acc := range maccPerms { 21 | require.Equal(t, true, app.BankKeeper.BlockedAddr(app.AccountKeeper.GetModuleAddress(acc)), 22 | "ensure that all module account addresses are properly blocked in bank keeper") 23 | } 24 | 25 | genesisState := NewDefaultGenesisState(encCfg.Marshaler) 26 | stateBytes, err := json.MarshalIndent(genesisState, "", " ") 27 | require.NoError(t, err) 28 | 29 | // Initialize the chain 30 | app.InitChain( 31 | abci.RequestInitChain{ 32 | Validators: []abci.ValidatorUpdate{}, 33 | AppStateBytes: stateBytes, 34 | }, 35 | ) 36 | app.Commit() 37 | 38 | // Making a new app object with the db, so that initchain hasn't been called 39 | app2 := NewStatesetApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg, simapp.EmptyAppOptions{}) 40 | _, err = app2.ExportAppStateAndValidators(false, []string{}) 41 | require.NoError(t, err, "ExportAppStateAndValidators should not have an error") 42 | } 43 | 44 | func TestGetMaccPerms(t *testing.T) { 45 | dup := GetMaccPerms() 46 | require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions") 47 | } -------------------------------------------------------------------------------- /app/encoding.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/std" 5 | "github.com/stateset/stateset-blockchain/app/params" 6 | ) 7 | 8 | // MakeEncodingConfig creates an EncodingConfig for testing 9 | func MakeEncodingConfig() params.EncodingConfig { 10 | encodingConfig := params.MakeEncodingConfig() 11 | std.RegisterLegacyAminoCodec(encodingConfig.Amino) 12 | std.RegisterInterfaces(encodingConfig.InterfaceRegistry) 13 | ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) 14 | ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) 15 | return encodingConfig 16 | } -------------------------------------------------------------------------------- /app/genesis.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | // The genesis state of the blockchain is represented here as a map of raw json 8 | // messages key'd by a identifier string. 9 | // The identifier is used to determine which module genesis information belongs 10 | // to so it may be appropriately routed during init chain. 11 | // Within this application default genesis information is retrieved from 12 | // the ModuleBasicManager which populates json from each BasicModule 13 | // object provided to it during init. 14 | type GenesisState map[string]json.RawMessage 15 | 16 | // NewDefaultGenesisState generates the default state for the application. 17 | func NewDefaultGenesisState() GenesisState { 18 | encCfg := MakeEncodingConfig() 19 | return ModuleBasics.DefaultGenesis(encCfg.Marshaler) 20 | } -------------------------------------------------------------------------------- /app/params/amino.go: -------------------------------------------------------------------------------- 1 | package params 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | "github.com/cosmos/cosmos-sdk/codec/types" 6 | authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" 7 | ) 8 | 9 | // MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. 10 | func MakeEncodingConfig() EncodingConfig { 11 | cdc := codec.New() 12 | interfaceRegistry := types.NewInterfaceRegistry() 13 | marshaler := codec.NewAminoCodec(cdc) 14 | 15 | return EncodingConfig{ 16 | InterfaceRegistry: interfaceRegistry, 17 | Marshaler: marshaler, 18 | TxConfig: authtypes.StdTxConfig{Cdc: cdc}, 19 | Amino: cdc, 20 | } 21 | } -------------------------------------------------------------------------------- /app/params/encoding.go: -------------------------------------------------------------------------------- 1 | package params 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/client" 5 | "github.com/cosmos/cosmos-sdk/codec" 6 | "github.com/cosmos/cosmos-sdk/codec/types" 7 | ) 8 | 9 | // EncodingConfig specifies the concrete encoding types to use for a given app. 10 | // This is provided for compatibility between protobuf and amino implementations. 11 | type EncodingConfig struct { 12 | InterfaceRegistry types.InterfaceRegistry 13 | Marshaler codec.Marshaler 14 | TxConfig client.TxConfig 15 | Amino *codec.LegacyAmino 16 | } 17 | -------------------------------------------------------------------------------- /app/params/proto.go: -------------------------------------------------------------------------------- 1 | package params 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | "github.com/cosmos/cosmos-sdk/codec/types" 6 | "github.com/cosmos/cosmos-sdk/x/auth/tx" 7 | ) 8 | 9 | // MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. 10 | func MakeEncodingConfig() EncodingConfig { 11 | amino := codec.NewLegacyAmino() 12 | interfaceRegistry := types.NewInterfaceRegistry() 13 | marshaler := codec.NewProtoCodec(interfaceRegistry) 14 | txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes) 15 | 16 | return EncodingConfig{ 17 | InterfaceRegistry: interfaceRegistry, 18 | Marshaler: marshaler, 19 | TxConfig: txCfg, 20 | Amino: amino, 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/types.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | abci "github.com/tendermint/tendermint/abci/types" 5 | 6 | "github.com/cosmos/cosmos-sdk/codec" 7 | servertypes "github.com/cosmos/cosmos-sdk/server/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | ) 10 | 11 | // App implements the common methods for a Cosmos SDK-based application 12 | // specific blockchain. 13 | type App interface { 14 | // The assigned name of the app. 15 | Name() string 16 | 17 | // The application types codec. 18 | // NOTE: This shoult be sealed before being returned. 19 | LegacyAmino() *codec.LegacyAmino 20 | 21 | // Application updates every begin block. 22 | BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock 23 | 24 | // Application updates every end block. 25 | EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock 26 | 27 | // Application update at chain (i.e app) initialization. 28 | InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain 29 | 30 | // Loads the app at a given height. 31 | LoadHeight(height int64) error 32 | 33 | // Exports the state of the application for a genesis file. 34 | ExportAppStateAndValidators( 35 | forZeroHeight bool, jailAllowedAddrs []string, 36 | ) (servertypes.ExportedApp, error) 37 | 38 | // All the registered module account addreses. 39 | ModuleAccountAddrs() map[string]bool 40 | } -------------------------------------------------------------------------------- /app/wasm_wrapper.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/server" 5 | ) 6 | 7 | type WasmWrapper struct { 8 | Wasm wasm.Config `mapstructure:"wasm"` 9 | } 10 | 11 | func getWasmConfig() wasm.Config { 12 | wasmWrap := WasmWrapper{Wasm: wasm.DefaultWasmConfig()} 13 | ctx := server.NewDefaultContext() 14 | err := ctx.Viper.Unmarshal(&wasmWrap) 15 | if err != nil { 16 | panic("error while reading wasm config: " + err.Error()) 17 | } 18 | 19 | return wasmWrap.Wasm 20 | } 21 | -------------------------------------------------------------------------------- /bash.exe.stackdump: -------------------------------------------------------------------------------- 1 | Stack trace: 2 | Frame Function Args 3 | 000FFFFC0B8 0018007164E (0018026F12D, 00180224DC6, 000FFFFC0B8, 000FFFFAFB0) 4 | 000FFFFC0B8 00180046669 (00000000000, 00000000000, 00000000000, 00000000008) 5 | 000FFFFC0B8 001800466A2 (0018026F1E9, 000FFFFBF68, 000FFFFC0B8, 00000000000) 6 | 000FFFFC0B8 001800BDFEF (00000000000, 00000000000, 00000000000, 00000000000) 7 | 000FFFFC0B8 001800BE20F (000FFFFC0E0, 00000000000, 00000000000, 00000000000) 8 | 000FFFFC160 001800BF4AD (000FFFFC0E0, 00000000000, 00000000000, 00000000000) 9 | End of stack trace 10 | -------------------------------------------------------------------------------- /cmd/statesetd/cmd/bech32.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | // DONTCOVER 4 | 5 | import ( 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/cosmos/cosmos-sdk/types/bech32" 9 | ) 10 | 11 | var ( 12 | flagBech32Prefix = "prefix" 13 | ) 14 | 15 | // get cmd to convert any bech32 address to an stateset prefix 16 | 17 | func ConvertBech32Cmd() *cobra.Command { 18 | cmd := &cobra.Command{ 19 | Use: "bech32-convert [bech32 string]", 20 | Short: "Convert any bech32 string to the stateset prefix", 21 | Long: `Convert any bech32 string to the stateset prefix 22 | Especially useful for converting cosmos addresses to statset addresses 23 | Example: 24 | statesetd bech32-convert stateset1ey69r37gfxvxg62sh4r0ktpuc46pzjrmz29g45 25 | `, 26 | Args: cobra.ExactArgs(1), 27 | RunE: func(cmd *cobra.Command, args []string) error { 28 | 29 | bech32prefix, err := cmd.Flags().GetString(flagBech32Prefix) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | _, bz, err := bech32.DecodeAndConvert(args[0]) 35 | if err != nil { 36 | return err 37 | } 38 | 39 | bech32Addr, err := bech32.ConvertAndEncode(bech32prefix, bz) 40 | if err != nil { 41 | panic(err) 42 | } 43 | 44 | cmd.Println(bech32Addr) 45 | 46 | return nil 47 | }, 48 | } 49 | 50 | cmd.Flags().StringP(flagBech32Prefix, "s", "stateset", "Bech32 Prefix to encode to") 51 | 52 | return cmd 53 | } -------------------------------------------------------------------------------- /cmd/statesetd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" 7 | "github.com/stateset/stateset-blockchain/app" 8 | "github.com/stateset/stateset-blockchain/cmd/statesetd/cmd" 9 | ) 10 | 11 | func main() { 12 | rootCmd, _ := NewRootCmd() 13 | 14 | if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil { 15 | switch e := err.(type) { 16 | case server.ErrorCode: 17 | os.Exit(e.Code) 18 | 19 | default: 20 | os.Exit(1) 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /config.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | accounts: 3 | - name: alice 4 | coins: ["1000token", "100000000stake"] 5 | - name: bob 6 | coins: ["500token"] 7 | validator: 8 | name: alice 9 | staked: "100000000stake" -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | statesetdnode0: 5 | container_name: statesetdnode0 6 | image: "stateset/statesetdnode" 7 | ports: 8 | - "26656-26657:26656-26657" 9 | environment: 10 | - ID=0 11 | - LOG=${LOG:-statesetd.log} 12 | volumes: 13 | - ./build:/statesetchaind:Z 14 | networks: 15 | localnet: 16 | ipv4_address: 192.168.10.2 17 | 18 | statesetdnode1: 19 | container_name: statesetdnode1 20 | image: "stateset/statesetdnode" 21 | ports: 22 | - "26659-26660:26656-26657" 23 | environment: 24 | - ID=1 25 | - LOG=${LOG:-statesetd.log} 26 | volumes: 27 | - ./build:/statesetd:Z 28 | networks: 29 | localnet: 30 | ipv4_address: 192.168.10.3 31 | 32 | statesetdnode2: 33 | container_name: statesetdnode2 34 | image: "stateset/statesetdnode" 35 | environment: 36 | - ID=2 37 | - LOG=${LOG:-statesetd.log} 38 | ports: 39 | - "26661-26662:26656-26657" 40 | volumes: 41 | - ./build:/statesetd:Z 42 | networks: 43 | localnet: 44 | ipv4_address: 192.168.10.4 45 | 46 | statesetdnode3: 47 | container_name: statesetdnode3 48 | image: "stateset/statesetdnode" 49 | environment: 50 | - ID=3 51 | - LOG=${LOG:-statesetd.log} 52 | ports: 53 | - "26663-26664:26656-26657" 54 | volumes: 55 | - ./build:/statesetd:Z 56 | networks: 57 | localnet: 58 | ipv4_address: 192.168.10.5 59 | 60 | networks: 61 | localnet: 62 | driver: bridge 63 | ipam: 64 | driver: default 65 | config: 66 | - 67 | subnet: 192.168.10.0/16 -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/stateset/stateset-blockchain 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/CosmWasm/wasmd v0.16.0 7 | github.com/cosmos/cosmos-sdk v0.42.6 8 | github.com/gogo/protobuf v1.3.3 9 | github.com/google/go-cmp v0.5.6 // indirect 10 | github.com/gorilla/mux v1.8.0 11 | github.com/grpc-ecosystem/grpc-gateway v1.16.0 12 | github.com/spf13/cast v1.3.1 13 | github.com/spf13/cobra v1.1.3 14 | github.com/stretchr/testify v1.7.0 15 | github.com/tendermint/spm v0.1.4 16 | github.com/tendermint/spm-extras v0.1.0 17 | github.com/tendermint/tendermint v0.34.11 18 | github.com/tendermint/tm-db v0.6.4 19 | google.golang.org/genproto v0.0.0-20210617175327-b9e0b3197ced 20 | google.golang.org/grpc v1.38.0 21 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect 22 | ) 23 | 24 | replace google.golang.org/grpc => google.golang.org/grpc v1.33.2 25 | 26 | replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 27 | -------------------------------------------------------------------------------- /internal/tools/tools.go: -------------------------------------------------------------------------------- 1 | // +build tools 2 | 3 | package tools 4 | 5 | import ( 6 | _ "github.com/golang/protobuf/protoc-gen-go" 7 | _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway" 8 | _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger" 9 | _ "github.com/regen-network/cosmos-proto/protoc-gen-gocosmos" 10 | ) 11 | -------------------------------------------------------------------------------- /math/math_test.go: -------------------------------------------------------------------------------- 1 | package math 2 | 3 | import ( 4 | "testing" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestAbsDifferenceWithSign(t *testing.T) { 12 | decA, err := sdk.NewDecFromStr("3.2") 13 | require.NoError(t, err) 14 | decB, err := sdk.NewDecFromStr("4.3432389") 15 | require.NoError(t, err) 16 | 17 | s, b := AbsDifferenceWithSign(decA, decB) 18 | require.True(t, b) 19 | 20 | expectedDec, err := sdk.NewDecFromStr("1.1432389") 21 | require.NoError(t, err) 22 | require.Equal(t, expectedDec, s) 23 | } 24 | 25 | func TestPowApprox(t *testing.T) { 26 | base, err := sdk.NewDecFromStr("0.8") 27 | require.NoError(t, err) 28 | exp, err := sdk.NewDecFromStr("0.32") 29 | require.NoError(t, err) 30 | 31 | s := PowApprox(base, exp, powPrecision) 32 | expectedDec, err := sdk.NewDecFromStr("0.93108385") 33 | require.NoError(t, err) 34 | 35 | require.True( 36 | t, 37 | expectedDec.Sub(s).Abs().LTE(powPrecision), 38 | "expected value & actual value's difference should less than precision", 39 | ) 40 | } 41 | 42 | func TestPow(t *testing.T) { 43 | base, err := sdk.NewDecFromStr("1.68") 44 | require.NoError(t, err) 45 | exp, err := sdk.NewDecFromStr("0.32") 46 | require.NoError(t, err) 47 | 48 | s := Pow(base, exp) 49 | expectedDec, err := sdk.NewDecFromStr("1.18058965") 50 | require.NoError(t, err) 51 | 52 | require.True( 53 | t, 54 | expectedDec.Sub(s).Abs().LTE(powPrecision), 55 | "expected value & actual value's difference should less than precision", 56 | ) 57 | } -------------------------------------------------------------------------------- /networks/local/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for the "statesetdnode" docker image. 2 | 3 | all: 4 | docker build --tag stateset/statesetdnode statesetdnode 5 | 6 | .PHONY: all -------------------------------------------------------------------------------- /networks/local/statesetdnode/Dockerfile: -------------------------------------------------------------------------------- 1 | #FROM alpine:3.10.2 2 | # 3 | #RUN apk update && \ 4 | # apk upgrade && \ 5 | # apk --no-cache add curl jq file 6 | 7 | # Changed from Alpine to Ubuntu because the keyring PR is linking to libc 8 | # Alpine uses muslc instead of libc 9 | 10 | FROM ubuntu:18.04 11 | 12 | RUN apt-get update && \ 13 | apt-get -y upgrade && \ 14 | apt-get -y install curl jq file 15 | 16 | VOLUME [ /statesetd ] 17 | WORKDIR /statesetd 18 | EXPOSE 26656 26657 19 | ENTRYPOINT ["/usr/bin/wrapper.sh"] 20 | CMD ["start"] 21 | STOPSIGNAL SIGTERM 22 | 23 | COPY wrapper.sh /usr/bin/wrapper.sh -------------------------------------------------------------------------------- /networks/local/statesetdnode/wrapper.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ## 4 | ## Input parameters 5 | ## 6 | BINARY=/statesetd/${BINARY:-statesetd} 7 | ID=${ID:-0} 8 | LOG=${LOG:-statesetd.log} 9 | 10 | ## 11 | ## Assert linux binary 12 | ## 13 | if ! [ -f "${BINARY}" ]; then 14 | echo "The binary $(basename "${BINARY}") cannot be found. Please add the binary to the shared folder. Please use the BINARY environment variable if the name of the binary is not 'statesetd' E.g.: -e BINARY=statesetd_my_test_version" 15 | exit 1 16 | fi 17 | BINARY_CHECK="$(file "$BINARY" | grep 'ELF 64-bit LSB executable, x86-64')" 18 | if [ -z "${BINARY_CHECK}" ]; then 19 | echo "Binary needs to be OS linux, ARCH amd64" 20 | exit 1 21 | fi 22 | 23 | ## 24 | ## Run binary with all parameters 25 | ## 26 | export STATESETDHOME="/statesetd/node${ID}/statesetd" 27 | 28 | if [ -d "$(dirname "${STATESETDHOME}"/"${LOG}")" ]; then 29 | "${BINARY}" --home "${STATESETDHOME}" "$@" | tee "${STATESETDHOME}/${LOG}" 30 | else 31 | "${BINARY}" --home "${STATESETDHOME}" "$@" 32 | fi -------------------------------------------------------------------------------- /ops/statesetd.service: -------------------------------------------------------------------------------- 1 | # Sets up systemd to start, stop, and restart the statesetd daemon. 2 | # This should live in /etc/systemd/system on an Ubuntu instance. 3 | # 4 | # Use like so: 5 | # sudo systemctl start statesetd.service 6 | # sudo systemctl stop statesetd.service 7 | # sudo systemctl restart statesetd.service 8 | # 9 | # Tail logs: 10 | # journalctl -u statesetd.service -f 11 | 12 | [Unit] 13 | Description=Stateset Node 14 | After=network-online.target 15 | 16 | [Service] 17 | User=ubuntu 18 | ExecStart=/home/ubuntu/go/bin/statesetd --log_level "main:info,state:info,*:error,app:info,account:info,statebank2:info,agreement:info,stateslashing:info,statefactoring:info" start 19 | Restart=always 20 | RestartSec=3 21 | LimitNOFILE=4096 22 | 23 | [Install] 24 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /proto/stateset/agreement/v1beta1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.agreement.v1beta1; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "stateset/agreement/v1beta1/agreement.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/agreement/types"; 8 | 9 | // GenesisState defines the genesis state used by agreement module 10 | message GenesisState { 11 | repeated Agreement agreements = 1 12 | [(gogoproto.nullable) = false, (gogoproto.jsontag) = "agreements", (gogoproto.moretags) = "yaml:\"agreements\""]; 13 | } -------------------------------------------------------------------------------- /proto/stateset/agreement/v1beta1/packet.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.agreement.v1beta1; 3 | 4 | // IbcAgreementPacketData defines a struct for the packet payload 5 | message IbcAgreementPacketData { 6 | string creator = 1; 7 | string agreement_id = 2; 8 | string agreement_number = 3; 9 | string agreement_name = 4; 10 | string agreement_type = 5; 11 | string agreement_status = 6; 12 | string total_agreement_value = 7; 13 | string party = 8; 14 | string counterparty = 9; 15 | string start_date = 10; 16 | string end_date = 11; 17 | } -------------------------------------------------------------------------------- /proto/stateset/agreement/v1beta1/sentAgreement.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.agreement.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/agreement/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message SentAgreement { 9 | string creator = 1; 10 | string agreement_id = 2; 11 | string agreement_number = 3; 12 | string agreement_name = 4; 13 | string agreement_type = 5; 14 | string agreement_status = 6; 15 | int32 total_agreement_value = 7; 16 | string party = 8; 17 | string counterparty = 9; 18 | string start_date = 10; 19 | string end_date = 11; 20 | } -------------------------------------------------------------------------------- /proto/stateset/agreement/v1beta1/timedoutAgreement.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.agreement.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/agreement/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message TimedoutAgreement { 9 | string creator = 1; 10 | string agreement_id = 2; 11 | string agreement_number = 3; 12 | string agreement_name = 4; 13 | string agreement_type = 5; 14 | string agreement_status = 6; 15 | int32 total_agreement_value = 7; 16 | string party = 8; 17 | string counterparty = 9; 18 | string start_date = 10; 19 | string end_date = 11; 20 | } -------------------------------------------------------------------------------- /proto/stateset/did/v1beta1/did.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package did; 3 | 4 | import "gogoproto/gogo.proto"; 5 | 6 | option go_package = "github.com/stateset/stateset-blockchain/x/did/types"; 7 | 8 | // Digital identity credential issued to an stateset DID 9 | message DidCredential { 10 | repeated string cred_type = 1 [(gogoproto.jsontag) = "type", (gogoproto.moretags) = "yaml:\"type\""]; 11 | string issuer = 2 [(gogoproto.moretags) = "yaml:\"issuer\""]; 12 | string issued = 3 [(gogoproto.moretags) = "yaml:\"issued\""]; 13 | Claim claim = 4 [(gogoproto.moretags) = "yaml:\"claim\""]; 14 | } 15 | 16 | // The claim section of a credential, indicating if the DID is KYC validated 17 | message Claim { 18 | string id = 1 [(gogoproto.moretags) = "yaml:\"id\""]; 19 | bool KYC_validated = 2 [(gogoproto.jsontag) = "KYCValidated", (gogoproto.moretags) = "yaml:\"KYCValidated\""]; 20 | } 21 | 22 | // A Stateset DID with public and private keys 23 | message StatesetDid { 24 | string did = 1 [(gogoproto.moretags) = "yaml:\"did\""]; 25 | string verify_key = 2 [(gogoproto.jsontag) = "verifyKey", (gogoproto.moretags) = "yaml:\"verifyKey\""]; 26 | string encryption_public_key = 3 [(gogoproto.jsontag) = "encryptionPublicKey", (gogoproto.moretags) = "yaml:\"encryptionPublicKey\""]; 27 | Secret secret = 4 [(gogoproto.moretags) = "yaml:\"secret\""]; 28 | } 29 | 30 | // The private section of an stateset DID 31 | message Secret { 32 | string seed = 1 [(gogoproto.moretags) = "yaml:\"seed\""]; 33 | string sign_key = 2 [(gogoproto.jsontag) = "signKey", (gogoproto.moretags) = "yaml:\"signKey\""]; 34 | string encryption_private_key = 3 [(gogoproto.jsontag) = "encryptionPrivateKey", (gogoproto.moretags) = "yaml:\"encryptionPrivateKey\""]; 35 | } -------------------------------------------------------------------------------- /proto/stateset/did/v1beta1/diddoc.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package did; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "did/did.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/did/types"; 8 | 9 | // BaseDidDoc defines a base DID document type. It implements the DidDoc interface. 10 | message BaseDidDoc { 11 | option (gogoproto.goproto_stringer) = false; 12 | option (gogoproto.goproto_getters) = false; 13 | option (gogoproto.equal) = false; 14 | 15 | string did = 1 [(gogoproto.moretags) = "yaml:\"did\"" ]; 16 | string pub_key = 2 [(gogoproto.jsontag) = "pubKey", (gogoproto.moretags) = "yaml:\"pubKey\"" ]; 17 | repeated DidCredential credentials = 3 [(gogoproto.moretags) = "yaml:\"credentials\""]; 18 | } -------------------------------------------------------------------------------- /proto/stateset/did/v1beta1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package did; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "google/protobuf/any.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/did/types"; 8 | 9 | // GenesisState defines the did module's genesis state. 10 | message GenesisState { 11 | repeated google.protobuf.Any did_docs = 1 [(gogoproto.moretags) = "yaml:\"did_docs\""]; 12 | } -------------------------------------------------------------------------------- /proto/stateset/did/v1beta1/tx.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package did; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "did/did.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/did/types"; 8 | 9 | // Msg defines the did Msg service. 10 | service Msg { 11 | // AddDid defines a method for adding a DID. 12 | rpc AddDid(MsgAddDid) returns (MsgAddDidResponse); 13 | 14 | // AddCredential defines a method for adding a credential to the signer's DID. 15 | rpc AddCredential(MsgAddCredential) returns (MsgAddCredentialResponse); 16 | } 17 | 18 | // MsgAddDid defines a message for adding a DID. 19 | message MsgAddDid { 20 | string did = 1 [(gogoproto.moretags) = "json:\"did\" yaml:\"did\""]; 21 | string pubKey = 2 [(gogoproto.moretags) = "json:\"pubKey\" yaml:\"pubKey\""]; 22 | } 23 | 24 | // MsgAddDidResponse defines the Msg/AddDid response type. 25 | message MsgAddDidResponse {} 26 | 27 | // MsgAddCredential defines a message for adding a credential to the signer's DID. 28 | message MsgAddCredential { 29 | DidCredential did_credential = 1 [(gogoproto.nullable) = false, (gogoproto.jsontag) = "credential", (gogoproto.moretags) = "yaml:\"credential\""]; 30 | } 31 | 32 | // MsgAddCredentialResponse defines the Msg/AddCredential response type. 33 | message MsgAddCredentialResponse {} -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/account/account.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package ibc.account; 3 | 4 | import "cosmos_proto/cosmos.proto"; 5 | import "gogoproto/gogo.proto"; 6 | 7 | import "cosmos/auth/v1beta1/auth.proto"; 8 | 9 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/core/types"; 10 | 11 | // IBCAccount defines an account to which other chains have privileges 12 | message IBCAccount { 13 | option (gogoproto.goproto_getters) = false; 14 | option (gogoproto.goproto_stringer) = false; 15 | option (cosmos_proto.implements_interface) = "IBCAccountI"; 16 | 17 | cosmos.auth.v1beta1.BaseAccount base_account = 1 [(gogoproto.embed) = true, (gogoproto.moretags) = "yaml:\"base_account\""]; 18 | string sourcePort = 2; 19 | string sourceChannel = 3; 20 | string destinationPort = 4; 21 | string destinationChannel = 5; 22 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/account/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package ibc.account; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/core/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | // GenesisState defines the ibc-account genesis state 9 | message GenesisState { 10 | string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""]; 11 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/account/query.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package ibc.account; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "google/api/annotations.proto"; 6 | 7 | import "ibc/account/account.proto"; 8 | 9 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/core/types"; 10 | 11 | // Query defines the gRPC querier service. 12 | service Query { 13 | rpc IBCAccount(QueryIBCAccountRequest) returns (QueryIBCAccountResponse) { 14 | option (google.api.http).get = "/cosmos/ibc/v1beta1/ibc-account/{address}"; 15 | } 16 | 17 | rpc IBCAccountFromData(QueryIBCAccountFromDataRequest) returns (QueryIBCAccountResponse) { 18 | option (google.api.http).get = "/cosmos/ibc/v1beta1/ibc-account-from-data/{port}/{channel}/{data}"; 19 | } 20 | } 21 | 22 | message QueryIBCAccountRequest { 23 | option (gogoproto.equal) = false; 24 | option (gogoproto.goproto_getters) = false; 25 | 26 | // address is the address to query. 27 | string address = 1; 28 | } 29 | 30 | message QueryIBCAccountFromDataRequest { 31 | option (gogoproto.equal) = false; 32 | option (gogoproto.goproto_getters) = false; 33 | 34 | string port = 1; 35 | string channel = 2; 36 | string data = 3; 37 | } 38 | 39 | message QueryIBCAccountResponse { 40 | // account defines the account of the corresponding address. 41 | ibc.account.IBCAccount account = 1; 42 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/account/types.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package ibc.account; 3 | 4 | import "google/protobuf/any.proto"; 5 | 6 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/core/types"; 7 | 8 | message IBCTxRaw { 9 | bytes body_bytes = 1; 10 | } 11 | 12 | message IBCTxBody { 13 | repeated google.protobuf.Any messages = 1; 14 | } 15 | 16 | enum Type { 17 | REGISTER = 0; 18 | RUNTX = 1; 19 | } 20 | 21 | message IBCAccountPacketData { 22 | Type type = 1; 23 | bytes data = 2; 24 | } 25 | 26 | message IBCAccountPacketAcknowledgement { 27 | Type type = 1; 28 | string chainID = 2; 29 | uint32 code = 3; 30 | bytes data = 4; 31 | string error = 5; 32 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/ibcdex/v1alpha1/buyOrderBook.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.ibcdex.v1alpha1 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message BuyOrderBook { 9 | string index = 2; 10 | int32 orderIDTrack = 3; 11 | string amountDenom = 4; 12 | string priceDenom = 5; 13 | } 14 | -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/ibcdex/v1alpha1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.ibcdex.v1alpha1 3 | 4 | import "ibcdex/v1alpha1/buyOrderBook.proto"; 5 | import "ibcdex/v1alpha1/sellOrderBook.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types"; 8 | 9 | // GenesisState defines the ibcdex module's genesis state. 10 | message GenesisState { 11 | repeated BuyOrderBook buyOrderBookList = 3; 12 | repeated SellOrderBook sellOrderBookList = 2; 13 | string port_id = 1; 14 | } 15 | -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/ibcdex/v1alpha1/sellOrderBook.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.ibcdex.v1alpha1 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message SellOrderBook { 9 | string index = 2; 10 | int32 orderIDTrack = 3; 11 | string amountDenom = 4; 12 | string priceDenom = 5; 13 | } 14 | -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/transfer/v1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.applications.transfer.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/apps/transfer/types"; 6 | 7 | import "ibc/applications/transfer/v1/transfer.proto"; 8 | import "gogoproto/gogo.proto"; 9 | 10 | // GenesisState defines the ibc-transfer genesis state 11 | message GenesisState { 12 | string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""]; 13 | repeated DenomTrace denom_traces = 2 [ 14 | (gogoproto.castrepeated) = "Traces", 15 | (gogoproto.nullable) = false, 16 | (gogoproto.moretags) = "yaml:\"denom_traces\"" 17 | ]; 18 | Params params = 3 [(gogoproto.nullable) = false]; 19 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/applications/transfer/v1/transfer.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.applications.transfer.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/apps/transfer/types"; 6 | 7 | import "gogoproto/gogo.proto"; 8 | 9 | // FungibleTokenPacketData defines a struct for the packet payload 10 | // See FungibleTokenPacketData spec: 11 | // https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#data-structures 12 | message FungibleTokenPacketData { 13 | // the token denomination to be transferred 14 | string denom = 1; 15 | // the token amount to be transferred 16 | uint64 amount = 2; 17 | // the sender address 18 | string sender = 3; 19 | // the recipient address on the destination chain 20 | string receiver = 4; 21 | } 22 | 23 | // DenomTrace contains the base denomination for ICS20 fungible tokens and the 24 | // source tracing information path. 25 | message DenomTrace { 26 | // path defines the chain of port/channel identifiers used for tracing the 27 | // source of the fungible token. 28 | string path = 1; 29 | // base denomination of the relayed fungible token. 30 | string base_denom = 2; 31 | } 32 | 33 | // Params defines the set of IBC transfer parameters. 34 | // NOTE: To prevent a single token from being transferred, set the 35 | // TransfersEnabled parameter to true and then set the bank module's SendEnabled 36 | // parameter for the denomination to false. 37 | message Params { 38 | // send_enabled enables or disables all cross-chain token transfers from this 39 | // chain. 40 | bool send_enabled = 1 [(gogoproto.moretags) = "yaml:\"send_enabled\""]; 41 | // receive_enabled enables or disables all cross-chain token transfers to this 42 | // chain. 43 | bool receive_enabled = 2 [(gogoproto.moretags) = "yaml:\"receive_enabled\""]; 44 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/core/channel/v1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.core.channel.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/core/04-channel/types"; 6 | 7 | import "gogoproto/gogo.proto"; 8 | import "ibc/core/channel/v1/channel.proto"; 9 | 10 | // GenesisState defines the ibc channel submodule's genesis state. 11 | message GenesisState { 12 | repeated IdentifiedChannel channels = 1 [(gogoproto.casttype) = "IdentifiedChannel", (gogoproto.nullable) = false]; 13 | repeated PacketState acknowledgements = 2 [(gogoproto.nullable) = false]; 14 | repeated PacketState commitments = 3 [(gogoproto.nullable) = false]; 15 | repeated PacketState receipts = 4 [(gogoproto.nullable) = false]; 16 | repeated PacketSequence send_sequences = 5 17 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"send_sequences\""]; 18 | repeated PacketSequence recv_sequences = 6 19 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"recv_sequences\""]; 20 | repeated PacketSequence ack_sequences = 7 21 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"ack_sequences\""]; 22 | // the sequence for the next generated channel identifier 23 | uint64 next_channel_sequence = 8 [(gogoproto.moretags) = "yaml:\"next_channel_sequence\""]; 24 | } 25 | 26 | // PacketSequence defines the genesis type necessary to retrieve and store 27 | // next send and receive sequences. 28 | message PacketSequence { 29 | string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""]; 30 | string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""]; 31 | uint64 sequence = 3; 32 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/core/commitment/v1/commitment.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.core.commitment.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/core/23-commitment/types"; 6 | 7 | import "gogoproto/gogo.proto"; 8 | import "confio/proofs.proto"; 9 | 10 | // MerkleRoot defines a merkle root hash. 11 | // In the Cosmos SDK, the AppHash of a block header becomes the root. 12 | message MerkleRoot { 13 | option (gogoproto.goproto_getters) = false; 14 | 15 | bytes hash = 1; 16 | } 17 | 18 | // MerklePrefix is merkle path prefixed to the key. 19 | // The constructed key from the Path and the key will be append(Path.KeyPath, 20 | // append(Path.KeyPrefix, key...)) 21 | message MerklePrefix { 22 | bytes key_prefix = 1 [(gogoproto.moretags) = "yaml:\"key_prefix\""]; 23 | } 24 | 25 | // MerklePath is the path used to verify commitment proofs, which can be an 26 | // arbitrary structured object (defined by a commitment type). 27 | // MerklePath is represented from root-to-leaf 28 | message MerklePath { 29 | option (gogoproto.goproto_stringer) = false; 30 | 31 | repeated string key_path = 1 [(gogoproto.moretags) = "yaml:\"key_path\""]; 32 | } 33 | 34 | // MerkleProof is a wrapper type over a chain of CommitmentProofs. 35 | // It demonstrates membership or non-membership for an element or set of 36 | // elements, verifiable in conjunction with a known commitment root. Proofs 37 | // should be succinct. 38 | // MerkleProofs are ordered from leaf-to-root 39 | message MerkleProof { 40 | repeated ics23.CommitmentProof proofs = 1; 41 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/core/connection/v1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.core.connection.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/core/03-connection/types"; 6 | 7 | import "gogoproto/gogo.proto"; 8 | import "ibc/core/connection/v1/connection.proto"; 9 | 10 | // GenesisState defines the ibc connection submodule's genesis state. 11 | message GenesisState { 12 | repeated IdentifiedConnection connections = 1 [(gogoproto.nullable) = false]; 13 | repeated ConnectionPaths client_connection_paths = 2 14 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"client_connection_paths\""]; 15 | // the sequence for the next generated connection identifier 16 | uint64 next_connection_sequence = 3 [(gogoproto.moretags) = "yaml:\"next_connection_sequence\""]; 17 | Params params = 4 [(gogoproto.nullable) = false]; 18 | } -------------------------------------------------------------------------------- /proto/stateset/ibc/core/types/v1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ibc.core.types.v1; 4 | 5 | option go_package = "github.com/cosmos/ibc-go/modules/core/types"; 6 | 7 | import "gogoproto/gogo.proto"; 8 | import "ibc/core/client/v1/genesis.proto"; 9 | import "ibc/core/connection/v1/genesis.proto"; 10 | import "ibc/core/channel/v1/genesis.proto"; 11 | 12 | // GenesisState defines the ibc module's genesis state. 13 | message GenesisState { 14 | // ICS002 - Clients genesis state 15 | ibc.core.client.v1.GenesisState client_genesis = 1 16 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"client_genesis\""]; 17 | // ICS003 - Connections genesis state 18 | ibc.core.connection.v1.GenesisState connection_genesis = 2 19 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"connection_genesis\""]; 20 | // ICS004 - Channel genesis state 21 | ibc.core.channel.v1.GenesisState channel_genesis = 3 22 | [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"channel_genesis\""]; 23 | } -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/events.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package stateset.invoice.v1beta1; 4 | 5 | import "gogoproto/gogo.proto"; 6 | 7 | option go_package = "github.com/stateset/stateset-blockchain/x/invoice"; 8 | 9 | // EventCreateInvoice is an event emitted when an invoice is created. 10 | message EventCreateInvoice { 11 | 12 | // invoice_id is the unique ID of invoice 13 | string invoice_id = 1 [ (gogoproto.moretags) = "yaml:\"invoice_id\"" ]; 14 | 15 | // creator is the creator of the invoice 16 | string creator = 2; 17 | } 18 | 19 | 20 | // EventCompleted is an event emitted when an invoice is completed. 21 | message EventCompleted { 22 | 23 | // agreement_id is the unique ID of invoice 24 | string invoice_id = 1 [ (gogoproto.moretags) = "yaml:\"invoice_id\"" ]; 25 | 26 | // creator is the creator of the invoice 27 | string creator = 2; 28 | } 29 | 30 | // EventCancelled is an event emitted when an invoice is cancelled. 31 | message EventCancelled { 32 | 33 | // agreement_id is the unique ID of invoice 34 | string invoice_id = 1 [ (gogoproto.moretags) = "yaml:\"invoice_id\"" ]; 35 | 36 | // creator is the creator of the invoice 37 | string creator = 2; 38 | } 39 | 40 | // EventFactored is an event emitted when an invoice is factored. 41 | message EventFactored { 42 | 43 | // invoice_id is the unique ID of invoice 44 | string invoice_id = 1 [ (gogoproto.moretags) = "yaml:\"invoice_id\"" ]; 45 | 46 | // creator is the creator of the invoice 47 | string creator = 2; 48 | } -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.invoive.v1beta1; 3 | 4 | import "stateset-blockchain/invoice.proto"; 5 | 6 | option go_package = "github.com/stateset/stateset-blockchain/x/invoice/types"; 7 | 8 | // GenesisState defines the genesis state used by agreement module 9 | message GenesisState { 10 | 11 | repeated Invoice invoices = 1; 12 | 13 | uint64 invoiceCount = 2; 14 | 15 | } -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/packet.proto: -------------------------------------------------------------------------------- 1 | // IbcInvoicePacketData defines a struct for the packet payload 2 | message IbcInvoicePacketData { 3 | string creator = 1; 4 | string invoice_id = 2; 5 | string invoice_number = 3; 6 | string invoice_name = 4; 7 | string billing_reason = 5; 8 | string amount_due = 6; 9 | string amount_paid = 7; 10 | string amount_remaining = 8; 11 | string subtotal = 9; 12 | string total = 10; 13 | string party = 11; 14 | string counterparty = 12; 15 | string factor = 13; 16 | string due_date = 14; 17 | string period_start_date = 15; 18 | string period_end_date = 16; 19 | } -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/query.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.invoice.v1beta1; 3 | 4 | import "cosmos_proto/cosmos.proto"; 5 | import "gogoproto/gogo.proto"; 6 | import "google/protobuf/any.proto"; 7 | import "google/api/annotations.proto"; 8 | import "cosmos/base/query/v1beta1/pagination.proto"; 9 | 10 | option go_package = "github.com/stateset/stateset-blockchain/x/invoice/types"; 11 | 12 | // Query defines the gRPC querier service. 13 | service Query { 14 | 15 | // Queries a day by id. 16 | rpc Invoice(QueryGetInvoiceRequest) returns (QueryGetInvoiceResponse) { 17 | option (google.api.http).get = "/stateset/invoice/v1beta1/invoices/{invoice_id}"; 18 | } 19 | 20 | // Invoices returns purchase order details based on purchase order. 21 | rpc Invoices(QueryInvoicesRequest) returns (QueryInvoicesResponse) { 22 | option (google.api.http).get = "/stateset/invoice/v1beta1/invoices"; 23 | } 24 | 25 | 26 | } 27 | 28 | // QueryInvoiceRequest is the Query/Invoice request type. 29 | message QueryInvoiceRequest { 30 | 31 | // invoice_id is the unique ID of invoice to query. 32 | string invoice_id = 1 [(gogoproto.moretags) = "yaml:\"invoice_id\""]; 33 | } 34 | 35 | message QueryInvoiceResponse { 36 | repeated QueryInvoiceResponse invoices = 1; 37 | 38 | } 39 | 40 | message QueryAllInvoiceResponse { 41 | repeated Invoice Invoice = 1; 42 | cosmos.base.query.v1beta1.PageResponse pagination = 2; 43 | } 44 | 45 | 46 | message QueryInvoiceResponse {} -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/sentInvoice.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.invoice.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/invoice/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message SentInvoice { 9 | string creator = 1; 10 | string invoice_id = 2; 11 | string invoicenumber = 3; 12 | string invoicename = 4; 13 | string billingreason = 5; 14 | string amountdue = 6; 15 | string amountpaid = 7; 16 | string amountremaining = 8; 17 | string subtotal = 9; 18 | string total = 10; 19 | string party = 11; 20 | string counterparty = 12; 21 | string factor = 13; 22 | string duedate = 14; 23 | string periodstartdate = 15; 24 | string periodenddate = 16; 25 | } -------------------------------------------------------------------------------- /proto/stateset/invoice/v1beta1/timedoutInvoice.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.invoice.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/invoice/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message TimedoutAgreement { 9 | string creator = 1; 10 | string invoice_id = 2; 11 | string invoicenumber = 3; 12 | string invoicename = 4; 13 | string billingreason = 5; 14 | string amountdue = 6; 15 | string amountpaid = 7; 16 | string amountremaining = 8; 17 | string subtotal = 9; 18 | string total = 10; 19 | string party = 11; 20 | string counterparty = 12; 21 | string factor = 13; 22 | string duedate = 14; 23 | string periodstartdate = 15; 24 | string periodenddate = 16; 25 | } -------------------------------------------------------------------------------- /proto/stateset/params/params.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package cosmos.params.v1beta1; 3 | 4 | option go_package = "github.com/cosmos/cosmos-sdk/x/params/types/proposal"; 5 | option (gogoproto.equal_all) = true; 6 | 7 | import "gogoproto/gogo.proto"; 8 | 9 | // ParameterChangeProposal defines a proposal to change one or more parameters. 10 | message ParameterChangeProposal { 11 | option (gogoproto.goproto_getters) = false; 12 | option (gogoproto.goproto_stringer) = false; 13 | 14 | string title = 1; 15 | string description = 2; 16 | repeated ParamChange changes = 3 [(gogoproto.nullable) = false]; 17 | } 18 | 19 | // ParamChange defines an individual parameter change, for use in 20 | // ParameterChangeProposal. 21 | message ParamChange { 22 | option (gogoproto.goproto_stringer) = false; 23 | 24 | string subspace = 1; 25 | string key = 2; 26 | string value = 3; 27 | } -------------------------------------------------------------------------------- /proto/stateset/params/query.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.params; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "google/api/annotations.proto"; 6 | import "stateset/params/params.proto"; 7 | 8 | option go_package = "github.com/cosmos/cosmos-sdk/x/params/types/proposal"; 9 | 10 | // Query defines the gRPC querier service. 11 | service Query { 12 | // Params queries a specific parameter of a module, given its subspace and 13 | // key. 14 | rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { 15 | option (google.api.http).get = "/stateset/params/params"; 16 | } 17 | } 18 | 19 | // QueryParamsRequest is request type for the Query/Params RPC method. 20 | message QueryParamsRequest { 21 | // subspace defines the module to query the parameter for. 22 | string subspace = 1; 23 | 24 | // key defines the key of the parameter in the subspace. 25 | string key = 2; 26 | } 27 | 28 | // QueryParamsResponse is response type for the Query/Params RPC method. 29 | message QueryParamsResponse { 30 | // param defines the queried parameter. 31 | ParamChange param = 1 [(gogoproto.nullable) = false]; 32 | } -------------------------------------------------------------------------------- /proto/stateset/purchaseorder/v1beta1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.purchaseorder.v1beta1; 3 | 4 | import "stateset-blockchain/purchaseorder.proto"; 5 | 6 | option go_package = "github.com/stateset/stateset-blockchain/x/purchaseorders/types"; 7 | 8 | // GenesisState defines the genesis state used by agreement module 9 | message GenesisState { 10 | 11 | repeated PurchaseOrder purchaseorders = 1; 12 | 13 | uint64 purchaseOrderCount = 2; 14 | 15 | } -------------------------------------------------------------------------------- /proto/stateset/purchaseorder/v1beta1/packet.proto: -------------------------------------------------------------------------------- 1 | // IbcPurchaseOrderPacketData defines a struct for the packet payload 2 | message IbcPurchaseOrderPacketData { 3 | string creator = 1; 4 | string purchaseorder_id = 2; 5 | string purchaseorder_number = 3; 6 | string purchaseorder_hash = 4; 7 | string purchaseorder_status = 5; 8 | string description = 6; 9 | string purchase_date = 7; 10 | string delivery_date = 8; 11 | string subtotal = 9; 12 | string total = 10; 13 | string purchaser = 11; 14 | string vendor = 12; 15 | string fulfiller = 13; 16 | string financer = 14; 17 | 18 | } -------------------------------------------------------------------------------- /proto/stateset/purchaseorder/v1beta1/query.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.purchaseorder.v1beta1; 3 | 4 | import "cosmos_proto/cosmos.proto"; 5 | import "gogoproto/gogo.proto"; 6 | import "google/protobuf/any.proto"; 7 | import "google/api/annotations.proto"; 8 | import "cosmos/base/query/v1beta1/pagination.proto"; 9 | 10 | option go_package = "github.com/stateset/stateset-blockchain/x/purchaseorder/types"; 11 | 12 | // Query defines the gRPC querier service. 13 | service Query { 14 | 15 | // PurchaseOrders returns purchase order details based on purchase order. 16 | rpc PurchaseOrders(QueryPurchaseOrdersRequest) returns (QueryPurchaseOrdersResponse) { 17 | option (google.api.http).get = 18 | "/stateset/purchaseorder/v1beta1/purchaseorders"; 19 | } 20 | 21 | // Purchase Order returns purchase order details based on purchase order. 22 | rpc PurchaseOrder(QueryPurchaseOrderRequest) returns (QueryPurchaseOrderResponse) { 23 | option (google.api.http).get = 24 | "/stateset/purchaseorder/v1beta1/purchaseorders/{purchaseorder_id}"; 25 | } 26 | 27 | } 28 | 29 | // QueryPurchaseOrderRequest is the Query/PurchaseOrder request type. 30 | message QueryPurchaseOrderRequest { 31 | 32 | // purchase_id is the unique ID of purchase order to query. 33 | string purchaseorder_id = 1 [ (gogoproto.moretags) = "yaml:\"purchaseorder_id\"" ]; 34 | 35 | } 36 | 37 | message QueryPurchaseOrderResponse { 38 | 39 | PurchaseOrder purchaseorder = 1; 40 | 41 | } 42 | 43 | 44 | message QueryPurchaseOrdersRequest { 45 | 46 | cosmos.base.query.v1beta1.PageRequest pagination = 1; 47 | 48 | } 49 | 50 | 51 | message QueryPurchaseOrdersResponse { 52 | 53 | repeated PurchaseOrder PurchaseOrder = 1; 54 | 55 | cosmos.base.query.v1beta1.PageResponse pagination = 2; 56 | } -------------------------------------------------------------------------------- /proto/stateset/purchaseorder/v1beta1/sentPurchaseOrder.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.purchaseorder.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/purchaseorder/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message SentPurchaseOrder { 9 | string creator = 1; 10 | string purchaseorder_id = 2; 11 | string purchaseorder_number = 3; 12 | string purchaseorder_hash = 4; 13 | string purchaseorder_status = 5; 14 | string description = 6; 15 | string purchase_date = 7; 16 | string delivery_date = 8; 17 | string subtotal = 9; 18 | string total = 10; 19 | string purchaser = 11; 20 | string vendor = 12; 21 | string fulfiller = 13; 22 | string financer = 14; 23 | } -------------------------------------------------------------------------------- /proto/stateset/purchaseorder/v1beta1/timedoutPurchaseOrder.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.purchaseorder.v1beta1; 3 | 4 | option go_package = "github.com/stateset/stateset-blockchain/x/purchaseorder/types"; 5 | 6 | import "gogoproto/gogo.proto"; 7 | 8 | message TimedOutPurchaseOrder { 9 | string creator = 1; 10 | string purchaseorder_id = 2; 11 | string purchaseorder_number = 3; 12 | string purchaseorder_hash = 4; 13 | string purchaseorder_status = 5; 14 | string description = 6; 15 | string purchase_date = 7; 16 | string delivery_date = 8; 17 | string subtotal = 9; 18 | string total = 10; 19 | string purchaser = 11; 20 | string vendor = 12; 21 | string fulfiller = 13; 22 | string financer = 14; 23 | } -------------------------------------------------------------------------------- /proto/stateset/wasm/v1beta1/genesis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package stateset.wasm.v1beta1; 3 | 4 | import "gogoproto/gogo.proto"; 5 | import "stateset/wasm/v1beta1/wasm.proto"; 6 | import "cosmos/base/v1beta1/coin.proto"; 7 | 8 | option go_package = "github.com/stateset/stateset-blockchain/x/wasm/internal/types"; 9 | 10 | // GenesisState defines the oracle module's genesis state. 11 | message GenesisState { 12 | Params params = 1 [(gogoproto.nullable) = false]; 13 | uint64 last_code_id = 2 [(gogoproto.customname) = "LastCodeID"]; 14 | uint64 last_instance_id = 3 [(gogoproto.customname) = "LastInstanceID"]; 15 | repeated Code codes = 4 [(gogoproto.nullable) = false]; 16 | repeated Contract contracts = 5 [(gogoproto.nullable) = false]; 17 | } 18 | 19 | // Model is a struct that holds a KV pair 20 | message Model { 21 | bytes key = 1; 22 | bytes value = 2; 23 | } 24 | 25 | // Code struct encompasses CodeInfo and CodeBytes 26 | message Code { 27 | CodeInfo code_info = 1 [(gogoproto.nullable) = false]; 28 | bytes code_bytes = 2; 29 | } 30 | 31 | // Contract struct encompasses ContractAddress, ContractInfo, and ContractState 32 | message Contract { 33 | ContractInfo contract_info = 1 [(gogoproto.nullable) = false]; 34 | repeated Model contract_store = 2 [(gogoproto.nullable) = false]; 35 | } -------------------------------------------------------------------------------- /scripts/protocgen: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # see pre-requests: 4 | # - https://grpc.io/docs/languages/go/quickstart/ 5 | # - gocosmos plugin is automatically installed during scaffolding. 6 | 7 | set -eo pipefail 8 | 9 | proto_dirs=$(find ./proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) 10 | for dir in $proto_dirs; do 11 | protoc \ 12 | -I "proto" \ 13 | -I "third_party/proto" \ 14 | --gocosmos_out=plugins=interfacetype+grpc,\ 15 | Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. \ 16 | $(find "${dir}" -maxdepth 1 -name '*.proto') 17 | 18 | # command to generate gRPC gateway (*.pb.gw.go in respective modules) files 19 | protoc \ 20 | -I "proto" \ 21 | -I "third_party/proto" \ 22 | --grpc-gateway_out=logtostderr=true:. \ 23 | $(find "${dir}" -maxdepth 1 -name '*.proto') 24 | done 25 | 26 | 27 | # move proto files to the right places 28 | cp -r github.com/stateset/stateset-blockchain/* ./ 29 | rm -rf github.com 30 | -------------------------------------------------------------------------------- /startnode.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf $HOME/.statesetd/ 4 | 5 | cd $HOME 6 | 7 | statesetd init --chain-id=testing testing --home=$HOME/.statesetd 8 | statesetd keys add validator --keyring-backend=test --home=$HOME/.statesetd 9 | statesetd add-genesis-account $(statesetd keys show validator -a --keyring-backend=test --home=$HOME/.statesetd) 1000000000stake,1000000000valtoken --home=$HOME/.statesetd 10 | statesetd gentx validator 500000000stake --keyring-backend=test --home=$HOME/.statesetd --chain-id=testing 11 | statesetd collect-gentxs --home=$HOME/.statesetd 12 | 13 | cat $HOME/.statesetd/config/genesis.json | jq '.app_state["gov"]["voting_params"]["voting_period"]="10s"' > $HOME/.statesetd/config/tmp_genesis.json && mv $HOME/.statesetd/config/tmp_genesis.json $HOME/.statesetd/config/genesis.json 14 | 15 | statesetd start --home=$HOME/.statesetd -------------------------------------------------------------------------------- /stateset-blockchain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NodesBlocks/stateset-blockchain/a360be6951a04d052240d897d66b2eeb47ebdeaa/stateset-blockchain.png -------------------------------------------------------------------------------- /types/address.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "crypto/sha256" 4 | 5 | func AddressHash(prefix string, contents []byte) []byte { 6 | preImage := []byte(prefix) 7 | if len(contents) != 0 { 8 | preImage = append(preImage, 0) 9 | preImage = append(preImage, contents...) 10 | } 11 | sum := sha256.Sum256(preImage) 12 | return sum[:20] 13 | } -------------------------------------------------------------------------------- /types/conn.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "context" 5 | 6 | "google.golang.org/grpc" 7 | ) 8 | 9 | type InvokerConn interface { 10 | grpc.ClientConnInterface 11 | Invoker(methodName string) (Invoker, error) 12 | } 13 | 14 | type Invoker func(ctx context.Context, request, response interface{}, opts ...interface{}) -------------------------------------------------------------------------------- /types/context.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "context" 5 | "time" 6 | 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | ) 9 | 10 | type Context struct { 11 | sdk.Context 12 | } 13 | 14 | var _ context.Context = Context{} 15 | 16 | func (c Context) Deadline() (deadline time.Time, ok bool) { 17 | return c.Context.Context().Deadline() 18 | } 19 | 20 | func (c Context) Done() <-chan struct{} { 21 | return c.Context.Context().Done() 22 | } 23 | 24 | func (c Context) Err() error { 25 | return c.Context.Context().Err() 26 | } 27 | 28 | func UnwrapSDKContext(ctx context.Context) Context { 29 | if sdkCtx, ok := ctx.(Context); ok { 30 | return sdkCtx 31 | } 32 | return Context{sdk.UnwrapSDKContext(ctx)} 33 | } -------------------------------------------------------------------------------- /types/id.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import sdk "github.com/cosmos/cosmos-sdk/types" 4 | 5 | type ModuleID struct { 6 | ModuleName string 7 | Path []byte 8 | } 9 | 10 | func (m ModuleID) Address() sdk.AccAddress { 11 | return AddressHash(m.ModuleName, m.Path) 12 | } -------------------------------------------------------------------------------- /types/util/address.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import "fmt" 4 | 5 | const ( 6 | // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address 7 | Bech32PrefixAccAddr = "stateset" 8 | // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key 9 | Bech32PrefixAccPub = "statesetpub" 10 | // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address 11 | Bech32PrefixValAddr = "statesetvaloper" 12 | // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key 13 | Bech32PrefixValPub = "statesetvaloperpub" 14 | // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address 15 | Bech32PrefixConsAddr = "statesetvalcons" 16 | // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key 17 | Bech32PrefixConsPub = "statesetvalconspub" 18 | ) 19 | 20 | var ( 21 | // AddressVerifier stateset address verifier 22 | AddressVerifier = func(bz []byte) error { 23 | if n := len(bz); n != 20 { 24 | return fmt.Errorf("incorrect address length %d", n) 25 | } 26 | 27 | return nil 28 | } 29 | ) -------------------------------------------------------------------------------- /types/util/blocks.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | ) 6 | 7 | // nolint 8 | const ( 9 | BlocksPerMinute = uint64(10) 10 | BlocksPerHour = BlocksPerMinute * 60 11 | BlocksPerDay = BlocksPerHour * 24 12 | BlocksPerWeek = BlocksPerDay * 7 13 | BlocksPerMonth = BlocksPerDay * 30 14 | BlocksPerYear = BlocksPerDay * 365 15 | ) 16 | 17 | // IsPeriodLastBlock returns true if we are at the last block of the period 18 | func IsPeriodLastBlock(ctx sdk.Context, blocksPerPeriod uint64) bool { 19 | return ((uint64)(ctx.BlockHeight())+1)%blocksPerPeriod == 0 20 | } -------------------------------------------------------------------------------- /x/README.md: -------------------------------------------------------------------------------- 1 | # Stateset Modules 2 | 3 | These are the modules that make Stateset: 4 | 5 | `stateset` is built on the Cosmos SDK using the following modules: 6 | 7 | - `x/agreement`: Agreement logic. 8 | - `x/common`: Common logic. 9 | - `x/did`: DID logic. 10 | - `x/ibc`: IBC logic. 11 | - `x/invoice`: Invoice logic. 12 | - `x/purchaseorder`: Purchase Order logic. 13 | - `x/wasm`: CosmWasm Smart Contracts. 14 | -------------------------------------------------------------------------------- /x/agreement/genesis.go: -------------------------------------------------------------------------------- 1 | package agreement 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | "github.com/stateset/stateset-blockchain/x/agreement/keeper" 6 | "github.com/stateset/stateset-blockchain/x/agreement/types" 7 | ) 8 | 9 | // DefaultGenesis returns the default Capability genesis state 10 | func DefaultGenesis() *GenesisState { 11 | return &GenesisState{ 12 | AgreementList: []*Agreement{}, 13 | } 14 | } 15 | 16 | 17 | func (gs GenesisState) Validate() error { 18 | 19 | agreementIdMap := make(map[uint64]bool) 20 | 21 | for _, elem := range gs.AgreementList { 22 | if _, ok := agreementIdMap[elem.Id]; ok { 23 | return fmt.Errorf("duplicated id for agreement") 24 | } 25 | agreementIdMap[elem.Id] = true 26 | } 27 | 28 | return nil 29 | } 30 | 31 | // ExportGenesis returns the capability module's exported genesis. 32 | func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { 33 | params, _ := k.GetParams(ctx) 34 | genesis := types.DefaultGenesis() 35 | genesis.Agreements = k.GetAgreements(ctx) 36 | genesis.PortId = k.GetPort(ctx) 37 | 38 | return genesis 39 | } -------------------------------------------------------------------------------- /x/agreement/handler/handler.go: -------------------------------------------------------------------------------- 1 | package agreement 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | ) 9 | 10 | // NewHandler returns a handler for "agreement" type messages 11 | func NewHandler(keeper Keeper) sdk.Handler { 12 | ms := NewServer(keepers) 13 | 14 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 15 | switch msg := msg.(type) { 16 | case *types.MsgCreateAgreement: 17 | res, err := ms.Create(sdk.WrapSDKContext(ctx), msg) 18 | return sdk.WrapServiceResult(ctx, res, err) 19 | 20 | case *types.MsgUpdateAgreement: 21 | res, err := ms.Update(sdk.WrapSDKContext(ctx), msg) 22 | return sdk.WrapServiceResult(ctx, res, err) 23 | 24 | case *types.MsgDeleteAgreement: 25 | res, err := ms.Delete(sdk.WrapSDKContext(ctx), msg) 26 | return sdk.WrapServiceResult(ctx, res, err) 27 | 28 | case *types.MsgRenewAgreement: 29 | res, err := ms.Renew(sdk.WrapSDKContext(ctx), msg) 30 | return sdk.WrapServiceResult(ctx, res, err) 31 | 32 | case *types.MsgAmendAgreement: 33 | res, err := ms.Amend(sdk.WrapSDKContext(ctx), msg) 34 | return sdk.WrapServiceResult(ctx, res, err) 35 | 36 | case *types.MsgTerminateAgreement: 37 | res, err := ms.Terminate(sdk.WrapSDKContext(ctx), msg) 38 | return sdk.WrapServiceResult(ctx, res, err) 39 | 40 | case *types.MsgExpireAgreement: 41 | res, err := ms.Expire(sdk.WrapSDKContext(ctx), msg) 42 | return sdk.WrapServiceResult(ctx, res, err) 43 | 44 | default: 45 | return nil, sdkerrors.ErrUnknownRequest 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /x/agreement/keeper/keeper_test.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/cosmos/cosmos-sdk/codec" 7 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 8 | "github.com/cosmos/cosmos-sdk/store" 9 | storetypes "github.com/cosmos/cosmos-sdk/store/types" 10 | sdk "github.com/cosmos/cosmos-sdk/types" 11 | "github.com/stateset/stateset-blockchain/x/agreement/types" 12 | "github.com/stretchr/testify/require" 13 | "github.com/tendermint/tendermint/libs/log" 14 | tmproto "github.com/tendermint/tendermint/proto/tendermint/types" 15 | tmdb "github.com/tendermint/tm-db" 16 | ) 17 | 18 | func setupKeeper(t testing.TB) (*Keeper, sdk.Context) { 19 | storeKey := sdk.NewKVStoreKey(types.StoreKey) 20 | memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) 21 | 22 | db := tmdb.NewMemDB() 23 | stateStore := store.NewCommitMultiStore(db) 24 | stateStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, db) 25 | stateStore.MountStoreWithDB(memStoreKey, sdk.StoreTypeMemory, nil) 26 | require.NoError(t, stateStore.LoadLatestVersion()) 27 | 28 | registry := codectypes.NewInterfaceRegistry() 29 | keeper := NewKeeper( 30 | codec.NewProtoCodec(registry), storeKey, memStoreKey, 31 | nil, nil, nil, 32 | ) 33 | 34 | ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) 35 | return keeper, ctx 36 | } 37 | -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/agreement/types" 5 | ) 6 | 7 | type msgServer struct { 8 | Keeper 9 | } 10 | 11 | // NewMsgServerImpl returns an implementation of the MsgServer interface 12 | // for the provided Keeper. 13 | func NewMsgServerImpl(keeper Keeper) types.MsgServer { 14 | return &msgServer{Keeper: keeper} 15 | } 16 | 17 | var _ types.MsgServer = msgServer{} 18 | 19 | func (server msgServer) CreateAgreement(goCtx context.Context, msg *types.MsgCreateAgreement) (*types.MsgCreateAgreementResponse, error) { 20 | ctx := sdk.UnwrapSDKContext(goCtx) 21 | 22 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 23 | if err != nil { 24 | return nil, err 25 | } 26 | 27 | poolId, err := server.keeper.CreateAgreement(ctx, sender, msg.AgreementParams, msg.AgremenetAssets) 28 | if err != nil { 29 | return nil, err 30 | } 31 | 32 | agreement, found := k.GetAgreement(ctx, msg.Id) 33 | agreement.AgreementStatus = "created" 34 | 35 | // Verify the Value of the Agreement from existing system 36 | k.zkpKeeper.VerifyProof(ctx, agreement) 37 | 38 | // Add a DID to represent the Agreement in the Cosmosverse DID:STATESET:AGREEMENT:123 39 | k.didKeeper.AddDID(ctx, agreementhash) 40 | 41 | // Mint a NFT that represents the Agreement DID and Value of the Agreement 42 | k.nftKeeper.MintNFT(ctx, did) 43 | 44 | ctx.EventManager().EmitEvents(sdk.Events{ 45 | sdk.NewEvent( 46 | types.TypeEvtPurchaseOrderCreated, 47 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(purchaseOrderId, 10)), 48 | ), 49 | sdk.NewEvent( 50 | sdk.EventTypeMessage, 51 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 52 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 53 | ), 54 | }) 55 | 56 | return &types.MsgCreatePurchaseOrderResponse{}, nil 57 | } -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_activate_agreement.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (k msgServer) ActivateAgreement(goCtx context.Context, msg *types.MsgActivateAgreement) (*types.MsgActivateAgreementResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | agreement, found := k.GetAgreement(ctx, msg.Id) 16 | if !found { 17 | return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) 18 | } 19 | 20 | if agreement.State != "requested" { 21 | return nil, sdkerrors.Wrapf(types.ErrWrongAgreementState, "%v", agreement.State) 22 | } 23 | 24 | borrower, _ := sdk.AccAddressFromBech32(loan.Borrower) 25 | collateral, _ := sdk.ParseCoinsNormalized(loan.Collateral) 26 | k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, borrower, collateral) 27 | 28 | agreement.State = "activated" 29 | 30 | k.SetAgreement(ctx, agreement) 31 | 32 | return &types.MsgActivateAgreementResponse{}, nil 33 | } -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_create_agreement.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (server msgServer) CreateAgreement(goCtx context.Context, msg *types.MsgCreateAgreement) (*types.MsgCreateAgreementResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | poolId, err := server.keeper.CreateAgreement(ctx, sender, msg.AgreementParams, msg.AgremenetAssets) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | agreement, found := k.GetAgreement(ctx, msg.Id) 26 | agreement.AgreementStatus = "created" 27 | 28 | // Verify the Value of the Agreement from existing system 29 | k.zkpKeeper.VerifyProof(ctx, agreement) 30 | 31 | // Add a DID to represent the Agreement in the Cosmosverse DID:STATESET:AGREEMENT:123 32 | k.didKeeper.AddDID(ctx, agreementhash) 33 | 34 | // Mint a NFT that represents the Agreement DID and Value of the Agreement 35 | k.nftKeeper.MintNFT(ctx, did) 36 | 37 | ctx.EventManager().EmitEvents(sdk.Events{ 38 | sdk.NewEvent( 39 | types.TypeEvtPurchaseOrderCreated, 40 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(purchaseOrderId, 10)), 41 | ), 42 | sdk.NewEvent( 43 | sdk.EventTypeMessage, 44 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 45 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 46 | ), 47 | }) 48 | 49 | return &types.MsgCreatePurchaseOrderResponse{}, nil 50 | } -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_ibcAgreement.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | "github.com/stateset/stateset-blockchain/x/agreement/types" 9 | ) 10 | 11 | func (k msgServer) SendIbcAgreement(goCtx context.Context, msg *types.MsgSendIbcAgreement) (*types.MsgSendIbcAgreementResponse, error) { 12 | ctx := sdk.UnwrapSDKContext(goCtx) 13 | 14 | // Construct the packet 15 | var packet types.IbcAgreementPacketData 16 | 17 | packet.AgreementID = msg.agreementID 18 | packet.AgreementNumber = msg.agreementNumber 19 | packet.AgreementName = msg.agreementName 20 | packet.AgreementType = msg.agreementType 21 | packet.AgreementStatus = msg.agreementStatus 22 | packet.TotalAgreementValue = msg.totalAgreementValue 23 | packet.Party = msg.party 24 | packet.Counterparty = msg.counterparty 25 | packet.AgreementStartBlock = msg.agreementStartBlock 26 | packet.AgreementEndBlock = msg.agreementEndBlock 27 | 28 | // Transmit the packet 29 | err := k.TransmitIbcAgreementPacket( 30 | ctx, 31 | packet, 32 | msg.Port, 33 | msg.ChannelID, 34 | clienttypes.ZeroHeight(), 35 | msg.TimeoutTimestamp, 36 | ) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | return &types.MsgSendIbcAgreementResponse{}, nil 42 | } 43 | -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_renew_agreement.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (k msgServer) RenewAgreement(goCtx context.Context, msg *types.MsgRenewAgreement) (*types.MsgRenewAgreementResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | agreement, found := k.GetAgreement(ctx, msg.Id) 16 | if !found { 17 | return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) 18 | } 19 | 20 | if agreement.State != "activated" { 21 | return nil, sdkerrors.Wrapf(types.ErrWrongAgreementState, "%v", agreement.State) 22 | } 23 | 24 | borrower, _ := sdk.AccAddressFromBech32(loan.Borrower) 25 | collateral, _ := sdk.ParseCoinsNormalized(loan.Collateral) 26 | k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, borrower, collateral) 27 | 28 | agreement.State = "renewed" 29 | 30 | k.SetAgreement(ctx, agreement) 31 | 32 | return &types.MsgRenewAgreementResponse{}, nil 33 | } -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_terminate_agreement.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (k msgServer) TerminateAgreement(goCtx context.Context, msg *types.MsgTerminateAgreement) (*types.MsgTerminateAgreementResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | agreement, found := k.GetAgreement(ctx, msg.Id) 16 | if !found { 17 | return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) 18 | } 19 | 20 | if agreement.State != "activated" { 21 | return nil, sdkerrors.Wrapf(types.ErrWrongAgreementState, "%v", agreement.State) 22 | } 23 | 24 | agreement.State = "terminated" 25 | 26 | k.SetAgreement(ctx, agreement) 27 | 28 | return &types.MsgTerminatedAgreementResponse{}, nil 29 | } -------------------------------------------------------------------------------- /x/agreement/keeper/msg_server_test.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/stateset/stateset-blockchain/x/agreement/types" 9 | ) 10 | 11 | func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { 12 | keeper, ctx := setupKeeper(t) 13 | return NewMsgServerImpl(*keeper), sdk.WrapSDKContext(ctx) 14 | } 15 | -------------------------------------------------------------------------------- /x/agreement/keeper/sentAgreement_test.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "testing" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func createNSentAgreement(keeper *Keeper, ctx sdk.Context, n int) []types.SentAgreement { 12 | items := make([]types.SentAgreement, n) 13 | for i := range items { 14 | items[i].Creator = "any" 15 | items[i].Id = keeper.AppendSentAgreement(ctx, items[i]) 16 | } 17 | return items 18 | } 19 | 20 | func TestSentAgreementGet(t *testing.T) { 21 | keeper, ctx := setupKeeper(t) 22 | items := createNSentAgreement(keeper, ctx, 10) 23 | for _, item := range items { 24 | assert.Equal(t, item, keeper.GetSentAgreement(ctx, item.Id)) 25 | } 26 | } 27 | 28 | func TestSentAgreementExist(t *testing.T) { 29 | keeper, ctx := setupKeeper(t) 30 | items := createNSentAgreement(keeper, ctx, 10) 31 | for _, item := range items { 32 | assert.True(t, keeper.HasSentAgreement(ctx, item.Id)) 33 | } 34 | } 35 | 36 | func TestSentAgreementRemove(t *testing.T) { 37 | keeper, ctx := setupKeeper(t) 38 | items := createNSentAgreement(keeper, ctx, 10) 39 | for _, item := range items { 40 | keeper.RemoveSentAgreement(ctx, item.Id) 41 | assert.False(t, keeper.HasSentAgreement(ctx, item.Id)) 42 | } 43 | } 44 | 45 | func TestSentAgreementGetAll(t *testing.T) { 46 | keeper, ctx := setupKeeper(t) 47 | items := createNSentAgreement(keeper, ctx, 10) 48 | assert.Equal(t, items, keeper.GetAllSentAgreement(ctx)) 49 | } 50 | 51 | func TestSentAgreementCount(t *testing.T) { 52 | keeper, ctx := setupKeeper(t) 53 | items := createNSentAgreement(keeper, ctx, 10) 54 | count := uint64(len(items)) 55 | assert.Equal(t, count, keeper.GetSentAgreementCount(ctx)) 56 | } 57 | -------------------------------------------------------------------------------- /x/agreement/keeper/timedoutAgreement_test.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "testing" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/agreement/types" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func createNTimedoutAgreement(keeper *Keeper, ctx sdk.Context, n int) []types.TimedoutAgreement { 12 | items := make([]types.TimedoutAgreement, n) 13 | for i := range items { 14 | items[i].Creator = "any" 15 | items[i].Id = keeper.AppendTimedoutAgreement(ctx, items[i]) 16 | } 17 | return items 18 | } 19 | 20 | func TestTimedoutAgreementGet(t *testing.T) { 21 | keeper, ctx := setupKeeper(t) 22 | items := createNTimedoutAgreement(keeper, ctx, 10) 23 | for _, item := range items { 24 | assert.Equal(t, item, keeper.GetTimedoutAgreement(ctx, item.Id)) 25 | } 26 | } 27 | 28 | func TestTimedoutAgreementExist(t *testing.T) { 29 | keeper, ctx := setupKeeper(t) 30 | items := createNTimedoutAgreement(keeper, ctx, 10) 31 | for _, item := range items { 32 | assert.True(t, keeper.HasTimedoutAgreement(ctx, item.Id)) 33 | } 34 | } 35 | 36 | func TestTimedoutAgreementRemove(t *testing.T) { 37 | keeper, ctx := setupKeeper(t) 38 | items := createNTimedoutAgreement(keeper, ctx, 10) 39 | for _, item := range items { 40 | keeper.RemoveTimedoutAgreement(ctx, item.Id) 41 | assert.False(t, keeper.HasTimedoutAgreement(ctx, item.Id)) 42 | } 43 | } 44 | 45 | func TestTimedoutAgreementGetAll(t *testing.T) { 46 | keeper, ctx := setupKeeper(t) 47 | items := createNTimedoutAgreement(keeper, ctx, 10) 48 | assert.Equal(t, items, keeper.GetAllTimedoutAgreement(ctx)) 49 | } 50 | 51 | func TestTimedoutAgreementCount(t *testing.T) { 52 | keeper, ctx := setupKeeper(t) 53 | items := createNTimedoutAgreement(keeper, ctx, 10) 54 | count := uint64(len(items)) 55 | assert.Equal(t, count, keeper.GetTimedoutAgreementCount(ctx)) 56 | } 57 | -------------------------------------------------------------------------------- /x/agreement/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // DONTCOVER 4 | 5 | import ( 6 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 7 | ) 8 | 9 | // x/agreement module sentinel errors 10 | var ( 11 | ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") 12 | ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 1500, "invalid packet timeout") 13 | ErrInvalidVersion = sdkerrors.Register(ModuleName, 1501, "invalid version") 14 | ErrWrongAgreementState = sdkerrors.Register(ModuleName, 6, "invalide agreement state") 15 | ) 16 | ) 17 | -------------------------------------------------------------------------------- /x/agreement/types/events.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | const ( 4 | TypeEvtAgreementCreated = "agreement_created" 5 | TypeEvtAgreementActivated = "agreement_activated" 6 | TypeEvtAgreementAmended = "agreement_amended" 7 | TypeEvtAgreementRenewed = "agreement_renewed" 8 | TypeEvtAgreementExpired = "agreement_expired" 9 | TypeEvtAgreementTerminated = "agreement_terminated" 10 | 11 | AttributeValueCategory = ModuleName 12 | AttributeKeyAgreementId = "agreement_id" 13 | ) -------------------------------------------------------------------------------- /x/agreement/types/events_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // IBC events 4 | const ( 5 | EventTypeTimeout = "timeout" 6 | // this line is used by starport scaffolding # ibc/packet/event 7 | 8 | AttributeKeyAckSuccess = "success" 9 | AttributeKeyAck = "acknowledgement" 10 | AttributeKeyAckError = "error" 11 | ) 12 | -------------------------------------------------------------------------------- /x/agreement/types/expected_keeper_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" 6 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 7 | ibcexported "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" 8 | ) 9 | 10 | // ChannelKeeper defines the expected IBC channel keeper 11 | type ChannelKeeper interface { 12 | GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) 13 | GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) 14 | SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error 15 | ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error 16 | } 17 | 18 | // PortKeeper defines the expected IBC port keeper 19 | type PortKeeper interface { 20 | BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability 21 | } 22 | 23 | // ScopedKeeper defines the expected IBC scoped keeper 24 | type ScopedKeeper interface { 25 | GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) 26 | AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool 27 | ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error 28 | } 29 | -------------------------------------------------------------------------------- /x/agreement/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" 7 | ) 8 | 9 | // DefaultIndex is the default capability global index 10 | const DefaultIndex uint64 = 1 11 | 12 | // DefaultGenesis returns the default Capability genesis state 13 | func DefaultGenesis() *GenesisState { 14 | return &GenesisState{ 15 | PortId: PortID, 16 | // this line is used by starport scaffolding # genesis/types/default 17 | TimedoutAgreementList: []*TimedoutAgreement{}, 18 | SentAgreementList: []*SentAgreement{}, 19 | } 20 | } 21 | 22 | // Validate performs basic genesis state validation returning an error upon any 23 | // failure. 24 | func (gs GenesisState) Validate() error { 25 | if err := host.PortIdentifierValidator(gs.PortId); err != nil { 26 | return err 27 | } 28 | 29 | // this line is used by starport scaffolding # genesis/types/validate 30 | // Check for duplicated ID in timedoutAgreement 31 | timedoutAgreementIdMap := make(map[uint64]bool) 32 | 33 | for _, elem := range gs.TimedoutAgreementList { 34 | if _, ok := timedoutAgreementIdMap[elem.Id]; ok { 35 | return fmt.Errorf("duplicated id for timedoutAgreement") 36 | } 37 | timedoutAgreementIdMap[elem.Id] = true 38 | } 39 | // Check for duplicated ID in sentAgreement 40 | sentAgreementIdMap := make(map[uint64]bool) 41 | 42 | for _, elem := range gs.SentAgreementList { 43 | if _, ok := sentAgreementIdMap[elem.Id]; ok { 44 | return fmt.Errorf("duplicated id for sentAgreement") 45 | } 46 | sentAgreementIdMap[elem.Id] = true 47 | } 48 | 49 | return nil 50 | } 51 | -------------------------------------------------------------------------------- /x/agreement/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | const ( 4 | ModuleName = "agreement" 5 | 6 | StoreKey = ModuleName 7 | 8 | DefaultParamspace = ModuleName 9 | 10 | RouterKey = ModuleName 11 | 12 | QuerierRoute = ModuleName 13 | 14 | MemStoreKey = "mem_agreement" 15 | 16 | // Version defines the current version the IBC module supports 17 | Version = "agreement-1" 18 | 19 | // PortID is the default port id that module binds to 20 | PortID = "agreement" 21 | ) 22 | 23 | var ( 24 | // PortKey defines the key to store the port ID in store 25 | PortKey = KeyPrefix("agreement-port-") 26 | ) 27 | 28 | func KeyPrefix(p string) []byte { 29 | return []byte(p) 30 | } 31 | -------------------------------------------------------------------------------- /x/agreement/types/packet_ibcAgreement.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // ValidateBasic is used for validating the packet 4 | func (p IbcAgreementPacketData) ValidateBasic() error { 5 | 6 | // TODO: Validate the packet data 7 | 8 | return nil 9 | } 10 | 11 | // GetBytes is a helper for serialising 12 | func (p IbcAgreementPacketData) GetBytes() ([]byte, error) { 13 | var modulePacket AgreementPacketData 14 | 15 | modulePacket.Packet = &AgreementPacketData_IbcAgreementPacket{&p} 16 | 17 | return modulePacket.Marshal() 18 | } 19 | -------------------------------------------------------------------------------- /x/common/const.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | ) 6 | 7 | // const 8 | const ( 9 | NativeToken = sdk.DefaultBondDenom 10 | TestToken = "xxb" 11 | 12 | blackHoleHex = "0000000000000000000000000000000000000000" 13 | ) 14 | -------------------------------------------------------------------------------- /x/common/monitor/config.go: -------------------------------------------------------------------------------- 1 | package monitor 2 | 3 | // const 4 | const ( 5 | xNameSpace = "x" 6 | orderSubSystem = "order" 7 | stakingSubSystem = "staking" 8 | streamSubSystem = "stream" 9 | ) 10 | 11 | type prometheusConfig struct { 12 | // when true, Prometheus metrics are served under /metrics on PrometheusListenAddr 13 | Prometheus bool 14 | } 15 | 16 | // DefaultPrometheusConfig returns a default PrometheusConfig pointer 17 | func DefaultPrometheusConfig() *prometheusConfig { 18 | return &prometheusConfig{ 19 | Prometheus: true, 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /x/common/monitor/stream.go: -------------------------------------------------------------------------------- 1 | package monitor 2 | 3 | import ( 4 | "github.com/go-kit/kit/metrics" 5 | "github.com/go-kit/kit/metrics/discard" 6 | "github.com/go-kit/kit/metrics/prometheus" 7 | stdprometheus "github.com/prometheus/client_golang/prometheus" 8 | ) 9 | 10 | // StreamMetrics is the struct of metric in stream module 11 | type StreamMetrics struct { 12 | CacheSize metrics.Gauge 13 | } 14 | 15 | // DefaultStreamMetrics returns Metrics build using Prometheus client library if Prometheus is enabled 16 | // Otherwise, it returns no-op Metrics 17 | func DefaultStreamMetrics(config *prometheusConfig) *StreamMetrics { 18 | if config.Prometheus { 19 | return NewStreamMetrics() 20 | } 21 | return NopStreamMetrics() 22 | } 23 | 24 | // NewStreamMetrics returns a pointer of a new StreamMetrics object 25 | func NewStreamMetrics(labelsAndValues ...string) *StreamMetrics { 26 | var labels []string 27 | for i := 0; i < len(labelsAndValues); i += 2 { 28 | labels = append(labels, labelsAndValues[i]) 29 | } 30 | return &StreamMetrics{ 31 | CacheSize: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ 32 | Namespace: xNameSpace, 33 | Subsystem: streamSubSystem, 34 | Name: "cache_size", 35 | Help: "the excuting cache queue size in stream module.", 36 | }, labels).With(labelsAndValues...), 37 | } 38 | } 39 | 40 | // NopStreamMetrics returns a pointer of no-op Metrics 41 | func NopStreamMetrics() *StreamMetrics { 42 | return &StreamMetrics{ 43 | //PulsarSendNum: discard.NewGauge(), 44 | CacheSize: discard.NewGauge(), 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /x/common/proto/keys.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | ) 6 | 7 | // keys 8 | var ( 9 | upgradeConfigKey = []byte("upgrade_config") 10 | currentVersionKey = []byte("current_version") 11 | lastFailedVersionKey = []byte("last_failed_version") 12 | cdc = codec.New() 13 | ) 14 | -------------------------------------------------------------------------------- /x/common/proto/test_common.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/cosmos/cosmos-sdk/store" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | "github.com/stretchr/testify/require" 10 | abci "github.com/tendermint/tendermint/abci/types" 11 | "github.com/tendermint/tendermint/libs/log" 12 | dbm "github.com/tendermint/tm-db" 13 | ) 14 | 15 | func createTestInput(t *testing.T) (sdk.Context, ProtocolKeeper) { 16 | keyMain := sdk.NewKVStoreKey("main") 17 | 18 | db := dbm.NewMemDB() 19 | ms := store.NewCommitMultiStore(db) 20 | ms.MountStoreWithDB(keyMain, sdk.StoreTypeIAVL, db) 21 | 22 | require.NoError(t, ms.LoadLatestVersion()) 23 | 24 | ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewTMLogger(os.Stdout)) 25 | 26 | keeper := NewProtocolKeeper(keyMain) 27 | 28 | return ctx, keeper 29 | } 30 | -------------------------------------------------------------------------------- /x/common/sample_sys_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestEnableSampleSystestAll(t *testing.T) { 11 | 12 | e := os.Setenv("SYS_TEST_ALL", "1") 13 | require.Nil(t, e) 14 | 15 | SkipSysTestChecker(t) 16 | require.True(t, true) 17 | } 18 | 19 | func TestEnableSampleSystestSingle(t *testing.T) { 20 | 21 | e := os.Setenv("SYS_TEST_ALL", "0") 22 | require.Nil(t, e) 23 | e = os.Setenv("SAMPLE_SYS_TEST", "1") 24 | require.Nil(t, e) 25 | 26 | SkipSysTestChecker(t) 27 | require.True(t, true) 28 | } 29 | 30 | func TestDisableSampleSystest(t *testing.T) { 31 | SkipSysTestChecker(t) 32 | require.True(t, false) 33 | } 34 | -------------------------------------------------------------------------------- /x/common/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | // ProtocolVersionType is the type of protocol version 4 | type ProtocolVersionType int32 5 | 6 | // const 7 | const ( 8 | ProtocolVersionV0 ProtocolVersionType = 0 9 | ProtocolVersionV1 ProtocolVersionType = 1 10 | CurrentProtocolVersion = ProtocolVersionV0 11 | Version = "0" 12 | ) 13 | -------------------------------------------------------------------------------- /x/did/genesis.go: -------------------------------------------------------------------------------- 1 | package did 2 | 3 | import ( 4 | "fmt" 5 | 6 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/gogo/protobuf/proto" 9 | "github.com/stateset/stateset-blockchain/x/did/exported" 10 | "github.com/stateset/stateset-blockchain/x/did/keeper" 11 | "github.com/stateset/stateset-blockchain/x/did/types" 12 | abci "github.com/tendermint/tendermint/abci/types" 13 | ) 14 | 15 | func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs *types.GenesisState) []abci.ValidatorUpdate { 16 | // Initialise did docs 17 | for _, d := range gs.DidDocs { 18 | dd, ok := d.GetCachedValue().(exported.DidDoc) 19 | if !ok { 20 | panic("expected DidDoc") 21 | } 22 | 23 | k.AddDidDoc(ctx, dd) 24 | } 25 | 26 | return []abci.ValidatorUpdate{} 27 | } 28 | 29 | func ExportGenesis(ctx sdk.Context, k keeper.Keeper) (data types.GenesisState) { 30 | dds := k.GetAllDidDocs(ctx) 31 | diddocs := make([]*codectypes.Any, len(dds)) 32 | for i, dd := range dds { 33 | msg, ok := dd.(proto.Message) 34 | if !ok { 35 | panic(fmt.Errorf("cannot proto marshal %T", dd)) 36 | } 37 | any, err := codectypes.NewAnyWithValue(msg) 38 | if err != nil { 39 | panic(err) 40 | } 41 | diddocs[i] = any 42 | } 43 | 44 | return types.GenesisState{ 45 | DidDocs: diddocs, 46 | } 47 | } -------------------------------------------------------------------------------- /x/did/handler.go: -------------------------------------------------------------------------------- 1 | package did 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | "github.com/stateset/stateset-blockchain/x/did/keeper" 7 | "github.com/stateset/stateset-blockchain/x/did/types" 8 | ) 9 | 10 | func NewHandler(k keeper.Keeper) sdk.Handler { 11 | msgServer := keeper.NewMsgServerImpl(k) 12 | 13 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 14 | ctx = ctx.WithEventManager(sdk.NewEventManager()) 15 | switch msg := msg.(type) { 16 | case *types.MsgAddDid: 17 | res, err := msgServer.AddDid(sdk.WrapSDKContext(ctx), msg) 18 | return sdk.WrapServiceResult(ctx, res, err) 19 | case *types.MsgAddCredential: 20 | res, err := msgServer.AddCredential(sdk.WrapSDKContext(ctx), msg) 21 | return sdk.WrapServiceResult(ctx, res, err) 22 | default: 23 | return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, 24 | "unrecognized %s Msg type: %v", types.ModuleName, msg.Type()) 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /x/did/types/codec.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | "github.com/cosmos/cosmos-sdk/codec/types" 6 | cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/cosmos/cosmos-sdk/types/msgservice" 9 | "github.com/stateset/stateset-blockchain/x/did/exported" 10 | ) 11 | 12 | func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { 13 | cdc.RegisterInterface((*exported.DidDoc)(nil), nil) 14 | 15 | cdc.RegisterConcrete(&MsgAddDid{}, "did/AddDid", nil) 16 | cdc.RegisterConcrete(&MsgAddCredential{}, "did/AddCredential", nil) 17 | 18 | cdc.RegisterConcrete(&BaseDidDoc{}, "did/BaseDidDoc", nil) 19 | } 20 | 21 | func RegisterInterfaces(registry types.InterfaceRegistry) { 22 | registry.RegisterInterface( 23 | "did.DidDoc", 24 | (*exported.DidDoc)(nil), 25 | &BaseDidDoc{}, 26 | ) 27 | 28 | registry.RegisterImplementations((*sdk.Msg)(nil), 29 | &MsgAddDid{}, 30 | &MsgAddCredential{}, 31 | ) 32 | 33 | msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) 34 | } 35 | 36 | var ( 37 | amino = codec.NewLegacyAmino() 38 | 39 | // ModuleCdc references the global x/did module codec. Note, the codec should 40 | // ONLY be used in certain instances of tests and for JSON encoding as Amino is 41 | // still used for that purpose. 42 | // 43 | // The actual codec used for serialization should be provided to x/did and 44 | // defined at the application level. 45 | ModuleCdc = codec.NewAminoCodec(amino) 46 | ) 47 | 48 | func init() { 49 | RegisterLegacyAminoCodec(amino) 50 | cryptocodec.RegisterCrypto(amino) 51 | } -------------------------------------------------------------------------------- /x/did/types/error.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 5 | ) 6 | 7 | const ( 8 | DefaultCodespace = ModuleName 9 | ) 10 | 11 | var ( 12 | ErrInvalidDid = sdkerrors.Register(DefaultCodespace, 2, "invalid did") 13 | ErrInvalidPubKey = sdkerrors.Register(DefaultCodespace, 3, "invalid pubKey") 14 | ErrDidPubKeyMismatch = sdkerrors.Register(DefaultCodespace, 4, "did pubKey mismatch") 15 | ErrInvalidIssuer = sdkerrors.Register(DefaultCodespace, 5, "invalid issuer") 16 | ErrInvalidCredentials = sdkerrors.Register(DefaultCodespace, 6, "invalid credentials") 17 | ErrInvalidClaimId = sdkerrors.Register(DefaultCodespace, 7, "invalid claim ID") 18 | ) -------------------------------------------------------------------------------- /x/did/types/events.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | const ( 4 | EventTypeAddDidDoc = "add_did_doc" 5 | EventTypeAddCredential = "add_credential" 6 | 7 | AttributeKeyDid = "did" 8 | AttributeKeyPubKey = "pub_key" 9 | AttributeKeyCredType = "cred_type" 10 | AttributeKeyIssuer = "issuer" 11 | AttributeKeyIssued = "issued" 12 | AttributeKeyClaimID = "claim" 13 | AttributeKeyKYCValidated = "kyc_validated" 14 | AttributeValueCategory = ModuleName 15 | ) -------------------------------------------------------------------------------- /x/did/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/cosmos/cosmos-sdk/codec/types" 7 | "github.com/gogo/protobuf/proto" 8 | "github.com/stateset/stateset-blockchain/x/did/exported" 9 | ) 10 | 11 | func NewGenesisState(dd []exported.DidDoc) *GenesisState { 12 | didDocs := make([]*types.Any, len(dd)) 13 | 14 | for i, diddoc := range dd { 15 | msg, ok := diddoc.(proto.Message) 16 | if !ok { 17 | panic(fmt.Errorf("cannot proto marshal %T", diddoc)) 18 | } 19 | any, err := types.NewAnyWithValue(msg) 20 | if err != nil { 21 | didDocs[i] = any 22 | } 23 | } 24 | 25 | return &GenesisState{ 26 | DidDocs: didDocs, 27 | } 28 | } 29 | 30 | // DefaultGenesisState - Return a default genesis state 31 | func DefaultGenesisState() *GenesisState { 32 | return NewGenesisState(nil) 33 | } 34 | 35 | // ValidateGenesis performs no inspection 36 | func ValidateGenesis(data *GenesisState) error { 37 | return nil 38 | } 39 | 40 | var _ types.UnpackInterfacesMessage = GenesisState{} 41 | 42 | // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces 43 | func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { 44 | for _, genesisDidDoc := range data.DidDocs { 45 | var didDoc exported.DidDoc 46 | err := unpacker.UnpackAny(genesisDidDoc, &didDoc) 47 | if err != nil { 48 | return err 49 | } 50 | } 51 | 52 | return nil 53 | } -------------------------------------------------------------------------------- /x/did/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/stateset/stateset-blockchain/x/did/exported" 4 | 5 | const ( 6 | ModuleName = "did" 7 | StoreKey = ModuleName 8 | RouterKey = ModuleName 9 | QuerierRoute = ModuleName 10 | ) 11 | 12 | var DidKey = []byte{0x01} 13 | 14 | func GetDidPrefixKey(did exported.Did) []byte { 15 | return append(DidKey, []byte(did)...) 16 | } -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/query.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "fmt" 5 | // "strings" 6 | 7 | "github.com/spf13/cobra" 8 | 9 | "github.com/cosmos/cosmos-sdk/client" 10 | // "github.com/cosmos/cosmos-sdk/client/flags" 11 | // sdk "github.com/cosmos/cosmos-sdk/types" 12 | 13 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 14 | ) 15 | 16 | // GetQueryCmd returns the cli query commands for this module 17 | func GetQueryCmd(queryRoute string) *cobra.Command { 18 | // Group ibcdex queries under a subcommand 19 | cmd := &cobra.Command{ 20 | Use: types.ModuleName, 21 | Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), 22 | DisableFlagParsing: true, 23 | SuggestionsMinimumDistance: 2, 24 | RunE: client.ValidateCmd, 25 | } 26 | 27 | // this line is used by starport scaffolding # 1 28 | 29 | cmd.AddCommand(CmdListBuyOrderBook()) 30 | cmd.AddCommand(CmdShowBuyOrderBook()) 31 | 32 | cmd.AddCommand(CmdListSellOrderBook()) 33 | cmd.AddCommand(CmdShowSellOrderBook()) 34 | 35 | return cmd 36 | } 37 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/queryBuyOrderBook.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/cosmos/cosmos-sdk/client" 7 | "github.com/cosmos/cosmos-sdk/client/flags" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | func CmdListBuyOrderBook() *cobra.Command { 13 | cmd := &cobra.Command{ 14 | Use: "list-buyOrderBook", 15 | Short: "list all buyOrderBook", 16 | RunE: func(cmd *cobra.Command, args []string) error { 17 | clientCtx := client.GetClientContextFromCmd(cmd) 18 | 19 | pageReq, err := client.ReadPageRequest(cmd.Flags()) 20 | if err != nil { 21 | return err 22 | } 23 | 24 | queryClient := types.NewQueryClient(clientCtx) 25 | 26 | params := &types.QueryAllBuyOrderBookRequest{ 27 | Pagination: pageReq, 28 | } 29 | 30 | res, err := queryClient.BuyOrderBookAll(context.Background(), params) 31 | if err != nil { 32 | return err 33 | } 34 | 35 | return clientCtx.PrintProto(res) 36 | }, 37 | } 38 | 39 | flags.AddQueryFlagsToCmd(cmd) 40 | 41 | return cmd 42 | } 43 | 44 | func CmdShowBuyOrderBook() *cobra.Command { 45 | cmd := &cobra.Command{ 46 | Use: "show-buyOrderBook [index]", 47 | Short: "shows a buyOrderBook", 48 | Args: cobra.ExactArgs(1), 49 | RunE: func(cmd *cobra.Command, args []string) error { 50 | clientCtx := client.GetClientContextFromCmd(cmd) 51 | 52 | queryClient := types.NewQueryClient(clientCtx) 53 | 54 | params := &types.QueryGetBuyOrderBookRequest{ 55 | Index: args[0], 56 | } 57 | 58 | res, err := queryClient.BuyOrderBook(context.Background(), params) 59 | if err != nil { 60 | return err 61 | } 62 | 63 | return clientCtx.PrintProto(res) 64 | }, 65 | } 66 | 67 | flags.AddQueryFlagsToCmd(cmd) 68 | 69 | return cmd 70 | } 71 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/querySellOrderBook.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/cosmos/cosmos-sdk/client" 7 | "github.com/cosmos/cosmos-sdk/client/flags" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | func CmdListSellOrderBook() *cobra.Command { 13 | cmd := &cobra.Command{ 14 | Use: "list-sellOrderBook", 15 | Short: "list all sellOrderBook", 16 | RunE: func(cmd *cobra.Command, args []string) error { 17 | clientCtx := client.GetClientContextFromCmd(cmd) 18 | 19 | pageReq, err := client.ReadPageRequest(cmd.Flags()) 20 | if err != nil { 21 | return err 22 | } 23 | 24 | queryClient := types.NewQueryClient(clientCtx) 25 | 26 | params := &types.QueryAllSellOrderBookRequest{ 27 | Pagination: pageReq, 28 | } 29 | 30 | res, err := queryClient.SellOrderBookAll(context.Background(), params) 31 | if err != nil { 32 | return err 33 | } 34 | 35 | return clientCtx.PrintProto(res) 36 | }, 37 | } 38 | 39 | flags.AddQueryFlagsToCmd(cmd) 40 | 41 | return cmd 42 | } 43 | 44 | func CmdShowSellOrderBook() *cobra.Command { 45 | cmd := &cobra.Command{ 46 | Use: "show-sellOrderBook [index]", 47 | Short: "shows a sellOrderBook", 48 | Args: cobra.ExactArgs(1), 49 | RunE: func(cmd *cobra.Command, args []string) error { 50 | clientCtx := client.GetClientContextFromCmd(cmd) 51 | 52 | queryClient := types.NewQueryClient(clientCtx) 53 | 54 | params := &types.QueryGetSellOrderBookRequest{ 55 | Index: args[0], 56 | } 57 | 58 | res, err := queryClient.SellOrderBook(context.Background(), params) 59 | if err != nil { 60 | return err 61 | } 62 | 63 | return clientCtx.PrintProto(res) 64 | }, 65 | } 66 | 67 | flags.AddQueryFlagsToCmd(cmd) 68 | 69 | return cmd 70 | } 71 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/tx.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/spf13/cobra" 8 | 9 | "github.com/cosmos/cosmos-sdk/client" 10 | // "github.com/cosmos/cosmos-sdk/client/flags" 11 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 12 | ) 13 | 14 | var ( 15 | DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) 16 | ) 17 | 18 | const ( 19 | flagPacketTimeoutTimestamp = "packet-timeout-timestamp" 20 | ) 21 | 22 | // GetTxCmd returns the transaction commands for this module 23 | func GetTxCmd() *cobra.Command { 24 | cmd := &cobra.Command{ 25 | Use: types.ModuleName, 26 | Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), 27 | DisableFlagParsing: true, 28 | SuggestionsMinimumDistance: 2, 29 | RunE: client.ValidateCmd, 30 | } 31 | 32 | // this line is used by starport scaffolding # 1 33 | cmd.AddCommand(CmdCancelBuyOrder()) 34 | 35 | cmd.AddCommand(CmdCancelSellOrder()) 36 | 37 | cmd.AddCommand(CmdSendBuyOrder()) 38 | 39 | cmd.AddCommand(CmdSendSellOrder()) 40 | 41 | cmd.AddCommand(CmdSendCreatePair()) 42 | 43 | return cmd 44 | } 45 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/txCancelBuyOrder.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/cosmos/cosmos-sdk/client" 9 | "github.com/cosmos/cosmos-sdk/client/flags" 10 | "github.com/cosmos/cosmos-sdk/client/tx" 11 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 12 | ) 13 | 14 | var _ = strconv.Itoa(0) 15 | 16 | func CmdCancelBuyOrder() *cobra.Command { 17 | cmd := &cobra.Command{ 18 | Use: "cancelBuyOrder [port] [channel] [amountDenom] [priceDenom] [orderID]", 19 | Short: "Cancel a buy order", 20 | Args: cobra.ExactArgs(5), 21 | RunE: func(cmd *cobra.Command, args []string) error { 22 | argsPort := string(args[0]) 23 | argsChannel := string(args[1]) 24 | argsAmountDenom := string(args[2]) 25 | argsPriceDenom := string(args[3]) 26 | argsOrderID, _ := strconv.ParseInt(args[4], 10, 64) 27 | 28 | clientCtx, err := client.GetClientTxContext(cmd) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | msg := types.NewMsgCancelBuyOrder(clientCtx.GetFromAddress().String(), string(argsPort), string(argsChannel), string(argsAmountDenom), string(argsPriceDenom), int32(argsOrderID)) 34 | if err := msg.ValidateBasic(); err != nil { 35 | return err 36 | } 37 | return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) 38 | }, 39 | } 40 | 41 | flags.AddTxFlagsToCmd(cmd) 42 | 43 | return cmd 44 | } 45 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/cli/txCancelSellOrder.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/cosmos/cosmos-sdk/client" 9 | "github.com/cosmos/cosmos-sdk/client/flags" 10 | "github.com/cosmos/cosmos-sdk/client/tx" 11 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 12 | ) 13 | 14 | var _ = strconv.Itoa(0) 15 | 16 | func CmdCancelSellOrder() *cobra.Command { 17 | cmd := &cobra.Command{ 18 | Use: "cancelSellOrder [port] [channel] [amountDenom] [priceDenom] [orderID]", 19 | Short: "Cancel a sell order", 20 | Args: cobra.ExactArgs(5), 21 | RunE: func(cmd *cobra.Command, args []string) error { 22 | argsPort := string(args[0]) 23 | argsChannel := string(args[1]) 24 | argsAmountDenom := string(args[2]) 25 | argsPriceDenom := string(args[3]) 26 | argsOrderID, _ := strconv.ParseInt(args[4], 10, 64) 27 | 28 | clientCtx, err := client.GetClientTxContext(cmd) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | msg := types.NewMsgCancelSellOrder(clientCtx.GetFromAddress().String(), string(argsPort), string(argsChannel), string(argsAmountDenom), string(argsPriceDenom), int32(argsOrderID)) 34 | if err := msg.ValidateBasic(); err != nil { 35 | return err 36 | } 37 | return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) 38 | }, 39 | } 40 | 41 | flags.AddTxFlagsToCmd(cmd) 42 | 43 | return cmd 44 | } 45 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/client/rest/rest.go: -------------------------------------------------------------------------------- 1 | package rest 2 | 3 | import ( 4 | "github.com/gorilla/mux" 5 | 6 | "github.com/cosmos/cosmos-sdk/client" 7 | ) 8 | 9 | const ( 10 | MethodGet = "GET" 11 | ) 12 | 13 | func RegisterRoutes(clientCtx client.Context, r *mux.Router) { 14 | } 15 | 16 | func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { 17 | } 18 | 19 | func registerTxHandlers(clientCtx client.Context, r *mux.Router) { 20 | } 21 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/handler.go: -------------------------------------------------------------------------------- 1 | package ibcdex 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 8 | "github.com/stateset/stateset-blockchain//x/ibc/applications/ibcdex/keeper" 9 | "github.com/stateset/stateset-blockchain//x/ibc/applications/ibcdex/types" 10 | ) 11 | 12 | // NewHandler ... 13 | func NewHandler(k keeper.Keeper) sdk.Handler { 14 | msgServer := keeper.NewMsgServerImpl(k) 15 | 16 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 17 | ctx = ctx.WithEventManager(sdk.NewEventManager()) 18 | 19 | switch msg := msg.(type) { 20 | // this line is used by starport scaffolding # 1 21 | case *types.MsgCancelBuyOrder: 22 | res, err := msgServer.CancelBuyOrder(sdk.WrapSDKContext(ctx), msg) 23 | return sdk.WrapServiceResult(ctx, res, err) 24 | 25 | case *types.MsgCancelSellOrder: 26 | res, err := msgServer.CancelSellOrder(sdk.WrapSDKContext(ctx), msg) 27 | return sdk.WrapServiceResult(ctx, res, err) 28 | 29 | case *types.MsgSendBuyOrder: 30 | res, err := msgServer.SendBuyOrder(sdk.WrapSDKContext(ctx), msg) 31 | return sdk.WrapServiceResult(ctx, res, err) 32 | 33 | case *types.MsgSendSellOrder: 34 | res, err := msgServer.SendSellOrder(sdk.WrapSDKContext(ctx), msg) 35 | return sdk.WrapServiceResult(ctx, res, err) 36 | 37 | case *types.MsgSendCreatePair: 38 | res, err := msgServer.SendCreatePair(sdk.WrapSDKContext(ctx), msg) 39 | return sdk.WrapServiceResult(ctx, res, err) 40 | 41 | default: 42 | errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) 43 | return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/buyOrderBook.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/store/prefix" 5 | sdk "github.com/cosmos/cosmos-sdk/types" 6 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 7 | ) 8 | 9 | // SetBuyOrderBook set a specific buyOrderBook in the store from its index 10 | func (k Keeper) SetBuyOrderBook(ctx sdk.Context, buyOrderBook types.BuyOrderBook) { 11 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BuyOrderBookKey)) 12 | b := k.cdc.MustMarshalBinaryBare(&buyOrderBook) 13 | store.Set(types.KeyPrefix(buyOrderBook.Index), b) 14 | } 15 | 16 | // GetBuyOrderBook returns a buyOrderBook from its index 17 | func (k Keeper) GetBuyOrderBook(ctx sdk.Context, index string) (val types.BuyOrderBook, found bool) { 18 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BuyOrderBookKey)) 19 | 20 | b := store.Get(types.KeyPrefix(index)) 21 | if b == nil { 22 | return val, false 23 | } 24 | 25 | k.cdc.MustUnmarshalBinaryBare(b, &val) 26 | return val, true 27 | } 28 | 29 | // DeleteBuyOrderBook removes a buyOrderBook from the store 30 | func (k Keeper) RemoveBuyOrderBook(ctx sdk.Context, index string) { 31 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BuyOrderBookKey)) 32 | store.Delete(types.KeyPrefix(index)) 33 | } 34 | 35 | // GetAllBuyOrderBook returns all buyOrderBook 36 | func (k Keeper) GetAllBuyOrderBook(ctx sdk.Context) (list []types.BuyOrderBook) { 37 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BuyOrderBookKey)) 38 | iterator := sdk.KVStorePrefixIterator(store, []byte{}) 39 | 40 | defer iterator.Close() 41 | 42 | for ; iterator.Valid(); iterator.Next() { 43 | var val types.BuyOrderBook 44 | k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val) 45 | list = append(list, val) 46 | } 47 | 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/grpc_query.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 5 | ) 6 | 7 | var _ types.QueryServer = Keeper{} 8 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/grpc_query_buyOrderBook.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/cosmos/cosmos-sdk/store/prefix" 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/cosmos/cosmos-sdk/types/query" 9 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 10 | "google.golang.org/grpc/codes" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | func (k Keeper) BuyOrderBookAll(c context.Context, req *types.QueryAllBuyOrderBookRequest) (*types.QueryAllBuyOrderBookResponse, error) { 15 | if req == nil { 16 | return nil, status.Error(codes.InvalidArgument, "invalid request") 17 | } 18 | 19 | var buyOrderBooks []*types.BuyOrderBook 20 | ctx := sdk.UnwrapSDKContext(c) 21 | 22 | store := ctx.KVStore(k.storeKey) 23 | buyOrderBookStore := prefix.NewStore(store, types.KeyPrefix(types.BuyOrderBookKey)) 24 | 25 | pageRes, err := query.Paginate(buyOrderBookStore, req.Pagination, func(key []byte, value []byte) error { 26 | var buyOrderBook types.BuyOrderBook 27 | if err := k.cdc.UnmarshalBinaryBare(value, &buyOrderBook); err != nil { 28 | return err 29 | } 30 | 31 | buyOrderBooks = append(buyOrderBooks, &buyOrderBook) 32 | return nil 33 | }) 34 | 35 | if err != nil { 36 | return nil, status.Error(codes.Internal, err.Error()) 37 | } 38 | 39 | return &types.QueryAllBuyOrderBookResponse{BuyOrderBook: buyOrderBooks, Pagination: pageRes}, nil 40 | } 41 | 42 | func (k Keeper) BuyOrderBook(c context.Context, req *types.QueryGetBuyOrderBookRequest) (*types.QueryGetBuyOrderBookResponse, error) { 43 | if req == nil { 44 | return nil, status.Error(codes.InvalidArgument, "invalid request") 45 | } 46 | ctx := sdk.UnwrapSDKContext(c) 47 | 48 | val, found := k.GetBuyOrderBook(ctx, req.Index) 49 | if !found { 50 | return nil, status.Error(codes.InvalidArgument, "not found") 51 | } 52 | 53 | return &types.QueryGetBuyOrderBookResponse{BuyOrderBook: &val}, nil 54 | } 55 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/grpc_query_sellOrderBook.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/cosmos/cosmos-sdk/store/prefix" 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/cosmos/cosmos-sdk/types/query" 9 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 10 | "google.golang.org/grpc/codes" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | func (k Keeper) SellOrderBookAll(c context.Context, req *types.QueryAllSellOrderBookRequest) (*types.QueryAllSellOrderBookResponse, error) { 15 | if req == nil { 16 | return nil, status.Error(codes.InvalidArgument, "invalid request") 17 | } 18 | 19 | var sellOrderBooks []*types.SellOrderBook 20 | ctx := sdk.UnwrapSDKContext(c) 21 | 22 | store := ctx.KVStore(k.storeKey) 23 | sellOrderBookStore := prefix.NewStore(store, types.KeyPrefix(types.SellOrderBookKey)) 24 | 25 | pageRes, err := query.Paginate(sellOrderBookStore, req.Pagination, func(key []byte, value []byte) error { 26 | var sellOrderBook types.SellOrderBook 27 | if err := k.cdc.UnmarshalBinaryBare(value, &sellOrderBook); err != nil { 28 | return err 29 | } 30 | 31 | sellOrderBooks = append(sellOrderBooks, &sellOrderBook) 32 | return nil 33 | }) 34 | 35 | if err != nil { 36 | return nil, status.Error(codes.Internal, err.Error()) 37 | } 38 | 39 | return &types.QueryAllSellOrderBookResponse{SellOrderBook: sellOrderBooks, Pagination: pageRes}, nil 40 | } 41 | 42 | func (k Keeper) SellOrderBook(c context.Context, req *types.QueryGetSellOrderBookRequest) (*types.QueryGetSellOrderBookResponse, error) { 43 | if req == nil { 44 | return nil, status.Error(codes.InvalidArgument, "invalid request") 45 | } 46 | ctx := sdk.UnwrapSDKContext(c) 47 | 48 | val, found := k.GetSellOrderBook(ctx, req.Index) 49 | if !found { 50 | return nil, status.Error(codes.InvalidArgument, "not found") 51 | } 52 | 53 | return &types.QueryGetSellOrderBookResponse{SellOrderBook: &val}, nil 54 | } 55 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/keeper.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/tendermint/tendermint/libs/log" 7 | 8 | "github.com/cosmos/cosmos-sdk/codec" 9 | sdk "github.com/cosmos/cosmos-sdk/types" 10 | capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" 11 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 12 | ) 13 | 14 | type ( 15 | Keeper struct { 16 | cdc codec.Marshaler 17 | storeKey sdk.StoreKey 18 | memKey sdk.StoreKey 19 | channelKeeper types.ChannelKeeper 20 | portKeeper types.PortKeeper 21 | scopedKeeper capabilitykeeper.ScopedKeeper 22 | } 23 | ) 24 | 25 | func NewKeeper( 26 | cdc codec.Marshaler, 27 | storeKey, 28 | memKey sdk.StoreKey, 29 | channelKeeper types.ChannelKeeper, 30 | portKeeper types.PortKeeper, 31 | scopedKeeper capabilitykeeper.ScopedKeeper, 32 | ) *Keeper { 33 | return &Keeper{ 34 | cdc: cdc, 35 | storeKey: storeKey, 36 | memKey: memKey, 37 | channelKeeper: channelKeeper, 38 | portKeeper: portKeeper, 39 | scopedKeeper: scopedKeeper, 40 | } 41 | } 42 | 43 | func (k Keeper) Logger(ctx sdk.Context) log.Logger { 44 | return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) 45 | } 46 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 5 | ) 6 | 7 | type msgServer struct { 8 | Keeper 9 | } 10 | 11 | // NewMsgServerImpl returns an implementation of the MsgServer interface 12 | // for the provided Keeper. 13 | func NewMsgServerImpl(keeper Keeper) types.MsgServer { 14 | return &msgServer{Keeper: keeper} 15 | } 16 | 17 | var _ types.MsgServer = msgServer{} 18 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server_buyOrder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | ) 10 | 11 | func (k msgServer) SendBuyOrder(goCtx context.Context, msg *types.MsgSendBuyOrder) (*types.MsgSendBuyOrderResponse, error) { 12 | ctx := sdk.UnwrapSDKContext(goCtx) 13 | 14 | // TODO: logic before transmitting the packet 15 | 16 | // Construct the packet 17 | var packet types.BuyOrderPacketData 18 | 19 | packet.AmountDenom = msg.AmountDenom 20 | packet.Amount = msg.Amount 21 | packet.PriceDenom = msg.PriceDenom 22 | packet.Price = msg.Price 23 | 24 | // Transmit the packet 25 | err := k.TransmitBuyOrderPacket( 26 | ctx, 27 | packet, 28 | msg.Port, 29 | msg.ChannelID, 30 | clienttypes.ZeroHeight(), 31 | msg.TimeoutTimestamp, 32 | ) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | return &types.MsgSendBuyOrderResponse{}, nil 38 | } 39 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server_cancelBuyOrder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 8 | ) 9 | 10 | func (k msgServer) CancelBuyOrder(goCtx context.Context, msg *types.MsgCancelBuyOrder) (*types.MsgCancelBuyOrderResponse, error) { 11 | ctx := sdk.UnwrapSDKContext(goCtx) 12 | 13 | // TODO: Handling the message 14 | _ = ctx 15 | 16 | return &types.MsgCancelBuyOrderResponse{}, nil 17 | } 18 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server_cancelSellOrder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 8 | ) 9 | 10 | func (k msgServer) CancelSellOrder(goCtx context.Context, msg *types.MsgCancelSellOrder) (*types.MsgCancelSellOrderResponse, error) { 11 | ctx := sdk.UnwrapSDKContext(goCtx) 12 | 13 | // TODO: Handling the message 14 | _ = ctx 15 | 16 | return &types.MsgCancelSellOrderResponse{}, nil 17 | } 18 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server_createPair.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | ) 10 | 11 | func (k msgServer) SendCreatePair(goCtx context.Context, msg *types.MsgSendCreatePair) (*types.MsgSendCreatePairResponse, error) { 12 | ctx := sdk.UnwrapSDKContext(goCtx) 13 | 14 | // TODO: logic before transmitting the packet 15 | 16 | // Construct the packet 17 | var packet types.CreatePairPacketData 18 | 19 | packet.SourceDenom = msg.SourceDenom 20 | packet.TargetDenom = msg.TargetDenom 21 | 22 | // Transmit the packet 23 | err := k.TransmitCreatePairPacket( 24 | ctx, 25 | packet, 26 | msg.Port, 27 | msg.ChannelID, 28 | clienttypes.ZeroHeight(), 29 | msg.TimeoutTimestamp, 30 | ) 31 | if err != nil { 32 | return nil, err 33 | } 34 | 35 | return &types.MsgSendCreatePairResponse{}, nil 36 | } 37 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/msg_server_sellOrder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | ) 10 | 11 | func (k msgServer) SendSellOrder(goCtx context.Context, msg *types.MsgSendSellOrder) (*types.MsgSendSellOrderResponse, error) { 12 | ctx := sdk.UnwrapSDKContext(goCtx) 13 | 14 | // TODO: logic before transmitting the packet 15 | 16 | // Construct the packet 17 | var packet types.SellOrderPacketData 18 | 19 | packet.AmountDenom = msg.AmountDenom 20 | packet.Amount = msg.Amount 21 | packet.PriceDenom = msg.PriceDenom 22 | packet.Price = msg.Price 23 | 24 | // Transmit the packet 25 | err := k.TransmitSellOrderPacket( 26 | ctx, 27 | packet, 28 | msg.Port, 29 | msg.ChannelID, 30 | clienttypes.ZeroHeight(), 31 | msg.TimeoutTimestamp, 32 | ) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | return &types.MsgSendSellOrderResponse{}, nil 38 | } 39 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/query.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | // this line is used by starport scaffolding # 1 5 | "github.com/cosmos/cosmos-sdk/codec" 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 8 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 9 | 10 | abci "github.com/tendermint/tendermint/abci/types" 11 | ) 12 | 13 | func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { 14 | return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { 15 | var ( 16 | res []byte 17 | err error 18 | ) 19 | 20 | switch path[0] { 21 | // this line is used by starport scaffolding # 1 22 | default: 23 | err = sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) 24 | } 25 | 26 | return res, err 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/keeper/sellOrderBook.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/store/prefix" 5 | sdk "github.com/cosmos/cosmos-sdk/types" 6 | "github.com/stateset/stateset-blockchain/x/ibc/applications/ibcdex/types" 7 | ) 8 | 9 | // SetSellOrderBook set a specific sellOrderBook in the store from its index 10 | func (k Keeper) SetSellOrderBook(ctx sdk.Context, sellOrderBook types.SellOrderBook) { 11 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SellOrderBookKey)) 12 | b := k.cdc.MustMarshalBinaryBare(&sellOrderBook) 13 | store.Set(types.KeyPrefix(sellOrderBook.Index), b) 14 | } 15 | 16 | // GetSellOrderBook returns a sellOrderBook from its index 17 | func (k Keeper) GetSellOrderBook(ctx sdk.Context, index string) (val types.SellOrderBook, found bool) { 18 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SellOrderBookKey)) 19 | 20 | b := store.Get(types.KeyPrefix(index)) 21 | if b == nil { 22 | return val, false 23 | } 24 | 25 | k.cdc.MustUnmarshalBinaryBare(b, &val) 26 | return val, true 27 | } 28 | 29 | // DeleteSellOrderBook removes a sellOrderBook from the store 30 | func (k Keeper) RemoveSellOrderBook(ctx sdk.Context, index string) { 31 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SellOrderBookKey)) 32 | store.Delete(types.KeyPrefix(index)) 33 | } 34 | 35 | // GetAllSellOrderBook returns all sellOrderBook 36 | func (k Keeper) GetAllSellOrderBook(ctx sdk.Context) (list []types.SellOrderBook) { 37 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SellOrderBookKey)) 38 | iterator := sdk.KVStorePrefixIterator(store, []byte{}) 39 | 40 | defer iterator.Close() 41 | 42 | for ; iterator.Valid(); iterator.Next() { 43 | var val types.SellOrderBook 44 | k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val) 45 | list = append(list, val) 46 | } 47 | 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/codec.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | cdctypes "github.com/cosmos/cosmos-sdk/codec/types" 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/cosmos/cosmos-sdk/types/msgservice" 8 | ) 9 | 10 | func RegisterCodec(cdc *codec.LegacyAmino) { 11 | cdc.RegisterConcrete(&MsgCancelBuyOrder{}, "ibcdex/CancelBuyOrder", nil) 12 | 13 | cdc.RegisterConcrete(&MsgCancelSellOrder{}, "ibcdex/CancelSellOrder", nil) 14 | 15 | cdc.RegisterConcrete(&MsgSendBuyOrder{}, "ibcdex/SendBuyOrder", nil) 16 | 17 | cdc.RegisterConcrete(&MsgSendSellOrder{}, "ibcdex/SendSellOrder", nil) 18 | 19 | cdc.RegisterConcrete(&MsgSendCreatePair{}, "ibcdex/SendCreatePair", nil) 20 | 21 | } 22 | 23 | func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { 24 | registry.RegisterImplementations((*sdk.Msg)(nil), 25 | &MsgCancelBuyOrder{}, 26 | ) 27 | registry.RegisterImplementations((*sdk.Msg)(nil), 28 | &MsgCancelSellOrder{}, 29 | ) 30 | registry.RegisterImplementations((*sdk.Msg)(nil), 31 | &MsgSendBuyOrder{}, 32 | ) 33 | registry.RegisterImplementations((*sdk.Msg)(nil), 34 | &MsgSendSellOrder{}, 35 | ) 36 | registry.RegisterImplementations((*sdk.Msg)(nil), 37 | &MsgSendCreatePair{}, 38 | ) 39 | 40 | msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) 41 | } 42 | 43 | var ( 44 | amino = codec.NewLegacyAmino() 45 | ModuleCdc = codec.NewAminoCodec(amino) 46 | ) 47 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // DONTCOVER 4 | 5 | import ( 6 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 7 | ) 8 | 9 | // x/ibcdex module sentinel errors 10 | var ( 11 | ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") 12 | ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 1500, "invalid packet timeout") 13 | ErrInvalidVersion = sdkerrors.Register(ModuleName, 1501, "invalid version") 14 | ) 15 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/events_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // IBC events 4 | const ( 5 | EventTypeTimeout = "timeout" 6 | // this line is used by starport scaffolding # ibc/packet/event 7 | EventTypeBuyOrderPacket = "buyOrder_packet" 8 | 9 | EventTypeSellOrderPacket = "sellOrder_packet" 10 | 11 | EventTypeCreatePairPacket = "createPair_packet" 12 | 13 | AttributeKeyAckSuccess = "success" 14 | AttributeKeyAck = "acknowledgement" 15 | AttributeKeyAckError = "error" 16 | ) 17 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" 7 | ) 8 | 9 | // DefaultIndex is the default capability global index 10 | const DefaultIndex uint64 = 1 11 | 12 | // DefaultGenesis returns the default Capability genesis state 13 | func DefaultGenesis() *GenesisState { 14 | return &GenesisState{ 15 | PortId: PortID, 16 | // this line is used by starport scaffolding # genesis/types/default 17 | BuyOrderBookList: []*BuyOrderBook{}, 18 | SellOrderBookList: []*SellOrderBook{}, 19 | } 20 | } 21 | 22 | // Validate performs basic genesis state validation returning an error upon any 23 | // failure. 24 | func (gs GenesisState) Validate() error { 25 | if err := host.PortIdentifierValidator(gs.PortId); err != nil { 26 | return err 27 | } 28 | 29 | // this line is used by starport scaffolding # genesis/types/validate 30 | // Check for duplicated index in buyOrderBook 31 | buyOrderBookIndexMap := make(map[string]bool) 32 | 33 | for _, elem := range gs.BuyOrderBookList { 34 | if _, ok := buyOrderBookIndexMap[elem.Index]; ok { 35 | return fmt.Errorf("duplicated index for buyOrderBook") 36 | } 37 | buyOrderBookIndexMap[elem.Index] = true 38 | } 39 | // Check for duplicated index in sellOrderBook 40 | sellOrderBookIndexMap := make(map[string]bool) 41 | 42 | for _, elem := range gs.SellOrderBookList { 43 | if _, ok := sellOrderBookIndexMap[elem.Index]; ok { 44 | return fmt.Errorf("duplicated index for sellOrderBook") 45 | } 46 | sellOrderBookIndexMap[elem.Index] = true 47 | } 48 | 49 | return nil 50 | } 51 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | const ( 4 | // ModuleName defines the module name 5 | ModuleName = "ibcdex" 6 | 7 | // StoreKey defines the primary module store key 8 | StoreKey = ModuleName 9 | 10 | // RouterKey is the message route for slashing 11 | RouterKey = ModuleName 12 | 13 | // QuerierRoute defines the module's query routing key 14 | QuerierRoute = ModuleName 15 | 16 | // MemStoreKey defines the in-memory store key 17 | MemStoreKey = "mem_capability" 18 | 19 | // Version defines the current version the IBC module supports 20 | Version = "ibcdex-1" 21 | 22 | // PortID is the default port id that module binds to 23 | PortID = "ibcdex" 24 | ) 25 | 26 | var ( 27 | // PortKey defines the key to store the port ID in store 28 | PortKey = KeyPrefix("ibcdex-port-") 29 | ) 30 | 31 | func KeyPrefix(p string) []byte { 32 | return []byte(p) 33 | } 34 | 35 | const ( 36 | SellOrderBookKey = "SellOrderBook-value-" 37 | ) 38 | 39 | const ( 40 | BuyOrderBookKey = "BuyOrderBook-value-" 41 | ) 42 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/message_cancelBuyOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | ) 7 | 8 | var _ sdk.Msg = &MsgCancelBuyOrder{} 9 | 10 | func NewMsgCancelBuyOrder(creator string, port string, channel string, amountDenom string, priceDenom string, orderID int32) *MsgCancelBuyOrder { 11 | return &MsgCancelBuyOrder{ 12 | Creator: creator, 13 | Port: port, 14 | Channel: channel, 15 | AmountDenom: amountDenom, 16 | PriceDenom: priceDenom, 17 | OrderID: orderID, 18 | } 19 | } 20 | 21 | func (msg *MsgCancelBuyOrder) Route() string { 22 | return RouterKey 23 | } 24 | 25 | func (msg *MsgCancelBuyOrder) Type() string { 26 | return "CancelBuyOrder" 27 | } 28 | 29 | func (msg *MsgCancelBuyOrder) GetSigners() []sdk.AccAddress { 30 | creator, err := sdk.AccAddressFromBech32(msg.Creator) 31 | if err != nil { 32 | panic(err) 33 | } 34 | return []sdk.AccAddress{creator} 35 | } 36 | 37 | func (msg *MsgCancelBuyOrder) GetSignBytes() []byte { 38 | bz := ModuleCdc.MustMarshalJSON(msg) 39 | return sdk.MustSortJSON(bz) 40 | } 41 | 42 | func (msg *MsgCancelBuyOrder) ValidateBasic() error { 43 | _, err := sdk.AccAddressFromBech32(msg.Creator) 44 | if err != nil { 45 | return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) 46 | } 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/message_cancelSellOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | ) 7 | 8 | var _ sdk.Msg = &MsgCancelSellOrder{} 9 | 10 | func NewMsgCancelSellOrder(creator string, port string, channel string, amountDenom string, priceDenom string, orderID int32) *MsgCancelSellOrder { 11 | return &MsgCancelSellOrder{ 12 | Creator: creator, 13 | Port: port, 14 | Channel: channel, 15 | AmountDenom: amountDenom, 16 | PriceDenom: priceDenom, 17 | OrderID: orderID, 18 | } 19 | } 20 | 21 | func (msg *MsgCancelSellOrder) Route() string { 22 | return RouterKey 23 | } 24 | 25 | func (msg *MsgCancelSellOrder) Type() string { 26 | return "CancelSellOrder" 27 | } 28 | 29 | func (msg *MsgCancelSellOrder) GetSigners() []sdk.AccAddress { 30 | creator, err := sdk.AccAddressFromBech32(msg.Creator) 31 | if err != nil { 32 | panic(err) 33 | } 34 | return []sdk.AccAddress{creator} 35 | } 36 | 37 | func (msg *MsgCancelSellOrder) GetSignBytes() []byte { 38 | bz := ModuleCdc.MustMarshalJSON(msg) 39 | return sdk.MustSortJSON(bz) 40 | } 41 | 42 | func (msg *MsgCancelSellOrder) ValidateBasic() error { 43 | _, err := sdk.AccAddressFromBech32(msg.Creator) 44 | if err != nil { 45 | return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) 46 | } 47 | return nil 48 | } 49 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/messages_buyOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | ) 7 | 8 | var _ sdk.Msg = &MsgSendBuyOrder{} 9 | 10 | func NewMsgSendBuyOrder( 11 | sender string, 12 | port string, 13 | channelID string, 14 | timeoutTimestamp uint64, 15 | amountDenom string, 16 | amount int32, 17 | priceDenom string, 18 | price int32, 19 | ) *MsgSendBuyOrder { 20 | return &MsgSendBuyOrder{ 21 | Sender: sender, 22 | Port: port, 23 | ChannelID: channelID, 24 | TimeoutTimestamp: timeoutTimestamp, 25 | AmountDenom: amountDenom, 26 | Amount: amount, 27 | PriceDenom: priceDenom, 28 | Price: price, 29 | } 30 | } 31 | 32 | func (msg *MsgSendBuyOrder) Route() string { 33 | return RouterKey 34 | } 35 | 36 | func (msg *MsgSendBuyOrder) Type() string { 37 | return "SendBuyOrder" 38 | } 39 | 40 | func (msg *MsgSendBuyOrder) GetSigners() []sdk.AccAddress { 41 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 42 | if err != nil { 43 | panic(err) 44 | } 45 | return []sdk.AccAddress{sender} 46 | } 47 | 48 | func (msg *MsgSendBuyOrder) GetSignBytes() []byte { 49 | bz := ModuleCdc.MustMarshalJSON(msg) 50 | return sdk.MustSortJSON(bz) 51 | } 52 | 53 | func (msg *MsgSendBuyOrder) ValidateBasic() error { 54 | _, err := sdk.AccAddressFromBech32(msg.Sender) 55 | if err != nil { 56 | return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address (%s)", err) 57 | } 58 | return nil 59 | } 60 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/messages_createPair.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | ) 7 | 8 | var _ sdk.Msg = &MsgSendCreatePair{} 9 | 10 | func NewMsgSendCreatePair( 11 | sender string, 12 | port string, 13 | channelID string, 14 | timeoutTimestamp uint64, 15 | sourceDenom string, 16 | targetDenom string, 17 | ) *MsgSendCreatePair { 18 | return &MsgSendCreatePair{ 19 | Sender: sender, 20 | Port: port, 21 | ChannelID: channelID, 22 | TimeoutTimestamp: timeoutTimestamp, 23 | SourceDenom: sourceDenom, 24 | TargetDenom: targetDenom, 25 | } 26 | } 27 | 28 | func (msg *MsgSendCreatePair) Route() string { 29 | return RouterKey 30 | } 31 | 32 | func (msg *MsgSendCreatePair) Type() string { 33 | return "SendCreatePair" 34 | } 35 | 36 | func (msg *MsgSendCreatePair) GetSigners() []sdk.AccAddress { 37 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 38 | if err != nil { 39 | panic(err) 40 | } 41 | return []sdk.AccAddress{sender} 42 | } 43 | 44 | func (msg *MsgSendCreatePair) GetSignBytes() []byte { 45 | bz := ModuleCdc.MustMarshalJSON(msg) 46 | return sdk.MustSortJSON(bz) 47 | } 48 | 49 | func (msg *MsgSendCreatePair) ValidateBasic() error { 50 | _, err := sdk.AccAddressFromBech32(msg.Sender) 51 | if err != nil { 52 | return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address (%s)", err) 53 | } 54 | return nil 55 | } 56 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/messages_sellOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | ) 7 | 8 | var _ sdk.Msg = &MsgSendSellOrder{} 9 | 10 | func NewMsgSendSellOrder( 11 | sender string, 12 | port string, 13 | channelID string, 14 | timeoutTimestamp uint64, 15 | amountDenom string, 16 | amount int32, 17 | priceDenom string, 18 | price int32, 19 | ) *MsgSendSellOrder { 20 | return &MsgSendSellOrder{ 21 | Sender: sender, 22 | Port: port, 23 | ChannelID: channelID, 24 | TimeoutTimestamp: timeoutTimestamp, 25 | AmountDenom: amountDenom, 26 | Amount: amount, 27 | PriceDenom: priceDenom, 28 | Price: price, 29 | } 30 | } 31 | 32 | func (msg *MsgSendSellOrder) Route() string { 33 | return RouterKey 34 | } 35 | 36 | func (msg *MsgSendSellOrder) Type() string { 37 | return "SendSellOrder" 38 | } 39 | 40 | func (msg *MsgSendSellOrder) GetSigners() []sdk.AccAddress { 41 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 42 | if err != nil { 43 | panic(err) 44 | } 45 | return []sdk.AccAddress{sender} 46 | } 47 | 48 | func (msg *MsgSendSellOrder) GetSignBytes() []byte { 49 | bz := ModuleCdc.MustMarshalJSON(msg) 50 | return sdk.MustSortJSON(bz) 51 | } 52 | 53 | func (msg *MsgSendSellOrder) ValidateBasic() error { 54 | _, err := sdk.AccAddressFromBech32(msg.Sender) 55 | if err != nil { 56 | return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address (%s)", err) 57 | } 58 | return nil 59 | } 60 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/packet_buyOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // ValidateBasic is used for validating the packet 4 | func (p BuyOrderPacketData) ValidateBasic() error { 5 | 6 | // TODO: Validate the packet data 7 | 8 | return nil 9 | } 10 | 11 | // GetBytes is a helper for serialising 12 | func (p BuyOrderPacketData) GetBytes() ([]byte, error) { 13 | var modulePacket IbcdexPacketData 14 | 15 | modulePacket.Packet = &IbcdexPacketData_BuyOrderPacket{&p} 16 | 17 | return modulePacket.Marshal() 18 | } 19 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/packet_createPair.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // ValidateBasic is used for validating the packet 4 | func (p CreatePairPacketData) ValidateBasic() error { 5 | 6 | // TODO: Validate the packet data 7 | 8 | return nil 9 | } 10 | 11 | // GetBytes is a helper for serialising 12 | func (p CreatePairPacketData) GetBytes() ([]byte, error) { 13 | var modulePacket IbcdexPacketData 14 | 15 | modulePacket.Packet = &IbcdexPacketData_CreatePairPacket{&p} 16 | 17 | return modulePacket.Marshal() 18 | } 19 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/packet_sellOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // ValidateBasic is used for validating the packet 4 | func (p SellOrderPacketData) ValidateBasic() error { 5 | 6 | // TODO: Validate the packet data 7 | 8 | return nil 9 | } 10 | 11 | // GetBytes is a helper for serialising 12 | func (p SellOrderPacketData) GetBytes() ([]byte, error) { 13 | var modulePacket IbcdexPacketData 14 | 15 | modulePacket.Packet = &IbcdexPacketData_SellOrderPacket{&p} 16 | 17 | return modulePacket.Marshal() 18 | } 19 | -------------------------------------------------------------------------------- /x/ibc/applications/ibcdex/types/types.go: -------------------------------------------------------------------------------- 1 | package types 2 | -------------------------------------------------------------------------------- /x/ibc/applications/transfer/client/cli/cli.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | 6 | "github.com/cosmos/cosmos-sdk/client" 7 | ) 8 | 9 | // GetQueryCmd returns the query commands for IBC connections 10 | func GetQueryCmd() *cobra.Command { 11 | queryCmd := &cobra.Command{ 12 | Use: "ibc-transfer", 13 | Short: "IBC fungible token transfer query subcommands", 14 | DisableFlagParsing: true, 15 | SuggestionsMinimumDistance: 2, 16 | } 17 | 18 | queryCmd.AddCommand( 19 | GetCmdQueryDenomTrace(), 20 | GetCmdQueryDenomTraces(), 21 | GetCmdParams(), 22 | ) 23 | 24 | return queryCmd 25 | } 26 | 27 | // NewTxCmd returns the transaction commands for IBC fungible token transfer 28 | func NewTxCmd() *cobra.Command { 29 | txCmd := &cobra.Command{ 30 | Use: "ibc-transfer", 31 | Short: "IBC fungible token transfer transaction subcommands", 32 | DisableFlagParsing: true, 33 | SuggestionsMinimumDistance: 2, 34 | RunE: client.ValidateCmd, 35 | } 36 | 37 | txCmd.AddCommand( 38 | NewTransferTxCmd(), 39 | ) 40 | 41 | return txCmd 42 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/handler.go: -------------------------------------------------------------------------------- 1 | package transfer 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" 7 | ) 8 | 9 | // NewHandler returns sdk.Handler for IBC token transfer module messages 10 | func NewHandler(k types.MsgServer) sdk.Handler { 11 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 12 | ctx = ctx.WithEventManager(sdk.NewEventManager()) 13 | 14 | switch msg := msg.(type) { 15 | case *types.MsgTransfer: 16 | res, err := k.Transfer(sdk.WrapSDKContext(ctx), msg) 17 | return sdk.WrapServiceResult(ctx, res, err) 18 | 19 | default: 20 | return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized ICS-20 transfer message type: %T", msg) 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/keeper/encoding.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" 5 | ) 6 | 7 | // UnmarshalDenomTrace attempts to decode and return an DenomTrace object from 8 | // raw encoded bytes. 9 | func (k Keeper) UnmarshalDenomTrace(bz []byte) (types.DenomTrace, error) { 10 | var denomTrace types.DenomTrace 11 | if err := k.cdc.UnmarshalBinaryBare(bz, &denomTrace); err != nil { 12 | return types.DenomTrace{}, err 13 | } 14 | return denomTrace, nil 15 | } 16 | 17 | // MustUnmarshalDenomTrace attempts to decode and return an DenomTrace object from 18 | // raw encoded bytes. It panics on error. 19 | func (k Keeper) MustUnmarshalDenomTrace(bz []byte) types.DenomTrace { 20 | var denomTrace types.DenomTrace 21 | k.cdc.MustUnmarshalBinaryBare(bz, &denomTrace) 22 | return denomTrace 23 | } 24 | 25 | // MarshalDenomTrace attempts to encode an DenomTrace object and returns the 26 | // raw encoded bytes. 27 | func (k Keeper) MarshalDenomTrace(denomTrace types.DenomTrace) ([]byte, error) { 28 | return k.cdc.MarshalBinaryBare(&denomTrace) 29 | } 30 | 31 | // MustMarshalDenomTrace attempts to encode an DenomTrace object and returns the 32 | // raw encoded bytes. It panics on error. 33 | func (k Keeper) MustMarshalDenomTrace(denomTrace types.DenomTrace) []byte { 34 | return k.cdc.MustMarshalBinaryBare(&denomTrace) 35 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/keeper/genesis.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" 8 | ) 9 | 10 | // InitGenesis initializes the ibc-transfer state and binds to PortID. 11 | func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { 12 | k.SetPort(ctx, state.PortId) 13 | 14 | for _, trace := range state.DenomTraces { 15 | k.SetDenomTrace(ctx, trace) 16 | } 17 | 18 | // Only try to bind to port if it is not already bound, since we may already own 19 | // port capability from capability InitGenesis 20 | if !k.IsBound(ctx, state.PortId) { 21 | // transfer module binds to the transfer port on InitChain 22 | // and claims the returned capability 23 | err := k.BindPort(ctx, state.PortId) 24 | if err != nil { 25 | panic(fmt.Sprintf("could not claim port capability: %v", err)) 26 | } 27 | } 28 | 29 | k.SetParams(ctx, state.Params) 30 | 31 | // check if the module account exists 32 | moduleAcc := k.GetTransferAccount(ctx) 33 | if moduleAcc == nil { 34 | panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) 35 | } 36 | } 37 | 38 | // ExportGenesis exports ibc-transfer module's portID and denom trace info into its genesis state. 39 | func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { 40 | return &types.GenesisState{ 41 | PortId: k.GetPort(ctx), 42 | DenomTraces: k.GetAllDenomTraces(ctx), 43 | Params: k.GetParams(ctx), 44 | } 45 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/keeper/msg_server.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" 8 | ) 9 | 10 | var _ types.MsgServer = Keeper{} 11 | 12 | // See createOutgoingPacket in spec:https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#packet-relay 13 | 14 | // Transfer defines a rpc handler method for MsgTransfer. 15 | func (k Keeper) Transfer(goCtx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) { 16 | ctx := sdk.UnwrapSDKContext(goCtx) 17 | 18 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 19 | if err != nil { 20 | return nil, err 21 | } 22 | if err := k.SendTransfer( 23 | ctx, msg.SourcePort, msg.SourceChannel, msg.Token, sender, msg.Receiver, msg.TimeoutHeight, msg.TimeoutTimestamp, 24 | ); err != nil { 25 | return nil, err 26 | } 27 | 28 | k.Logger(ctx).Info("IBC fungible token transfer", "token", msg.Token.Denom, "amount", msg.Token.Amount.String(), "sender", msg.Sender, "receiver", msg.Receiver) 29 | 30 | ctx.EventManager().EmitEvents(sdk.Events{ 31 | sdk.NewEvent( 32 | types.EventTypeTransfer, 33 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 34 | sdk.NewAttribute(types.AttributeKeyReceiver, msg.Receiver), 35 | ), 36 | sdk.NewEvent( 37 | sdk.EventTypeMessage, 38 | sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), 39 | ), 40 | }) 41 | 42 | return &types.MsgTransferResponse{}, nil 43 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/keeper/params.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" 6 | ) 7 | 8 | // GetSendEnabled retrieves the send enabled boolean from the paramstore 9 | func (k Keeper) GetSendEnabled(ctx sdk.Context) bool { 10 | var res bool 11 | k.paramSpace.Get(ctx, types.KeySendEnabled, &res) 12 | return res 13 | } 14 | 15 | // GetReceiveEnabled retrieves the receive enabled boolean from the paramstore 16 | func (k Keeper) GetReceiveEnabled(ctx sdk.Context) bool { 17 | var res bool 18 | k.paramSpace.Get(ctx, types.KeyReceiveEnabled, &res) 19 | return res 20 | } 21 | 22 | // GetParams returns the total set of ibc-transfer parameters. 23 | func (k Keeper) GetParams(ctx sdk.Context) types.Params { 24 | return types.NewParams(k.GetSendEnabled(ctx), k.GetReceiveEnabled(ctx)) 25 | } 26 | 27 | // SetParams sets the total set of ibc-transfer parameters. 28 | func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { 29 | k.paramSpace.SetParamSet(ctx, ¶ms) 30 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/codec.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/cosmos/cosmos-sdk/types/msgservice" 8 | ) 9 | 10 | // RegisterLegacyAminoCodec registers the necessary x/ibc transfer interfaces and concrete types 11 | // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. 12 | func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { 13 | cdc.RegisterConcrete(&MsgTransfer{}, "cosmos-sdk/MsgTransfer", nil) 14 | } 15 | 16 | // RegisterInterfaces register the ibc transfer module interfaces to protobuf 17 | // Any. 18 | func RegisterInterfaces(registry codectypes.InterfaceRegistry) { 19 | registry.RegisterImplementations((*sdk.Msg)(nil), &MsgTransfer{}) 20 | 21 | msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) 22 | } 23 | 24 | var ( 25 | amino = codec.NewLegacyAmino() 26 | 27 | // ModuleCdc references the global x/ibc-transfer module codec. Note, the codec 28 | // should ONLY be used in certain instances of tests and for JSON encoding. 29 | // 30 | // The actual codec used for serialization should be provided to x/ibc transfer and 31 | // defined at the application level. 32 | ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) 33 | 34 | // AminoCdc is a amino codec created to support amino json compatible msgs. 35 | AminoCdc = codec.NewAminoCodec(amino) 36 | ) 37 | 38 | func init() { 39 | RegisterLegacyAminoCodec(amino) 40 | amino.Seal() 41 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 5 | ) 6 | 7 | // IBC channel sentinel errors 8 | var ( 9 | ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 2, "invalid packet timeout") 10 | ErrInvalidDenomForTransfer = sdkerrors.Register(ModuleName, 3, "invalid denomination for cross-chain transfer") 11 | ErrInvalidVersion = sdkerrors.Register(ModuleName, 4, "invalid ICS20 version") 12 | ErrInvalidAmount = sdkerrors.Register(ModuleName, 5, "invalid token amount") 13 | ErrTraceNotFound = sdkerrors.Register(ModuleName, 6, "denomination trace not found") 14 | ErrSendDisabled = sdkerrors.Register(ModuleName, 7, "fungible token transfers from this chain are disabled") 15 | ErrReceiveDisabled = sdkerrors.Register(ModuleName, 8, "fungible token transfers to this chain are disabled") 16 | ErrMaxTransferChannels = sdkerrors.Register(ModuleName, 9, "max transfer channels") 17 | ) -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/events.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // IBC transfer events 4 | const ( 5 | EventTypeTimeout = "timeout" 6 | EventTypePacket = "fungible_token_packet" 7 | EventTypeTransfer = "ibc_transfer" 8 | EventTypeChannelClose = "channel_closed" 9 | EventTypeDenomTrace = "denomination_trace" 10 | 11 | AttributeKeyReceiver = "receiver" 12 | AttributeKeyDenom = "denom" 13 | AttributeKeyAmount = "amount" 14 | AttributeKeyRefundReceiver = "refund_receiver" 15 | AttributeKeyRefundDenom = "refund_denom" 16 | AttributeKeyRefundAmount = "refund_amount" 17 | AttributeKeyAckSuccess = "success" 18 | AttributeKeyAck = "acknowledgement" 19 | AttributeKeyAckError = "error" 20 | AttributeKeyTraceHash = "trace_hash" 21 | ) -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" 5 | ) 6 | 7 | // NewGenesisState creates a new ibc-transfer GenesisState instance. 8 | func NewGenesisState(portID string, denomTraces Traces, params Params) *GenesisState { 9 | return &GenesisState{ 10 | PortId: portID, 11 | DenomTraces: denomTraces, 12 | Params: params, 13 | } 14 | } 15 | 16 | // DefaultGenesisState returns a GenesisState with "transfer" as the default PortID. 17 | func DefaultGenesisState() *GenesisState { 18 | return &GenesisState{ 19 | PortId: PortID, 20 | DenomTraces: Traces{}, 21 | Params: DefaultParams(), 22 | } 23 | } 24 | 25 | // Validate performs basic genesis state validation returning an error upon any 26 | // failure. 27 | func (gs GenesisState) Validate() error { 28 | if err := host.PortIdentifierValidator(gs.PortId); err != nil { 29 | return err 30 | } 31 | if err := gs.DenomTraces.Validate(); err != nil { 32 | return err 33 | } 34 | return gs.Params.Validate() 35 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | ) 9 | 10 | const ( 11 | // ModuleName defines the IBC transfer name 12 | ModuleName = "transfer" 13 | 14 | // Version defines the current version the IBC tranfer 15 | // module supports 16 | Version = "ics20-1" 17 | 18 | // PortID is the default port id that transfer module binds to 19 | PortID = "transfer" 20 | 21 | // StoreKey is the store key string for IBC transfer 22 | StoreKey = ModuleName 23 | 24 | // RouterKey is the message route for IBC transfer 25 | RouterKey = ModuleName 26 | 27 | // QuerierRoute is the querier route for IBC transfer 28 | QuerierRoute = ModuleName 29 | 30 | // DenomPrefix is the prefix used for internal SDK coin representation. 31 | DenomPrefix = "ibc" 32 | ) 33 | 34 | var ( 35 | // PortKey defines the key to store the port ID in store 36 | PortKey = []byte{0x01} 37 | // DenomTraceKey defines the key to store the denomination trace info in store 38 | DenomTraceKey = []byte{0x02} 39 | ) 40 | 41 | // GetEscrowAddress returns the escrow address for the specified channel. 42 | // The escrow address follows the format as outlined in ADR 028: 43 | // https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-028-public-key-addresses.md 44 | func GetEscrowAddress(portID, channelID string) sdk.AccAddress { 45 | // a slash is used to create domain separation between port and channel identifiers to 46 | // prevent address collisions between escrow addresses created for different channels 47 | contents := fmt.Sprintf("%s/%s", portID, channelID) 48 | 49 | // ADR 028 AddressHash construction 50 | preImage := []byte(Version) 51 | preImage = append(preImage, 0) 52 | preImage = append(preImage, contents...) 53 | hash := sha256.Sum256(preImage) 54 | return hash[:20] 55 | } -------------------------------------------------------------------------------- /x/ibc/applications/transfer/types/params.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" 7 | ) 8 | 9 | const ( 10 | // DefaultSendEnabled enabled 11 | DefaultSendEnabled = true 12 | // DefaultReceiveEnabled enabled 13 | DefaultReceiveEnabled = true 14 | ) 15 | 16 | var ( 17 | // KeySendEnabled is store's key for SendEnabled Params 18 | KeySendEnabled = []byte("SendEnabled") 19 | // KeyReceiveEnabled is store's key for ReceiveEnabled Params 20 | KeyReceiveEnabled = []byte("ReceiveEnabled") 21 | ) 22 | 23 | // ParamKeyTable type declaration for parameters 24 | func ParamKeyTable() paramtypes.KeyTable { 25 | return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) 26 | } 27 | 28 | // NewParams creates a new parameter configuration for the ibc transfer module 29 | func NewParams(enableSend, enableReceive bool) Params { 30 | return Params{ 31 | SendEnabled: enableSend, 32 | ReceiveEnabled: enableReceive, 33 | } 34 | } 35 | 36 | // DefaultParams is the default parameter configuration for the ibc-transfer module 37 | func DefaultParams() Params { 38 | return NewParams(DefaultSendEnabled, DefaultReceiveEnabled) 39 | } 40 | 41 | // Validate all ibc-transfer module parameters 42 | func (p Params) Validate() error { 43 | if err := validateEnabled(p.SendEnabled); err != nil { 44 | return err 45 | } 46 | 47 | return validateEnabled(p.ReceiveEnabled) 48 | } 49 | 50 | // ParamSetPairs implements params.ParamSet 51 | func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { 52 | return paramtypes.ParamSetPairs{ 53 | paramtypes.NewParamSetPair(KeySendEnabled, p.SendEnabled, validateEnabled), 54 | paramtypes.NewParamSetPair(KeyReceiveEnabled, p.ReceiveEnabled, validateEnabled), 55 | } 56 | } 57 | 58 | func validateEnabled(i interface{}) error { 59 | _, ok := i.(bool) 60 | if !ok { 61 | return fmt.Errorf("invalid parameter type: %T", i) 62 | } 63 | 64 | return nil 65 | } -------------------------------------------------------------------------------- /x/ibc/core/genesis.go: -------------------------------------------------------------------------------- 1 | package ibc 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | client "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client" 6 | connection "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection" 7 | channel "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel" 8 | "github.com/cosmos/cosmos-sdk/x/ibc/core/keeper" 9 | "github.com/cosmos/cosmos-sdk/x/ibc/core/types" 10 | ) 11 | 12 | // InitGenesis initializes the ibc state from a provided genesis 13 | // state. 14 | func InitGenesis(ctx sdk.Context, k keeper.Keeper, createLocalhost bool, gs *types.GenesisState) { 15 | client.InitGenesis(ctx, k.ClientKeeper, gs.ClientGenesis) 16 | connection.InitGenesis(ctx, k.ConnectionKeeper, gs.ConnectionGenesis) 17 | channel.InitGenesis(ctx, k.ChannelKeeper, gs.ChannelGenesis) 18 | } 19 | 20 | // ExportGenesis returns the ibc exported genesis. 21 | func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { 22 | return &types.GenesisState{ 23 | ClientGenesis: client.ExportGenesis(ctx, k.ClientKeeper), 24 | ConnectionGenesis: connection.ExportGenesis(ctx, k.ConnectionKeeper), 25 | ChannelGenesis: channel.ExportGenesis(ctx, k.ChannelKeeper), 26 | } 27 | } -------------------------------------------------------------------------------- /x/ibc/core/types/codec.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 5 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 6 | connectiontypes "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types" 7 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 8 | commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types" 9 | solomachinetypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/06-solomachine/types" 10 | ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types" 11 | localhosttypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/09-localhost/types" 12 | ) 13 | 14 | // RegisterInterfaces registers x/ibc interfaces into protobuf Any. 15 | func RegisterInterfaces(registry codectypes.InterfaceRegistry) { 16 | clienttypes.RegisterInterfaces(registry) 17 | connectiontypes.RegisterInterfaces(registry) 18 | channeltypes.RegisterInterfaces(registry) 19 | solomachinetypes.RegisterInterfaces(registry) 20 | ibctmtypes.RegisterInterfaces(registry) 21 | localhosttypes.RegisterInterfaces(registry) 22 | commitmenttypes.RegisterInterfaces(registry) 23 | } -------------------------------------------------------------------------------- /x/ibc/core/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 5 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 6 | connectiontypes "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types" 7 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 8 | ) 9 | 10 | var _ codectypes.UnpackInterfacesMessage = GenesisState{} 11 | 12 | // DefaultGenesisState returns the ibc module's default genesis state. 13 | func DefaultGenesisState() *GenesisState { 14 | return &GenesisState{ 15 | ClientGenesis: clienttypes.DefaultGenesisState(), 16 | ConnectionGenesis: connectiontypes.DefaultGenesisState(), 17 | ChannelGenesis: channeltypes.DefaultGenesisState(), 18 | } 19 | } 20 | 21 | // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces 22 | func (gs GenesisState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { 23 | return gs.ClientGenesis.UnpackInterfaces(unpacker) 24 | } 25 | 26 | // Validate performs basic genesis state validation returning an error upon any 27 | // failure. 28 | func (gs *GenesisState) Validate() error { 29 | if err := gs.ClientGenesis.Validate(); err != nil { 30 | return err 31 | } 32 | 33 | if err := gs.ConnectionGenesis.Validate(); err != nil { 34 | return err 35 | } 36 | 37 | return gs.ChannelGenesis.Validate() 38 | } -------------------------------------------------------------------------------- /x/ibc/core/types/query.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/gogo/protobuf/grpc" 5 | 6 | client "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | connection "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection" 9 | connectiontypes "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types" 10 | channel "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel" 11 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 12 | ) 13 | 14 | // QueryServer defines the IBC interfaces that the gRPC query server must implement 15 | type QueryServer interface { 16 | clienttypes.QueryServer 17 | connectiontypes.QueryServer 18 | channeltypes.QueryServer 19 | } 20 | 21 | // RegisterQueryService registers each individual IBC submodule query service 22 | func RegisterQueryService(server grpc.Server, queryService QueryServer) { 23 | client.RegisterQueryService(server, queryService) 24 | connection.RegisterQueryService(server, queryService) 25 | channel.RegisterQueryService(server, queryService) 26 | } -------------------------------------------------------------------------------- /x/invoice/genesis.go: -------------------------------------------------------------------------------- 1 | package invoice 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/invoice/keeper" 8 | "github.com/stateset/stateset-blockchain/x/invoice/types" 9 | ) 10 | 11 | // GenesisState defines genesis data for the module 12 | type GenesisState struct { 13 | Invoices []Invoice `json:"invoices"` 14 | Params Params `json:"params"` 15 | } 16 | 17 | // NewGenesisState creates a new genesis state. 18 | func NewGenesisState() GenesisState { 19 | return GenesisState{ 20 | Invoices: nil, 21 | Params: DefaultParams(), 22 | } 23 | } 24 | 25 | // DefaultGenesisState returns a default genesis state 26 | func DefaultGenesisState() GenesisState { return NewGenesisState() } 27 | 28 | // InitGenesis initializes stateset from genesis file 29 | func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { 30 | for _, c := range data.Invoices { 31 | k.setInvoices(ctx, c) 32 | k.setInvoiceAgreement(ctx, c.AgreementID, c.InvoiceID) 33 | } 34 | k.setInvoiceID(ctx, uint64(len(data.Invoices)+1)) 35 | k.SetParams(ctx, data.Params) 36 | } 37 | 38 | // ExportGenesis exports the genesis state 39 | func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { 40 | return GenesisState{ 41 | Invoices: k.Invoices(ctx), 42 | Params: k.GetParams(ctx), 43 | } 44 | } 45 | 46 | // ValidateGenesis validates the genesis state data 47 | func ValidateGenesis(data GenesisState) error { 48 | if data.Params.MinInvoiceLength < 1 { 49 | return fmt.Errorf("Param: MinInvoiceLength must have a positive value") 50 | } 51 | if data.Params.MaxInvoiceLength < 1 { 52 | return fmt.Errorf("Param: MaxInvoiceLength must have a positive value") 53 | } 54 | 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /x/invoice/handler/handler.go: -------------------------------------------------------------------------------- 1 | package invoice 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | "github.com/stateset/stateset-blockchain/x/invoice/keeper" 7 | "github.com/stateset/stateset-blockchain/x/invoice/types" 8 | ) 9 | 10 | 11 | // NewHandler returns a handler for "invoice" type messages. 12 | func NewHandler(k keeper.Keeper) sdk.Handler { 13 | msgServer := keeper.NewMsgServerImpl(k) 14 | 15 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 16 | ctx = ctx.WithEventManager(sdk.NewEventManager()) 17 | 18 | switch msg := msg.(type) { 19 | case *types.MsgCreateInvoice: 20 | res, err := msgServer.CreateInvoice(sdk.WrapSDKContext(ctx), msg) 21 | return sdk.WrapServiceResult(ctx, res, err) 22 | 23 | case *types.MsgEditInvoice: 24 | res, err := msgServer.EditInvoice(sdk.WrapSDKContext(ctx), msg) 25 | return sdk.WrapServiceResult(ctx, res, err) 26 | 27 | case *types.MsgDeleteInvoice: 28 | res, err := msgServer.DeleteInvoice(sdk.WrapSDKContext(ctx), msg) 29 | return sdk.WrapServiceResult(ctx, res, err) 30 | 31 | case *types.MsgCompleteInvoice: 32 | res, err := msgServer.CancelInvoice(sdk.WrapSDKContext(ctx), msg) 33 | return sdk.WrapServiceResult(ctx, res, err) 34 | 35 | case *types.MsgCancelInvoice: 36 | res, err := msgServer.CancelInvoice(sdk.WrapSDKContext(ctx), msg) 37 | return sdk.WrapServiceResult(ctx, res, err) 38 | 39 | case *types.MsgLockInvoice: 40 | res, err := msgServer.LockInvoice(sdk.WrapSDKContext(ctx), msg) 41 | return sdk.WrapServiceResult(ctx, res, err) 42 | 43 | case *types.MsgFactorInvoice: 44 | res, err := msgServer.FactorInvoice(sdk.WrapSDKContext(ctx), msg) 45 | return sdk.WrapServiceResult(ctx, res, err) 46 | 47 | default: 48 | return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /x/invoice/keeper/grpc_query.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/invoice/types" 5 | ) 6 | 7 | var _ types.QueryServer = Keeper{} 8 | -------------------------------------------------------------------------------- /x/invoice/keeper/grpc_query_invoice.go: -------------------------------------------------------------------------------- 1 | package invoice 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/cosmos/cosmos-sdk/store/prefix" 7 | sdk "github.com/cosmos/cosmos-sdk/types" 8 | "github.com/cosmos/cosmos-sdk/types/query" 9 | "github.com/stateset/stateset-blockchain/x/invoice/types" 10 | "google.golang.org/grpc/codes" 11 | "google.golang.org/grpc/status" 12 | ) 13 | 14 | func (k Keeper) InvoiceAll(c context.Context, req *types.QueryAllInvoiceRequest) (*types.QueryAllInvoiceResponse, error) { 15 | if req == nil { 16 | return nil, status.Error(codes.InvalidArgument, "invalid request") 17 | } 18 | 19 | var invoices []*types.Invoice 20 | ctx := sdk.UnwrapSDKContext(c) 21 | 22 | store := ctx.KVStore(k.storeKey) 23 | invoiceStore := prefix.NewStore(store, types.KeyPrefix(types.InvoiceKey)) 24 | 25 | pageRes, err := query.Paginate(invoiceStore, req.Pagination, func(key []byte, value []byte) error { 26 | var invoice types.Invoice 27 | if err := k.cdc.UnmarshalBinaryBare(value, &invoice); err != nil { 28 | return err 29 | } 30 | 31 | invoices = append(invoices, &invoice) 32 | return nil 33 | }) 34 | 35 | if err != nil { 36 | return nil, status.Error(codes.Internal, err.Error()) 37 | } 38 | 39 | return &types.QueryAllInvoiceResponse{Invoice: invoices, Pagination: pageRes}, nil 40 | } 41 | 42 | func (k Keeper) Invoice(c context.Context, req *types.QueryGetInvoiceRequest) (*types.QueryGetInvoiceResponse, error) { 43 | if req == nil { 44 | return nil, status.Error(codes.InvalidArgument, "invalid request") 45 | } 46 | 47 | var invoice types.Invoice 48 | ctx := sdk.UnwrapSDKContext(c) 49 | 50 | store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.InvoiceKey)) 51 | k.cdc.MustUnmarshalBinaryBare(store.Get(types.KeyPrefix(types.InvoiceKey + req.Id)), &invoice) 52 | 53 | return &types.QueryGetInvoiceResponse{Invoice: &invoice}, nil 54 | } 55 | -------------------------------------------------------------------------------- /x/invoice/keeper/msg_server_cancel_invoice.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/invoice/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | 13 | 14 | // Cancel Invoice 15 | func (server msgServer) CancelInvoice(goCtx context.Context, msg *types.MsgCancelInvoice) (*types.MsgCancelInvoiceResponse, error) { 16 | ctx := sdk.UnwrapSDKContext(goCtx) 17 | 18 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | err = server.keeper.CancelInvoice(ctx, sender, msg.InvoiceId, msg.amount) 24 | if err != nil { 25 | return nil, err 26 | } 27 | 28 | // Burn a NFT that represents the Invoice DID and Value of the Invoice 29 | k.bankKeeper.BurnCoins(ctx, did) 30 | 31 | invoice, found := k.GetInvoice(ctx, msg.Id) 32 | invoice.InvoiceStatus = "cancelled" 33 | 34 | ctx.EventManager().EmitEvents(sdk.Events{ 35 | sdk.NewEvent( 36 | types.TypeEvtInvoiceCanceld, 37 | sdk.NewAttribute(types.AttributeKeyInvoiceId, strconv.FormatUint(msg.InvoiceId, 10)), 38 | ), 39 | sdk.NewEvent( 40 | sdk.EventTypeMessage, 41 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 42 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 43 | ), 44 | }) 45 | 46 | return &types.MsgCancelInvoiceResponse{}, nil 47 | } -------------------------------------------------------------------------------- /x/invoice/keeper/msg_server_create_invoice.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/invoice/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | 13 | // Create Invoice 14 | func (server msgServer) CreateInvoice(goCtx context.Context, msg *types.MsgCreateInvoice) (*types.MsgCreateInvoiceResponse, error) { 15 | ctx := sdk.UnwrapSDKContext(goCtx) 16 | 17 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 18 | if err != nil { 19 | return nil, err 20 | } 21 | 22 | invoiceId, err := server.keeper.CreateInvoice(ctx, sender, msg.InvoiceParams, msg.InvoiceAssets) 23 | if err != nil { 24 | return nil, err 25 | } 26 | 27 | invoice, found := k.GetInvoice(ctx, msg.Id) 28 | invoice.InvoiceStatus = "created" 29 | 30 | // Verify the Value of the Invoice from existing system 31 | k.zkpKeeper.VerifyProof(ctx, invoice) 32 | 33 | // Add a DID to represent the Invoice in the Cosmosverse DID:STATESET:INV:123 34 | k.didKeeper.AddDID(ctx, invoicehash) 35 | 36 | // Mint a NFT that represents the Invoice DID and Value of the Invoice 37 | k.nftKeeper.MintCoins(ctx, did) 38 | 39 | ctx.EventManager().EmitEvents(sdk.Events{ 40 | sdk.NewEvent( 41 | types.TypeEvtInvoiceCreated, 42 | sdk.NewAttribute(types.AttributeKeyInvoiceId, strconv.FormatUint(purchaseOrderId, 10)), 43 | ), 44 | sdk.NewEvent( 45 | sdk.EventTypeMessage, 46 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 47 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 48 | ), 49 | }) 50 | 51 | return &types.MsgCreateInvoiceResponse{}, nil 52 | } -------------------------------------------------------------------------------- /x/invoice/keeper/msg_server_factor_invoice.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/invoice/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | // Factor Invoice 13 | func (server msgServer) FactorInvoice(goCtx context.Context, msg *types.MsgFactorInvoice) (*types.MsgFactorInvoiceResponse, error) { 14 | ctx := sdk.UnwrapSDKContext(goCtx) 15 | 16 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 17 | if err != nil { 18 | return nil, err 19 | } 20 | 21 | err = server.keeper.FactorInvoice(ctx, sender, msg.InvoiceId, msg.Amount) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | invoice, found := k.GetInvoice(ctx, msg.Id) 27 | invoice.InvoiceStatus = "factored" 28 | 29 | ctx.EventManager().EmitEvents(sdk.Events{ 30 | sdk.NewEvent( 31 | types.TypeEvtInvoiceFactored, 32 | sdk.NewAttribute(types.AttributeKeyInvoiceId, strconv.FormatUint(msg.InvoiceId, 10)), 33 | ), 34 | sdk.NewEvent( 35 | sdk.EventTypeMessage, 36 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 37 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 38 | ), 39 | }) 40 | 41 | return &types.MsgFinanceInvoiceResponse{}, nil 42 | } -------------------------------------------------------------------------------- /x/invoice/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // DONTCOVER 4 | 5 | import ( 6 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 7 | ) 8 | 9 | // x/invoice module sentinel errors 10 | var ( 11 | ErrInvoiceNotFound = sdkerrors.Register(ModuleName, 1, "invoice not found") 12 | ErrInvoiceAlreadyExist = sdkerrors.Register(ModuleName, 2, "invoice already exist") 13 | ErrInvoiceLocked = sdkerrors.Register(ModuleName, 3, "invoice is locked") 14 | ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 4, "invalid packet timeout") 15 | ErrInvalidVersion = sdkerrors.Register(ModuleName, 5, "invalid version") 16 | ) 17 | -------------------------------------------------------------------------------- /x/invoice/types/events.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // event types 4 | const ( 5 | TypeEvtInvoiceCreated = "invoice_created" 6 | TypeEvtInvoiceUpdated = "invoice_updated" 7 | TypeEvtInvoiceDeleted = "invoice_deleted" 8 | TypeEvtInvoiceCompleted = "invoice_completed" 9 | TypeEvtInvoiceDeleted = "invoice_deleted" 10 | TypeEvtInvoiceCanceled = "invoice_canceled" 11 | TypeEvtInvoiceLocked = "invoice_locked" 12 | TypeEvtInvoiceFactored = "invoice_factored" 13 | TypeEvtInvoicePaid = "invoice_paid" 14 | 15 | 16 | AttributeValueCategory = ModuleName 17 | AttributeKeyInvoiceId = "invoice_id" 18 | AttributeKeySwapFee = "swap_fee" 19 | AttributeKeyTokensIn = "tokens_in" 20 | AttributeKeyTokensOut = "tokens_out" 21 | ) -------------------------------------------------------------------------------- /x/invoice/types/events_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // Stateset Invoice IBC events 4 | const ( 5 | EventTypeTimeout = "timeout" 6 | EventTypeIbcPurchaseOrderPacket = "ibcInvoice_packet" 7 | 8 | AttributeKeyAckSuccess = "success" 9 | AttributeKeyAck = "acknowledgement" 10 | AttributeKeyAckError = "error" 11 | ) 12 | -------------------------------------------------------------------------------- /x/invoice/types/expected_keeper_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" 6 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 7 | ibcexported "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" 8 | ) 9 | 10 | // ChannelKeeper defines the expected IBC channel keeper 11 | type ChannelKeeper interface { 12 | GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) 13 | GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) 14 | SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error 15 | ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error 16 | } 17 | 18 | // PortKeeper defines the expected IBC port keeper 19 | type PortKeeper interface { 20 | BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability 21 | } 22 | 23 | // ScopedKeeper defines the expected IBC scoped keeper 24 | type ScopedKeeper interface { 25 | GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) 26 | AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool 27 | ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error 28 | } 29 | -------------------------------------------------------------------------------- /x/invoice/types/keys.go: -------------------------------------------------------------------------------- 1 | package invoice 2 | 3 | import ( 4 | "time" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | ) 8 | 9 | // Keys for invoice store 10 | // Items are stored with the following key: values 11 | // 12 | // - 0x00: Invoice_Bytes 13 | // - 0x01: nextInvoiceID_Bytes 14 | // 15 | // - 0x11: invoiceID_Bytes 16 | // - 0x12: invoiceID_Bytes 17 | var ( 18 | InvoicesKeyPrefix = []byte{0x00} 19 | InvoiceIDKey = []byte{0x01} 20 | CreatedTimeInvoicesPrefix = []byte{0x12} 21 | ) 22 | 23 | // key for getting a specific invoice from the store 24 | func key(invoiceID uint64) []byte { 25 | bz := sdk.Uint64ToBigEndian(invoiceID) 26 | return append(InvoicesKeyPrefix, bz...) 27 | } 28 | 29 | func createdTimeInvoicesKey(createdTime time.Time) []byte { 30 | return append(CreatedTimeInvoicesPrefix, sdk.FormatTimeBytes(createdTime)...) 31 | } 32 | 33 | func createdTimeInvoiceKey(createdTime time.Time, invoiceID uint64) []byte { 34 | bz := sdk.Uint64ToBigEndian(invoiceID) 35 | return append(createdTimeInvoicesKey(createdTime), bz...) 36 | } -------------------------------------------------------------------------------- /x/purchaseorder/genesis.go: -------------------------------------------------------------------------------- 1 | package purchaseorder 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | "github.com/stateset/stateset-blockchain/x/purchaseorder/keeper" 8 | "github.com/stateset/stateset-blockchain/x/purchaseorder/types" 9 | ) 10 | 11 | // DefaultGenesis returns the default Capability genesis state 12 | func DefaultGenesis() *GenesisState { 13 | return &GenesisState{ 14 | PurchaseOrderList: []*PurchaseOrder{}, 15 | } 16 | } 17 | 18 | 19 | func (gs GenesisState) Validate() error { 20 | 21 | purchaseOrderIdMap := make(map[uint64]bool) 22 | 23 | for _, elem := range gs.PurchaseOrderList { 24 | if _, ok := purchaseOrderIdMap[elem.Id]; ok { 25 | return fmt.Errorf("duplicated id for po") 26 | } 27 | purchaseOrderIdMap[elem.Id] = true 28 | } 29 | 30 | return nil 31 | } 32 | 33 | // ExportGenesis returns the capability module's exported genesis. 34 | func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { 35 | genesis := types.DefaultGenesis() 36 | 37 | // this line is used by starport scaffolding # genesis/module/export 38 | 39 | genesis.PortId = k.GetPort(ctx) 40 | 41 | return genesis 42 | } -------------------------------------------------------------------------------- /x/purchaseorder/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 6 | "github.com/stateset/stateset-blockchain/x/purchaseorder/keeper" 7 | "github.com/stateset/stateset-blockchain/x/purchaseorder/types" 8 | ) 9 | 10 | 11 | // NewHandler returns a handler for "purchaseorder" type messages. 12 | func NewHandler(k keeper.Keeper) sdk.Handler { 13 | msgServer := keeper.NewMsgServerImpl(k) 14 | 15 | return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { 16 | ctx = ctx.WithEventManager(sdk.NewEventManager()) 17 | 18 | switch msg := msg.(type) { 19 | case *types.MsgCreatePurchaseOrder: 20 | res, err := msgServer.Create(sdk.WrapSDKContext(ctx), msg) 21 | return sdk.WrapServiceResult(ctx, res, err) 22 | 23 | case *types.MsgUpdatePurchaseOrder: 24 | res, err := msgServer.Update(sdk.WrapSDKContext(ctx), msg) 25 | return sdk.WrapServiceResult(ctx, res, err) 26 | 27 | case *types.MsgDeletePurchaseOrder: 28 | res, err := msgServer.Delete(sdk.WrapSDKContext(ctx), msg) 29 | return sdk.WrapServiceResult(ctx, res, err) 30 | 31 | case *types.MsgCompletePurchaseOrder: 32 | res, err := msgServer.Complete(sdk.WrapSDKContext(ctx), msg) 33 | return sdk.WrapServiceResult(ctx, res, err) 34 | 35 | case *types.MsgCancelPurchaseOrder: 36 | res, err := msgServer.Cancel(sdk.WrapSDKContext(ctx), msg) 37 | return sdk.WrapServiceResult(ctx, res, err) 38 | 39 | case *types.MsgLockPurchaseOrder: 40 | res, err := msgServer.Lock(sdk.WrapSDKContext(ctx), msg) 41 | return sdk.WrapServiceResult(ctx, res, err) 42 | 43 | case *types.MsgFinancePurchaseOrder: 44 | res, err := msgServer.Finance(sdk.WrapSDKContext(ctx), msg) 45 | return sdk.WrapServiceResult(ctx, res, err) 46 | 47 | default: 48 | return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /x/purchaseorder/keeper/grpc_query.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/purchaseorder/types" 5 | ) 6 | 7 | var _ types.QueryServer = Keeper{} 8 | -------------------------------------------------------------------------------- /x/purchaseorder/keeper/keeper.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/tendermint/tendermint/libs/log" 7 | 8 | "github.com/cosmos/cosmos-sdk/codec" 9 | sdk "github.com/cosmos/cosmos-sdk/types" 10 | "github.com/stateset/stateset-blockchain/x/purchaseorder/types" 11 | ) 12 | 13 | type ( 14 | Keeper struct { 15 | cdc codec.Marshaler 16 | storeKey sdk.StoreKey 17 | memKey sdk.StoreKey 18 | 19 | paramSpace paramtypes.Subspace 20 | hooks types.PurchaseOrderHooks 21 | 22 | // keepers 23 | accountKeeper types.AccountKeeper 24 | bankKeeper types.BankKeeper 25 | 26 | channelKeeper types.ChannelKeeper 27 | portKeeper types.PortKeeper 28 | scopedKeeper types.ScopedKeeper 29 | } 30 | ) 31 | 32 | func NewKeeper( 33 | cdc codec.Marshaler, 34 | storeKey, 35 | memKey sdk.StoreKey, 36 | channelKeeper types.ChannelKeeper, 37 | portKeeper types.PortKeeper, 38 | scopedKeeper types.ScopedKeeper, 39 | ) *Keeper { 40 | return &Keeper{ 41 | cdc: cdc, 42 | storeKey: storeKey, 43 | memKey: memKey, 44 | channelKeeper: channelKeeper, 45 | portKeeper: portKeeper, 46 | scopedKeeper: scopedKeeper, 47 | } 48 | } 49 | 50 | 51 | func (k *Keeper) createFinanceEvent(ctx sdk.Context, sender sdk.AccAddress, purchaseOrderId uint64, input sdk.Coins) { 52 | ctx.EventManager().EmitEvents(sdk.Events{ 53 | sdk.NewEvent( 54 | types.TypeEvtPurchaseOrderFinanced, 55 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 56 | sdk.NewAttribute(sdk.AttributeKeySender, sender.String()), 57 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(purchaseOrderId, 10)), 58 | sdk.NewAttribute(types.AttributeKeyTokensIn, input.String()), 59 | ), 60 | }) 61 | } 62 | 63 | func (k Keeper) Logger(ctx sdk.Context) log.Logger { 64 | return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) 65 | } 66 | -------------------------------------------------------------------------------- /x/purchaseorder/keeper/msg_server_cancel_purchaseorder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/loan/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (server msgServer) CancelPurchaseOrder(goCtx context.Context, msg *types.MsgCancelPurchaseOrder) (*types.MsgCancelPurchaseOrderResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | err = server.keeper.CompletePurchaseOrder(ctx, sender, msg.PurchaseOrderId, msg.amount) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | purchaseorder, found := k.GetPurchaseOrder(ctx, msg.Id) 26 | purchaseorder.PurchaseOrderStatus = "cancelled" 27 | 28 | // Burn a NFT that represents the Purchase Order DID and Value of the PO 29 | k.bankKeeper.BurnCoins(ctx, purchaseorder, 1) 30 | 31 | ctx.EventManager().EmitEvents(sdk.Events{ 32 | sdk.NewEvent( 33 | types.TypeEvtPurchaseOrderCancelled, 34 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(msg.PurchaseOrderId, 10)), 35 | ), 36 | sdk.NewEvent( 37 | sdk.EventTypeMessage, 38 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 39 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 40 | ), 41 | }) 42 | 43 | return &types.MsgCancelPurchaseOrderResponse{}, nil 44 | } -------------------------------------------------------------------------------- /x/purchaseorder/keeper/msg_server_complete_purchaseorder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/loan/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (server msgServer) CompletePurchaseOrder(goCtx context.Context, msg *types.MsgCompletePurchaseOrder) (*types.MsgCompletePurchaseOrderResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | err = server.keeper.CompletePurchaseOrder(ctx, sender, msg.PurchaseOrderId, msg.amount) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | purchaseorder, found := k.GetPurchaseOrder(ctx, msg.Id) 26 | purchaseorder.PurchaseOrderStatus = "completed" 27 | 28 | ctx.EventManager().EmitEvents(sdk.Events{ 29 | sdk.NewEvent( 30 | types.TypeEvtPurchaseOrderCompleted, 31 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(msg.PurchaseOrderId, 10)), 32 | ), 33 | sdk.NewEvent( 34 | sdk.EventTypeMessage, 35 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 36 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 37 | ), 38 | }) 39 | 40 | return &types.MsgCompletePurchaseOrderResponse{}, nil 41 | } -------------------------------------------------------------------------------- /x/purchaseorder/keeper/msg_server_create_purchaseorder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/stateset/stateset-blockchain/x/loan/types" 8 | sdk "github.com/cosmos/cosmos-sdk/types" 9 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 10 | ) 11 | 12 | func (server msgServer) CreatePurchaseOrder(goCtx context.Context, msg *types.MsgCreatePurchaseOrder) (*types.MsgCreatePurchaseOrderResponse, error) { 13 | ctx := sdk.UnwrapSDKContext(goCtx) 14 | 15 | sender, err := sdk.AccAddressFromBech32(msg.Sender) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | poolId, err := server.keeper.CreatePurchaseOrder(ctx, sender, msg.PurchaseOrderParams, msg.PurchaseOrderAssets) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | purchaseorder, found := k.GetPurchaseOrder(ctx, msg.Id) 26 | purchaseorder.PurchaseOrderStatus = "created" 27 | 28 | // Verify the Value of the Purchase Order from existing system 29 | // k.zkpKeeper.VerifyProof(ctx, purchaseorder) 30 | 31 | // Add a DID to represent the Purchase Order in the Cosmosverse DID:STATESET:PO:123 32 | k.didKeeper.AddDID(ctx, purchaseorderhash) 33 | 34 | // Mint a NFT that represents the Purchase Order DID and Value of the PO 35 | k.bankKeeper.MintCoins(ctx, purchaseorder, 1) 36 | 37 | ctx.EventManager().EmitEvents(sdk.Events{ 38 | sdk.NewEvent( 39 | types.TypeEvtPurchaseOrderCreated, 40 | sdk.NewAttribute(types.AttributeKeyPurchaseOrderId, strconv.FormatUint(purchaseOrderId, 10)), 41 | ), 42 | sdk.NewEvent( 43 | sdk.EventTypeMessage, 44 | sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), 45 | sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), 46 | ), 47 | }) 48 | 49 | return &types.MsgCreatePurchaseOrderResponse{}, nil 50 | } -------------------------------------------------------------------------------- /x/purchaseorder/keeper/msg_server_ibcPurchaseOrder.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "context" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" 8 | "github.com/stateset/stateset-blockchain/x/purchaseorder/types" 9 | ) 10 | 11 | func (k msgServer) SendIbcPurchaseOrder(goCtx context.Context, msg *types.MsgSendIbcPurchaseOrder) (*types.MsgSendIbcPurchaseOrderResponse, error) { 12 | ctx := sdk.UnwrapSDKContext(goCtx) 13 | 14 | var packet types.IbcPurchaseOrderPacketData 15 | 16 | packet.PurchaseOrderID = msg.purchaseOrderID 17 | packet.PurchaseOrderNumber = msg.purchaseOrderNumber 18 | packet.PurchaseOrderName = msg.purchaseOrderName 19 | packet.PurchaseOrderStatus = msg.purchaseOrderStatus 20 | packet.Description = msg.description 21 | packet.PurchaseDate = msg.purchaseDate 22 | packet.DeliveryDate = msg.deliveryDate 23 | packet.Subtotal = msg.subtotal 24 | packet.Total = msg.total 25 | packet.Purchaser = msg.purchaser 26 | packet.Vendor = msg.vendor 27 | packet.Fulfiller = msg.fulfiller 28 | packet.Financer = msg.financer 29 | 30 | // Transmit the packet 31 | err := k.TransmitIbcPurchaseOrderPacket( 32 | ctx, 33 | packet, 34 | msg.Port, 35 | msg.ChannelID, 36 | clienttypes.ZeroHeight(), 37 | msg.TimeoutTimestamp, 38 | ) 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | return &types.MsgSendIbcPurchaseOrderResponse{}, nil 44 | } 45 | -------------------------------------------------------------------------------- /x/purchaseorder/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // DONTCOVER 4 | 5 | import ( 6 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 7 | ) 8 | 9 | // x/purchase order module sentinel errors 10 | var ( 11 | ErrPurchaseOrderNotFound = sdkerrors.Register(ModuleName, 1, "purchase order not found") 12 | ErrPurchaseOrderAlreadyExist = sdkerrors.Register(ModuleName, 2, "purchase order already exist") 13 | ErrPurchaseOrderLocked = sdkerrors.Register(ModuleName, 3, "purchase order is locked") 14 | ErrInvalidPacketTimeout = sdkerrors.Register(ModuleName, 4, "invalid packet timeout") 15 | ErrInvalidVersion = sdkerrors.Register(ModuleName, 5, "invalid version") 16 | ErrWrongPurchaseOrderState = sdkerrors.Register(ModuleName, 6, "invalide purchase order state") 17 | ) 18 | -------------------------------------------------------------------------------- /x/purchaseorder/types/events.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // event types 4 | const ( 5 | TypeEvtPurchaseOrderCreated = "purchase_order_created" 6 | TypeEvtPurchaseOrderUpdated = "purchase_order_updated" 7 | TypeEvtPurchaseOrderDeleted = "purchase_order_deleted" 8 | TypeEvtPurchaseOrderCompleted = "purchase_order_completed" 9 | TypeEvtPurchaseOrderDeleted = "purchase_order_deleted" 10 | TypeEvtPurchaseOrderCanceled = "purchase_order_canceled" 11 | TypeEvtPurchaseOrderLocked = "purchase_order_locked" 12 | TypeEvtPurchaseOrderFinanced = "purchase_order_financed" 13 | 14 | AttributeValueCategory = ModuleName 15 | AttributeKeyPurchaseOrderId = "purchase_order_id" 16 | AttributeKeySwapFee = "swap_fee" 17 | AttributeKeyTokensIn = "tokens_in" 18 | AttributeKeyTokensOut = "tokens_out" 19 | ) -------------------------------------------------------------------------------- /x/purchaseorder/types/events_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // Stateset Purchase Order IBC events 4 | const ( 5 | EventTypeTimeout = "timeout" 6 | EventTypeIbcPurchaseOrderPacket = "ibcPurchaseOrder_packet" 7 | 8 | AttributeKeyAckSuccess = "success" 9 | AttributeKeyAck = "acknowledgement" 10 | AttributeKeyAckError = "error" 11 | ) 12 | -------------------------------------------------------------------------------- /x/purchaseorder/types/expected_keeper_ibc.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" 6 | channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" 7 | ibcexported "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" 8 | ) 9 | 10 | // ChannelKeeper defines the expected IBC channel keeper 11 | type ChannelKeeper interface { 12 | GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) 13 | GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) 14 | SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error 15 | ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error 16 | } 17 | 18 | // PortKeeper defines the expected IBC port keeper 19 | type PortKeeper interface { 20 | BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability 21 | } 22 | 23 | // ScopedKeeper defines the expected IBC scoped keeper 24 | type ScopedKeeper interface { 25 | GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) 26 | AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool 27 | ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error 28 | } 29 | -------------------------------------------------------------------------------- /x/purchaseorder/types/genesis.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host" 7 | codectypes "github.com/cosmos/cosmos-sdk/codec/types" 8 | ) 9 | 10 | // DefaultIndex is the default capability global index 11 | const DefaultIndex uint64 = 1 12 | 13 | // DefaultGenesis returns the default Capability genesis state 14 | func DefaultGenesis() *GenesisState { 15 | return &GenesisState{ 16 | PortId: PortID, 17 | PurchaseOrders: []*codectypes:Any{}, 18 | Params: DefaultParams(), 19 | TimedoutPurchaseOrderList: []*TimedoutPurchaseOrder{}, 20 | SentPurchaseOrderList: []*SentPurchaseOrder{}, 21 | } 22 | } 23 | 24 | // Validate performs basic genesis state validation returning an error upon any 25 | // failure. 26 | func (gs GenesisState) Validate() error { 27 | if err := host.PortIdentifierValidator(gs.PortId); err != nil { 28 | return err 29 | } 30 | 31 | // this line is used by starport scaffolding # genesis/types/validate 32 | // Check for duplicated ID in timedoutPurchaseOrder 33 | timedoutPurchaseOrderIdMap := make(map[uint64]bool) 34 | 35 | for _, elem := range gs.TimedoutPurchaseOrderList { 36 | if _, ok := timedoutPurchaseOrderIdMap[elem.Id]; ok { 37 | return fmt.Errorf("duplicated id for timedoutPurchaseOrder") 38 | } 39 | timedoutPurchaseOrderIdMap[elem.Id] = true 40 | } 41 | // Check for duplicated ID in sentPurchaseOrder 42 | sentPurchaseOrderIdMap := make(map[uint64]bool) 43 | 44 | for _, elem := range gs.SentPurchaseOrderList { 45 | if _, ok := sentPurchaseOrderIdMap[elem.Id]; ok { 46 | return fmt.Errorf("duplicated id for sentPurchaseOrder") 47 | } 48 | sentPurchaseOrderIdMap[elem.Id] = true 49 | } 50 | 51 | return nil 52 | } 53 | -------------------------------------------------------------------------------- /x/purchaseorder/types/key.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | ) 8 | 9 | const ( 10 | ModuleName = "purchaseorder" 11 | 12 | StoreKey = ModuleName 13 | 14 | RouterKey = ModuleName 15 | 16 | QuerierRoute = ModuleName 17 | ) 18 | 19 | var ( 20 | // KeyNextGlobalPurchaseOrderNumber defines key to store the next Purchase Order ID to be used 21 | KeyNextGlobalPurchaseOrderNumber = []byte{0x01} 22 | // KeyPrefixPurchasOrders defines prefix to store purchaseorders 23 | KeyPrefixPurchaseOrders = []byte{0x02} 24 | // KeyTotalLiquidity defines key to store total liquidity 25 | KeyTotalLiquidity = []byte{0x03} 26 | ) 27 | 28 | func GetPurchaseOrderShareDenom(purchaseOrderId uint64) string { 29 | return fmt.Sprintf("purchaseorder/%d", purchaseOrderId) 30 | } 31 | 32 | func GetKeyPrefixPurchaseOrders(purchaseOrderId uint64) []byte { 33 | return append(KeyPrefixPurchaseOrders, sdk.Uint64ToBigEndian(purchaseOrderId)...) 34 | } -------------------------------------------------------------------------------- /x/purchaseorder/types/packet_ibcPurchaseOrder.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | // ValidateBasic is used for validating the packet 4 | func (p IbcPurchaseOrderPacketData) ValidateBasic() error { 5 | 6 | // TODO: Validate the packet data 7 | 8 | return nil 9 | } 10 | 11 | // GetBytes is a helper for serialising 12 | func (p IbcPurchaseOrderPacketData) GetBytes() ([]byte, error) { 13 | var modulePacket PurchaseorderPacketData 14 | 15 | modulePacket.Packet = &PurchaseorderPacketData_IbcPurchaseOrderPacket{&p} 16 | 17 | return modulePacket.Marshal() 18 | } 19 | -------------------------------------------------------------------------------- /x/wasm/abci.go: -------------------------------------------------------------------------------- 1 | package wasm 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | 6 | core "github.com/stateset/stateset-blockchain/types" 7 | "github.com/stateset/stateset-blockchain/x/wasm/internal/keeper" 8 | ) 9 | 10 | // BeginBlocker handles softfork over param changes 11 | func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { 12 | if core.IsSoftforkHeight(ctx, 1) { 13 | params := k.GetParams(ctx) 14 | params.MaxContractMsgSize = 4096 15 | k.SetParams(ctx, params) 16 | } 17 | } -------------------------------------------------------------------------------- /x/wasm/config/toml.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "bytes" 5 | "text/template" 6 | 7 | "github.com/spf13/viper" 8 | tmos "github.com/tendermint/tendermint/libs/os" 9 | ) 10 | 11 | const defaultConfigTemplate = `# This is a TOML config file. 12 | # For more information, see https://github.com/toml-lang/toml 13 | ##### main base config options ##### 14 | # The maximum gas amount can be spent for contract query. 15 | # The contract query will invoke contract execution vm, 16 | # so we need to restrict the max usage to prevent DoS attack 17 | contract-query-gas-limit = "{{ .BaseConfig.ContractQueryGasLimit }}" 18 | # Only The logs from the contracts listed in this array 19 | # are stored in the local storage. To keep all logs, 20 | # a node operator can set "*" (not recommended). 21 | contract-logging-whitelist = "{{ .BaseConfig.ContractLoggingWhitelist }}" 22 | ` 23 | 24 | var configTemplate *template.Template 25 | 26 | func init() { 27 | var err error 28 | tmpl := template.New("wasmConfigFileTemplate") 29 | if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { 30 | panic(err) 31 | } 32 | } 33 | 34 | // ParseConfig retrieves the default environment configuration for the 35 | // application. 36 | func ParseConfig() (*Config, error) { 37 | conf := DefaultConfig() 38 | err := viper.Unmarshal(conf) 39 | return conf, err 40 | } 41 | 42 | // WriteConfigFile renders config using the template and writes it to 43 | // configFilePath. 44 | func WriteConfigFile(configFilePath string, config *Config) { 45 | var buffer bytes.Buffer 46 | 47 | if err := configTemplate.Execute(&buffer, config); err != nil { 48 | panic(err) 49 | } 50 | 51 | tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) 52 | } -------------------------------------------------------------------------------- /x/wasm/exported/alias.go: -------------------------------------------------------------------------------- 1 | // nolint 2 | package exported 3 | 4 | import "github.com/stateset/stateset-blockchain/x/wasm/internal/types" 5 | 6 | var ( 7 | EncodeSdkCoin = types.EncodeSdkCoin 8 | EncodeSdkCoins = types.EncodeSdkCoins 9 | ParseToCoin = types.ParseToCoin 10 | ParseToCoins = types.ParseToCoins 11 | 12 | ErrInvalidMsg = types.ErrInvalidMsg 13 | ) 14 | 15 | type ( 16 | WasmMsgParserInterface = types.WasmMsgParserInterface 17 | WasmQuerierInterface = types.WasmQuerierInterface 18 | MsgInstantiateContract = types.MsgInstantiateContract 19 | MsgExecuteContract = types.MsgExecuteContract 20 | MsgStoreCode = types.MsgStoreCode 21 | ) -------------------------------------------------------------------------------- /x/wasm/internal/keeper/connector.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "github.com/stateset/stateset-blockchain/x/auth/ante" 5 | 6 | sdk "github.com/cosmos/cosmos-sdk/types" 7 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 8 | cosmosante "github.com/cosmos/cosmos-sdk/x/auth/ante" 9 | ) 10 | 11 | func (k Keeper) dispatchMessages(ctx sdk.Context, contractAddr sdk.AccAddress, msgs []wasmTypes.CosmosMsg) error { 12 | var sdkMsgs []sdk.Msg 13 | for _, msg := range msgs { 14 | 15 | msgs, err := k.msgParser.Parse(contractAddr, msg) 16 | if err != nil { 17 | return err 18 | } 19 | 20 | sdkMsgs = append(sdkMsgs, msgs...) 21 | } 22 | 23 | // Charge tax on result msg 24 | taxes := ante.FilterMsgAndComputeTax(ctx, k.treasuryKeeper, sdkMsgs) 25 | if !taxes.IsZero() { 26 | contractAcc := k.accountKeeper.GetAccount(ctx, contractAddr) 27 | if err := cosmosante.DeductFees(k.supplyKeeper, ctx, contractAcc, taxes); err != nil { 28 | return err 29 | } 30 | } 31 | 32 | for _, sdkMsg := range sdkMsgs { 33 | if err := k.handleSdkMessage(ctx, contractAddr, sdkMsg); err != nil { 34 | return err 35 | } 36 | } 37 | 38 | return nil 39 | } 40 | 41 | func (k Keeper) handleSdkMessage(ctx sdk.Context, contractAddr sdk.AccAddress, msg sdk.Msg) error { 42 | // make sure this account can send it 43 | for _, acct := range msg.GetSigners() { 44 | if !acct.Equals(contractAddr) { 45 | return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") 46 | } 47 | } 48 | 49 | // find the handler and execute it 50 | h := k.router.Route(ctx, msg.Route()) 51 | if h == nil { 52 | return sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, msg.Route()) 53 | } 54 | 55 | res, err := h(ctx, msg) 56 | if err != nil { 57 | return err 58 | } 59 | 60 | // redispatch all events, (type sdk.EventTypeMessage will be filtered out in the handler) 61 | ctx.EventManager().EmitEvents(res.Events) 62 | 63 | return nil 64 | } 65 | -------------------------------------------------------------------------------- /x/wasm/internal/keeper/ioutil.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | "io" 7 | "io/ioutil" 8 | 9 | sdk "github.com/cosmos/cosmos-sdk/types" 10 | ) 11 | 12 | var gzipIdent = []byte("\x1F\x8B\x08") 13 | 14 | // uncompress returns gzip uncompressed content or given src when not gzip. 15 | func (k Keeper) uncompress(ctx sdk.Context, src []byte) ([]byte, error) { 16 | if len(src) < 3 { 17 | return src, nil 18 | } 19 | 20 | if !bytes.Equal(gzipIdent, src[0:3]) { 21 | return src, nil 22 | } 23 | 24 | zr, err := gzip.NewReader(bytes.NewReader(src)) 25 | if err != nil { 26 | return nil, err 27 | } 28 | zr.Multistream(false) 29 | 30 | return ioutil.ReadAll(io.LimitReader(zr, int64(k.MaxContractSize(ctx)))) 31 | } 32 | -------------------------------------------------------------------------------- /x/wasm/internal/keeper/params.go: -------------------------------------------------------------------------------- 1 | package keeper 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | "github.com/stateset/stateset-blockchain/x/wasm/internal/types" 6 | ) 7 | 8 | // MaxContractSize defines maximum bytes size of a contract 9 | func (k Keeper) MaxContractSize(ctx sdk.Context) (res uint64) { 10 | k.paramSpace.Get(ctx, types.ParamStoreKeyMaxContractSize, &res) 11 | return 12 | } 13 | 14 | // MaxContractGas defines allowed maximum gas usage per each contract execution 15 | func (k Keeper) MaxContractGas(ctx sdk.Context) (res uint64) { 16 | k.paramSpace.Get(ctx, types.ParamStoreKeyMaxContractGas, &res) 17 | return 18 | } 19 | 20 | // MaxContractMsgSize defines maximum bytes size of a contract 21 | func (k Keeper) MaxContractMsgSize(ctx sdk.Context) (res uint64) { 22 | k.paramSpace.Get(ctx, types.ParamStoreKeyMaxContractMsgSize, &res) 23 | return 24 | } 25 | 26 | // GetParams returns the total set of oracle parameters. 27 | func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { 28 | k.paramSpace.GetParamSet(ctx, ¶ms) 29 | return params 30 | } 31 | 32 | // SetParams sets the total set of oracle parameters. 33 | func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { 34 | k.paramSpace.SetParamSet(ctx, ¶ms) 35 | } -------------------------------------------------------------------------------- /x/wasm/internal/types/codec.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/cosmos/cosmos-sdk/codec" 5 | ) 6 | 7 | // RegisterCodec registers the wasm types and interface 8 | func RegisterCodec(cdc *codec.LegacyAmino) { 9 | cdc.RegisterConcrete(MsgStoreCode{}, "wasm/MsgStoreCode", nil) 10 | cdc.RegisterConcrete(MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) 11 | cdc.RegisterConcrete(MsgExecuteContract{}, "wasm/MsgExecuteContract", nil) 12 | cdc.RegisterConcrete(MsgMigrateContract{}, "wasm/MsgMigrateContract", nil) 13 | cdc.RegisterConcrete(MsgUpdateContractOwner{}, "wasm/MsgUpdateContractOwner", nil) 14 | } 15 | 16 | // ModuleCdc generic sealed codec to be used throughout module 17 | var ModuleCdc *codec.LegacyAmino 18 | 19 | func init() { 20 | cdc := codec.New() 21 | RegisterCodec(cdc) 22 | codec.RegisterCrypto(cdc) 23 | ModuleCdc = cdc.Seal() 24 | } -------------------------------------------------------------------------------- /x/wasm/internal/types/errors.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 5 | ) 6 | 7 | // Wasm Errors 8 | var ( 9 | ErrInternal = sdkerrors.Register(ModuleName, 1, "internal error") 10 | ErrAccountExists = sdkerrors.Register(ModuleName, 2, "contract account already exists") 11 | ErrInstantiateFailed = sdkerrors.Register(ModuleName, 3, "instantiate wasm contract failed") 12 | ErrExecuteFailed = sdkerrors.Register(ModuleName, 4, "execute wasm contract failed") 13 | ErrGasLimit = sdkerrors.Register(ModuleName, 5, "insufficient gas") 14 | ErrInvalidGenesis = sdkerrors.Register(ModuleName, 6, "invalid genesis") 15 | ErrNotFound = sdkerrors.Register(ModuleName, 7, "not found") 16 | ErrInvalidMsg = sdkerrors.Register(ModuleName, 8, "invalid Msg from the contract") 17 | ErrNoRegisteredQuerier = sdkerrors.Register(ModuleName, 9, "failed to find querier for route") 18 | ErrNoRegisteredParser = sdkerrors.Register(ModuleName, 10, "failed to find parser for route") 19 | ErrMigrationFailed = sdkerrors.Register(ModuleName, 11, "migrate wasm contract failed") 20 | ErrNotMigratable = sdkerrors.Register(ModuleName, 12, "the contract is not migratable ") 21 | ErrStoreCodeFailed = sdkerrors.Register(ModuleName, 13, "store wasm contract failed") 22 | ErrContractQueryFailed = sdkerrors.Register(ModuleName, 14, "contract query failed") 23 | ) -------------------------------------------------------------------------------- /x/wasm/internal/types/events.go: -------------------------------------------------------------------------------- 1 | 2 | // noalias 3 | package types 4 | 5 | // Wasm module event types 6 | const ( 7 | EventTypeStoreCode = "store_code" 8 | EventTypeInstantiateContract = "instantiate_contract" 9 | EventTypeExecuteContract = "execute_contract" 10 | EventTypeMigrateContract = "migrate_contract" 11 | EventTypeUpdateContractOwner = "update_contract_owner" 12 | EventTypeFromContract = "from_contract" 13 | 14 | AttributeKeySender = "sender" 15 | AttributeKeyCodeID = "code_id" 16 | AttributeKeyContractAddress = "contract_address" 17 | AttributeKeyContractID = "contract_id" 18 | AttributeKeyOwner = "owner" 19 | 20 | AttributeValueCategory = ModuleName 21 | ) -------------------------------------------------------------------------------- /x/wasm/internal/types/expected_keeper.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | ) 6 | 7 | // AccountKeeper - expected account keeper 8 | type AccountKeeper interface { 9 | NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authexported.Account 10 | GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account 11 | SetAccount(ctx sdk.Context, acc authexported.Account) 12 | } 13 | 14 | // BankKeeper - expected bank keeper 15 | type BankKeeper interface { 16 | SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error 17 | } 18 | 19 | // Treasurykeeper for tax charging & recording 20 | type TreasuryKeeper interface { 21 | RecordEpochTaxProceeds(ctx sdk.Context, delta sdk.Coins) 22 | GetTaxRate(ctx sdk.Context) (taxRate sdk.Dec) 23 | GetTaxCap(ctx sdk.Context, denom string) (taxCap sdk.Int) 24 | } 25 | 26 | // SupplyKeeper defines the expected supply Keeper (noalias) 27 | type SupplyKeeper interface { 28 | SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error 29 | GetModuleAccount(ctx sdk.Context, moduleName string) supplyexported.ModuleAccountI 30 | GetModuleAddress(moduleName string) sdk.AccAddress 31 | } 32 | -------------------------------------------------------------------------------- /x/wasm/internal/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | sdk "github.com/cosmos/cosmos-sdk/types" 5 | ) 6 | 7 | const ( 8 | // ModuleName is the name of the contract module 9 | ModuleName = "wasm" 10 | 11 | // StoreKey is the string store representation 12 | StoreKey = ModuleName 13 | 14 | // TStoreKey is the string transient store representation 15 | TStoreKey = "transient_" + ModuleName 16 | 17 | // QuerierRoute is the querier route for the staking module 18 | QuerierRoute = ModuleName 19 | 20 | // RouterKey is the msg router key for the staking module 21 | RouterKey = ModuleName 22 | ) 23 | 24 | // Keys for wasm store 25 | // Items are stored with the following key: values 26 | // 27 | // - 0x01: uint64 28 | // 29 | // - 0x02: uint64 30 | // 31 | // - 0x03: CodeInfo 32 | // 33 | // - 0x04: ContractInfo 34 | // 35 | // - 0x05: KVStore for contract 36 | var ( 37 | LastCodeIDKey = []byte{0x01} 38 | LastInstanceIDKey = []byte{0x02} 39 | CodeKey = []byte{0x03} 40 | ContractInfoKey = []byte{0x04} 41 | ContractStoreKey = []byte{0x05} 42 | ) 43 | 44 | // GetCodeInfoKey constructs the key of the WASM code info for the ID 45 | func GetCodeInfoKey(codeID uint64) []byte { 46 | contractIDBz := sdk.Uint64ToBigEndian(codeID) 47 | return append(CodeKey, contractIDBz...) 48 | } 49 | 50 | // GetContractInfoKey returns the key of the WASM contract info for the contract address 51 | func GetContractInfoKey(addr sdk.AccAddress) []byte { 52 | return append(ContractInfoKey, addr...) 53 | } 54 | 55 | // GetContractStoreKey returns the store prefix for the WASM contract store 56 | func GetContractStoreKey(addr sdk.AccAddress) []byte { 57 | return append(ContractStoreKey, addr...) 58 | } -------------------------------------------------------------------------------- /x/wasm/rest/rest.go: -------------------------------------------------------------------------------- 1 | package rest 2 | 3 | import ( 4 | "github.com/gorilla/mux" 5 | 6 | 7 | ) 8 | 9 | const ( 10 | RestCodeID = "code_id" 11 | RestContractAddress = "contract_address" 12 | ) 13 | 14 | // RegisterRoutes registers staking-related REST handlers to a router 15 | func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { 16 | registerQueryRoutes(cliCtx, r) 17 | registerTxRoutes(cliCtx, r) 18 | } -------------------------------------------------------------------------------- /x/wasm/utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | "encoding/binary" 7 | ) 8 | 9 | var ( 10 | gzipIdent = []byte("\x1F\x8B\x08") 11 | wasmIdent = []byte("\x00\x61\x73\x6D") 12 | ) 13 | 14 | // IsGzip returns checks if the file contents are gzip compressed 15 | func IsGzip(input []byte) bool { 16 | return bytes.Equal(input[:3], gzipIdent) 17 | } 18 | 19 | // IsWasm checks if the file contents are of wasm binary 20 | func IsWasm(input []byte) bool { 21 | return bytes.Equal(input[:4], wasmIdent) 22 | } 23 | 24 | // GzipIt compresses the input ([]byte) 25 | func GzipIt(input []byte) ([]byte, error) { 26 | // Create gzip writer. 27 | var b bytes.Buffer 28 | w := gzip.NewWriter(&b) 29 | _, err := w.Write(input) 30 | if err != nil { 31 | return nil, err 32 | } 33 | err = w.Close() // You must close this first to flush the bytes to the buffer. 34 | if err != nil { 35 | return nil, err 36 | } 37 | 38 | return b.Bytes(), nil 39 | } 40 | 41 | //EncodeKey encode given key with prefix of key's length 42 | func EncodeKey(key string) []byte { 43 | keyLength := uint64(len(key)) 44 | keyBz := make([]byte, 2, 2+keyLength) 45 | 46 | bz := make([]byte, 8) 47 | binary.LittleEndian.PutUint64(bz, keyLength) 48 | 49 | keyBz[0] = bz[1] 50 | keyBz[1] = bz[0] 51 | 52 | keyBz = append(keyBz, []byte(key)...) 53 | 54 | return keyBz 55 | } --------------------------------------------------------------------------------