Skip to content

Commit

Permalink
Add new wasmx module, update proto
Browse files Browse the repository at this point in the history
  • Loading branch information
nhannamsiu committed May 31, 2022
1 parent 67eda2d commit e26db47
Show file tree
Hide file tree
Showing 17 changed files with 3,347 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,8 @@ copy-chain-types:
rm -rf chain/oracle/types/*test.go rm -rf chain/oracle/types/*gw.go
cp ../injective-core/injective-chain/modules/peggy/types/*.go chain/peggy/types
rm -rf chain/peggy/types/*test.go rm -rf chain/peggy/types/*gw.go
cp ../injective-core/injective-chain/modules/wasmx/types/*.go chain/wasmx/types
rm -rf chain/wasmx/types/*test.go rm -rf chain/wasmx/types/*gw.go

echo "👉 Replace injective-core/injective-chain/modules with sdk-go/chain"
echo "👉 Replace injective-core/injective-chain/types with sdk-go/chain/types"
103 changes: 103 additions & 0 deletions chain/exchange/types/wasm_trade_summary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package types

import (
"bytes"
"sort"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
)

type MarketSummary struct {
TotalUserQuantity sdk.Dec
TotalContractQuantity sdk.Dec
TotalUserMargin sdk.Dec
TotalContractMargin sdk.Dec
netQuantity sdk.Dec
}

func NewMarketSummary() *MarketSummary {
return &MarketSummary{
TotalUserQuantity: sdk.ZeroDec(),
TotalContractQuantity: sdk.ZeroDec(),
TotalUserMargin: sdk.ZeroDec(),
TotalContractMargin: sdk.ZeroDec(),
netQuantity: sdk.ZeroDec(),
}
}

func NewSyntheticTradeActionSummary() *SyntheticTradeActionSummary {
return &SyntheticTradeActionSummary{
MarketSummary: make(map[common.Hash]*MarketSummary),
MarketIDs: make([]common.Hash, 0),
}
}

type SyntheticTradeActionSummary struct {
MarketSummary map[common.Hash]*MarketSummary
MarketIDs []common.Hash
}

func (s *SyntheticTradeActionSummary) GetMarketIDs() []common.Hash {
var marketIDs []common.Hash
for marketID := range s.MarketSummary {
marketIDs = append(marketIDs, marketID)
}

sort.SliceStable(marketIDs, func(i, j int) bool {
return bytes.Compare(marketIDs[i].Bytes(), marketIDs[j].Bytes()) < 0
})
s.MarketIDs = marketIDs
return marketIDs
}

func (s SyntheticTradeActionSummary) Update(t *SyntheticTrade, isForUser bool) {
if _, ok := s.MarketSummary[t.MarketID]; !ok {
s.MarketSummary[t.MarketID] = NewMarketSummary()
}
summary := s.MarketSummary[t.MarketID]

if t.IsBuy {
summary.netQuantity = summary.netQuantity.Add(t.Quantity)
} else {
summary.netQuantity = summary.netQuantity.Sub(t.Quantity)
}

if isForUser {
summary.TotalUserQuantity = summary.TotalUserQuantity.Add(t.Quantity)
summary.TotalUserMargin = summary.TotalUserMargin.Add(t.Margin)
} else {
summary.TotalContractQuantity = summary.TotalContractQuantity.Add(t.Quantity)
summary.TotalContractMargin = summary.TotalContractMargin.Add(t.Margin)
}
}

// IsValid checks that all the net quantities are zero
func (s SyntheticTradeActionSummary) IsValid() bool {
for _, v := range s.MarketSummary {
if !v.netQuantity.IsZero() {
return false
}
}
return true
}

func (a *SyntheticTradeAction) Summarize() (*SyntheticTradeActionSummary, error) {
summary := NewSyntheticTradeActionSummary()

for _, t := range a.UserTrades {
summary.Update(t, true)
}

for _, t := range a.ContractTrades {
summary.Update(t, false)
}

// ensure that sum(buy quantity) == sum(sell quantity) for all markets
if !summary.IsValid() {
return nil, ErrInvalidQuantity
}

summary.GetMarketIDs()
return summary, nil
}
45 changes: 45 additions & 0 deletions chain/wasmx/types/codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package types

import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/types/msgservice"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
)

// RegisterLegacyAminoCodec registers the necessary x/wasmx interfaces and concrete types
// on the provided LegacyAmino codec. These types are used for Amino JSON serialization.
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&ContractRegistrationRequestProposal{}, "wasmx/ContractRegistrationRequestProposal", nil)
cdc.RegisterConcrete(&BatchContractRegistrationRequestProposal{}, "wasmx/BatchContractRegistrationRequestProposal", nil)

}

func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations(
(*govtypes.Content)(nil),
&ContractRegistrationRequestProposal{},
&BatchContractRegistrationRequestProposal{},
)

msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}

var (
amino = codec.NewLegacyAmino()

// ModuleCdc references the global x/wasmx module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding as Amino is
// still used for that purpose.
//
// The actual codec used for serialization should be provided to x/wasmx and
// defined at the application level.
ModuleCdc = codec.NewAminoCodec(amino)
)

func init() {
RegisterLegacyAminoCodec(amino)
cryptocodec.RegisterCrypto(amino)
amino.Seal()
}
36 changes: 36 additions & 0 deletions chain/wasmx/types/custom_execution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package types

import (
"encoding/json"

sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)

type InjectiveExecMsg struct {
ExecutionData ExecutionData `json:"injective_exec"`
}

type ExecutionData struct {
Origin string `json:"origin"`
Name string `json:"name"`
Args interface{} `json:"args"`
}

func NewInjectiveExecMsg(origin sdk.AccAddress, data string) (*InjectiveExecMsg, error) {
var e ExecutionData
if err := json.Unmarshal([]byte(data), &e); err != nil {
return nil, sdkerrors.Wrap(err, data)
}

if e.Origin == "" && origin.Empty() {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "origin address is empty")
}

// override e.Origin for safety
e.Origin = origin.String()

return &InjectiveExecMsg{
ExecutionData: e,
}, nil
}
10 changes: 10 additions & 0 deletions chain/wasmx/types/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package types

import sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"

var (
ErrInvalidGasLimit = sdkerrors.Register(ModuleName, 1, "invalid gas limit")
ErrInvalidGasPrice = sdkerrors.Register(ModuleName, 2, "invalid gas price")
ErrInvalidContractAddress = sdkerrors.Register(ModuleName, 3, "invalid contract address")
ErrAlreadyRegistered = sdkerrors.Register(ModuleName, 4, "contract already registered")
)
165 changes: 165 additions & 0 deletions chain/wasmx/types/exec_msgs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package types

import (
"encoding/json"
"fmt"
"sort"

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

func NewRegistryRegisterMsg(req *ContractRegistrationRequest) RegistryRegisterMsg {
return RegistryRegisterMsg{
Register: &RegisterMsg{
GasLimit: req.GasLimit,
ContractAddress: req.ContractAddress,
GasPrice: req.GasPrice.String(),
IsExecutable: true,
},
}
}

type RegistryRegisterMsg struct {
Register *RegisterMsg `json:"register,omitempty"`
}

type RegisterMsg struct {
GasLimit uint64 `json:"gas_limit"`
ContractAddress string `json:"contract_address"`
GasPrice string `json:"gas_price"`
IsExecutable bool `json:"is_executable"`
}

func NewBeginBlockerExecMsg() ([]byte, error) {
// Construct Exec message
beginBlocker := CWBeginBlockerExecMsg{BeginBlockerMsg: &BeginBlockerMsg{}}

//execMsg := []byte(`{"begin_blocker":{}}`)
execMsg, err := json.Marshal(beginBlocker)
if err != nil {
fmt.Println("Register marshal failed")
return nil, err
}

return execMsg, nil
}

type CWBeginBlockerExecMsg struct {
BeginBlockerMsg *BeginBlockerMsg `json:"begin_blocker,omitempty"`
}

type BeginBlockerMsg struct {
}

func NewRegistryDeactivateMsg(contractAddress string) ([]byte, error) {
// Construct Exec message
deActivateMsg := RegistryDeActivateMsg{RegistryDeActivate: &RegistryDeActivate{ContractAddress: contractAddress}}

//execMsg := []byte('{"de_activate":{"contract_address":"inj1nc5tatafv6eyq7llkr2gv50ff9e22mnfhg8yh3"}}')
execMsg, err := json.Marshal(deActivateMsg)
if err != nil {
fmt.Println("Register marshal failed")
return nil, err
}

return execMsg, nil
}

type RegistryDeActivateMsg struct {
RegistryDeActivate *RegistryDeActivate `json:"de_activate,omitempty"`
}

type RegistryDeActivate struct {
ContractAddress string `json:"contract_address"`
}

// NewRegistryContractQuery constructs the registyr Exec message
func NewRegistryContractQuery() ([]byte, error) {
contractQuery := RegistryContractQueryMsg{QueryContractsMsg: &QueryContractsMsg{}}

queryMsg, err := json.Marshal(contractQuery)
if err != nil {
fmt.Println("Register marshal failed")
return nil, err
}

return queryMsg, nil
}

type RegistryContractQueryMsg struct {
QueryContractsMsg *QueryContractsMsg `json:"get_contracts,omitempty"`
}

type QueryContractsMsg struct {
}

// NewRegistryActiveContractQuery constructs the registry active contracts query message
func NewRegistryActiveContractQuery() ([]byte, error) {
contractQuery := RegistryActiveContractQueryMsg{QueryActiveContractsMsg: &QueryActiveContractsMsg{}}

// queryData := []byte("{\"get_active_contracts\": {}}")
queryMsg, err := json.Marshal(contractQuery)
if err != nil {
fmt.Println("Register marshal failed")
return nil, err
}

return queryMsg, nil
}

type RegistryActiveContractQueryMsg struct {
QueryActiveContractsMsg *QueryActiveContractsMsg `json:"get_active_contracts,omitempty"`
}

type QueryActiveContractsMsg struct {
}

type RawContractExecutionParams struct {
Address string `json:"address"`
GasLimit uint64 `json:"gas_limit"`
GasPrice string `json:"gas_price"`
IsExecutable bool `json:"is_executable"`
}

func (r *RawContractExecutionParams) ToContractExecutionParams() (p *ContractExecutionParams, err error) {
addr, err := sdk.AccAddressFromBech32(r.Address)
if err != nil {
return nil, err
}

gasPrice, ok := sdk.NewIntFromString(r.GasPrice)
if !ok {
return nil, ErrInvalidGasPrice
}

return &ContractExecutionParams{
Address: addr,
GasLimit: r.GasLimit,
GasPrice: gasPrice,
}, nil
}

type ContractExecutionParams struct {
Address sdk.AccAddress
GasLimit uint64
GasPrice sdk.Int
IsExecutable bool
}

// GetSortedContractExecutionParams returns the ContractExecutionParams sorted by descending order of gas price
func GetSortedContractExecutionParams(contractExecutionList []RawContractExecutionParams) ([]*ContractExecutionParams, error) {
paramList := make([]*ContractExecutionParams, len(contractExecutionList))
for idx, elem := range contractExecutionList {
if v, err := elem.ToContractExecutionParams(); err != nil {
return nil, err
} else {
paramList[idx] = v
}
}

sort.SliceStable(paramList, func(i, j int) bool {
return paramList[i].GasPrice.GT(paramList[j].GasPrice)
})

return paramList, nil
}
23 changes: 23 additions & 0 deletions chain/wasmx/types/expected_keepers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package types

import (
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

// BankKeeper defines the expected bank keeper methods
type BankKeeper interface {
GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins
SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error
SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
}

type WasmViewKeeper interface {
wasmtypes.ViewKeeper
}

type WasmContractOpsKeeper interface {
wasmtypes.ContractOpsKeeper
}
Loading

0 comments on commit e26db47

Please sign in to comment.