From ad8ff34bc9bfe349635b1e15d5898c6eae96d31b Mon Sep 17 00:00:00 2001 From: kwt <4344285+kwtalley@users.noreply.github.com> Date: Thu, 8 Aug 2024 22:28:13 -0500 Subject: [PATCH 1/5] remove deprecated wasm bindings --- x/attribute/wasm/encode.go | 178 ------------- x/attribute/wasm/query.go | 129 ---------- x/attribute/wasm/types.go | 20 -- x/marker/wasm/encode.go | 325 ------------------------ x/marker/wasm/query.go | 104 -------- x/marker/wasm/types.go | 174 ------------- x/metadata/wasm/encode.go | 67 ----- x/metadata/wasm/query.go | 114 --------- x/metadata/wasm/types.go | 497 ------------------------------------- x/msgfees/wasm/encode.go | 66 ----- x/name/wasm/encode.go | 116 --------- x/name/wasm/query.go | 100 -------- x/name/wasm/types.go | 14 -- 13 files changed, 1904 deletions(-) delete mode 100644 x/attribute/wasm/encode.go delete mode 100644 x/attribute/wasm/query.go delete mode 100644 x/attribute/wasm/types.go delete mode 100644 x/marker/wasm/encode.go delete mode 100644 x/marker/wasm/query.go delete mode 100644 x/marker/wasm/types.go delete mode 100644 x/metadata/wasm/encode.go delete mode 100644 x/metadata/wasm/query.go delete mode 100644 x/metadata/wasm/types.go delete mode 100644 x/msgfees/wasm/encode.go delete mode 100644 x/name/wasm/encode.go delete mode 100644 x/name/wasm/query.go delete mode 100644 x/name/wasm/types.go diff --git a/x/attribute/wasm/encode.go b/x/attribute/wasm/encode.go deleted file mode 100644 index 263dc6d650..0000000000 --- a/x/attribute/wasm/encode.go +++ /dev/null @@ -1,178 +0,0 @@ -// Package wasm supports smart contract integration with the provenance attribute module. -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/attribute/types" -) - -// Compile time interface check -var _ provwasm.Encoder = Encoder - -// AttributeMsgParams are params for encoding []sdk.Msg types from the attribute module. -// Only one field should be set. -type AttributeMsgParams struct { - // A request to encode a MsgAddAttribute - Add *AddAttributeParams `json:"add_attribute"` - // A request to encode a MsgDeleteAttribute - Del *DeleteAttributeParams `json:"delete_attribute"` - // A request to encode a MsgDeleteAttribute - DelDistinct *DeleteDistinctAttributeParams `json:"delete_distinct_attribute"` - // A request to encode a MsgUpdateAttribute - Update *UpdateAttributeParams `json:"update_attribute"` -} - -// AddAttributeParams are params for encoding a MsgAddAttribute -type AddAttributeParams struct { - // The address of the account to add the attribute to. - Address string `json:"address"` - // The attribute name. - Name string `json:"name"` - // The attribute value. - Value []byte `json:"value"` - // The attribute value type. - ValueType string `json:"value_type"` -} - -// DeleteAttributeParams are params for encoding a MsgDeleteAttribute -type DeleteAttributeParams struct { - // The address of the account to delete the attribute from. - Address string `json:"address"` - // The attribute name. - Name string `json:"name"` -} - -// DeleteDistinctAttributeParams are params for encoding a MsgDeleteDistinctAttribute -type DeleteDistinctAttributeParams struct { - // The address of the account to delete the attribute from. - Address string `json:"address"` - // The attribute name. - Name string `json:"name"` - // The attribute value. - Value []byte `json:"value"` -} - -// UpdateAttributeParams are params for encoding a MsgUpdateAttributeRequest -type UpdateAttributeParams struct { - // The address of the account on the attribute - Address string `json:"address"` - // The attribute name. - Name string `json:"name"` - // The original attribute value. - OriginalValue []byte `json:"original_value"` - // The original attribute value type. - OriginalValueType string `json:"original_value_type"` - // The new attribute value. - UpdateValue []byte `json:"update_value"` - // The new attribute value type. - UpdateValueType string `json:"update_value_type"` -} - -// Encoder returns a smart contract message encoder for the attribute module. -func Encoder(contract sdk.AccAddress, msg json.RawMessage, _ string) ([]sdk.Msg, error) { - wrapper := struct { - Params *AttributeMsgParams `json:"attribute"` - }{} - if err := json.Unmarshal(msg, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: failed to unmarshal encode attribute request: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil attribute encode params") - } - switch { - case params.Add != nil: - return params.Add.Encode(contract) - case params.Del != nil: - return params.Del.Encode(contract) - case params.DelDistinct != nil: - return params.DelDistinct.Encode(contract) - case params.Update != nil: - return params.Update.Encode(contract) - default: - return nil, fmt.Errorf("wasm: invalid attribute encoder params: %s", string(msg)) - } -} - -// Encode creates a MsgAddAttribute. -// INFO: The contract must be the owner of the name of the attribute being added. -func (params *AddAttributeParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := types.ValidateAttributeAddress(params.Address); err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - msg := types.NewMsgAddAttributeRequest( - params.Address, - contract, - params.Name, - encodeType(params.ValueType), - params.Value, - ) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgDeleteAttribute. -// INFO: The contract must be the owner of the name of the attribute being deleted. -func (params *DeleteAttributeParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := types.ValidateAttributeAddress(params.Address); err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - msg := types.NewMsgDeleteAttributeRequest(params.Address, contract, params.Name) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgDeleteDistinctAttribute. -// INFO: The contract must be the owner of the name of the attribute being deleted. -func (params *DeleteDistinctAttributeParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := types.ValidateAttributeAddress(params.Address); err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - msg := types.NewMsgDeleteDistinctAttributeRequest(params.Address, contract, params.Name, params.Value) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgUpdateAttribute. -// INFO: The contract must be the owner of the name of the attribute being updated. -func (params *UpdateAttributeParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := types.ValidateAttributeAddress(params.Address); err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - msg := types.NewMsgUpdateAttributeRequest( - params.Address, - contract, - params.Name, - params.OriginalValue, - params.UpdateValue, - encodeType(params.OriginalValueType), - encodeType(params.UpdateValueType), - ) - return []sdk.Msg{msg}, nil -} - -// Adapt the attribute type from a string passed in message encode params passed from a smart contract. -func encodeType(valueType string) types.AttributeType { - switch valueType { - case "bytes": - return types.AttributeType_Bytes - case "json": - return types.AttributeType_JSON - case "string": - return types.AttributeType_String - case "uuid": - return types.AttributeType_UUID - case "uri": - return types.AttributeType_Uri - case "int": - return types.AttributeType_Int - case "float": - return types.AttributeType_Float - case "proto": - return types.AttributeType_Proto - default: - return types.AttributeType_Unspecified - } -} diff --git a/x/attribute/wasm/query.go b/x/attribute/wasm/query.go deleted file mode 100644 index cdd6e02aa4..0000000000 --- a/x/attribute/wasm/query.go +++ /dev/null @@ -1,129 +0,0 @@ -// Package wasm supports smart contract integration with the provenance attribute module. -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/attribute/keeper" - "github.com/provenance-io/provenance/x/attribute/types" -) - -// AttributeQueryParams represents the request type for the attribute module sent by a smart contracts. -// Only one field should be set. -type AttributeQueryParams struct { - // Get account attributes by name. - Get *GetAttributesParams `json:"get_attributes,omitempty"` - // Get all account attributes. - GetAll *GetAllAttributesParams `json:"get_all_attributes,omitempty"` -} - -// GetAttributesParams are params for querying an account attributes by address and name. -type GetAttributesParams struct { - // The account address - Address string `json:"address"` - // The name of the attributes to query - Name string `json:"name"` -} - -// GetAllAttributesParams are params for querying account attributes by address. -type GetAllAttributesParams struct { - // The account to query - Address string `json:"address"` -} - -// Querier returns a smart contract querier for the attribute module. -func Querier(keeper keeper.Keeper) provwasm.Querier { - return func(ctx sdk.Context, query json.RawMessage, _ string) ([]byte, error) { - wrapper := struct { - Params *AttributeQueryParams `json:"attribute"` - }{} - if err := json.Unmarshal(query, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: invalid query: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil account query params") - } - switch { - case params.Get != nil: - return params.Get.Run(ctx, keeper) - case params.GetAll != nil: - return params.GetAll.Run(ctx, keeper) - default: - return nil, fmt.Errorf("wasm: invalid account attribute query: %s", string(query)) - } - } -} - -// Run queries for account attributes by address and name. -func (params *GetAttributesParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - err := types.ValidateAttributeAddress(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - attrs, err := keeper.GetAttributes(ctx, params.Address, params.Name) - if err != nil { - return nil, fmt.Errorf("wasm: attribute query failed: %w", err) - } - return createResponse(params.Address, attrs) -} - -// Run queries for account attributes by address. -func (params *GetAllAttributesParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - err := types.ValidateAttributeAddress(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - attrs, err := keeper.GetAllAttributes(ctx, params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: attribute query failed: %w", err) - } - return createResponse(params.Address, attrs) -} - -// Create a JSON response from the results of a account attribute query. -func createResponse(address string, attrs []types.Attribute) ([]byte, error) { - res := AttributeResponse{Address: address} - for _, a := range attrs { - attr := Attribute{ - Name: a.Name, - Value: append([]byte{}, a.Value...), - Type: decodeType(a.AttributeType), - } - res.Attributes = append(res.Attributes, attr) - } - bz, err := json.Marshal(res) - if err != nil { - return nil, fmt.Errorf("wasm: marshal response failed: %w", err) - } - return bz, nil -} - -// Adapt the attribute type to a string that will deserialize to the correct rust enum type on -// the smart contract side of the query. -func decodeType(attributeType types.AttributeType) string { - switch attributeType { - case types.AttributeType_Bytes: - return "bytes" - case types.AttributeType_Float: - return "float" - case types.AttributeType_Int: - return "int" - case types.AttributeType_JSON: - return "json" - case types.AttributeType_String: - return "string" - case types.AttributeType_UUID: - return "uuid" - case types.AttributeType_Uri: - return "uri" - case types.AttributeType_Proto: - return "proto" - default: - return "unspecified" - } -} diff --git a/x/attribute/wasm/types.go b/x/attribute/wasm/types.go deleted file mode 100644 index a0da42163f..0000000000 --- a/x/attribute/wasm/types.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package wasm supports smart contract integration with the provenance attribute module. -package wasm - -// Attribute is a typed key-value pair attached to a cosmos account. -type Attribute struct { - // The attribute name. - Name string `json:"name"` - // The attribute value. - Value []byte `json:"value"` - // The attribute value type. - Type string `json:"type"` -} - -// AttributeResponse returns attributes attached to a cosmos account. -type AttributeResponse struct { - // The account account address in Bech32 formt - Address string `json:"address"` - // The attributes queried for the account. - Attributes []Attribute `json:"attributes,omitempty"` -} diff --git a/x/marker/wasm/encode.go b/x/marker/wasm/encode.go deleted file mode 100644 index 84c0105802..0000000000 --- a/x/marker/wasm/encode.go +++ /dev/null @@ -1,325 +0,0 @@ -// Package wasm supports smart contract integration with the provenance marker module. -package wasm - -import ( - "encoding/json" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/x/marker/types" -) - -// MarkerMsgParams are params for encoding []sdk.Msg types from the marker module. -// Only one field should be set per request. -type MarkerMsgParams struct { - // Params for encoding a MsgAddMarkerRequest - Create *CreateMarkerParams `json:"create_marker,omitempty"` - // Params for encoding a MsgAddAccessRequest - Grant *GrantAccessParams `json:"grant_marker_access,omitempty"` - // Params for encoding a MsgRevokeAccess - Revoke *RevokeAccessParams `json:"revoke_marker_access,omitempty"` - // Params for encoding a MsgFinalizeRequest - Finalize *FinalizeMarkerParams `json:"finalize_marker,omitempty"` - // Params for encoding a MsgActivateMarker - Activate *ActivateMarkerParams `json:"activate_marker,omitempty"` - // Params for encoding a MsgCancelRequest - Cancel *CancelMarkerParams `json:"cancel_marker,omitempty"` - // Params for encoding a MsgDeleteRequest - Destroy *DestroyMarkerParams `json:"destroy_marker,omitempty"` - // Params for encoding a MsgMintRequest - Mint *MintSupplyParams `json:"mint_marker_supply,omitempty"` - // Params for encoding a MsgBurnRequest - Burn *BurnSupplyParams `json:"burn_marker_supply,omitempty"` - // Params for encoding a MsgWithdrawRequest - Withdraw *WithdrawParams `json:"withdraw_coins,omitempty"` - // Params for encoding a MsgTransferRequest - Transfer *TransferParams `json:"transfer_marker_coins,omitempty"` -} - -// CreateMarkerParams are params for encoding a MsgAddMarkerRequest. -type CreateMarkerParams struct { - // The marker denomination and amount - Coin sdk.Coin `json:"coin"` - // The marker type - Type string `json:"marker_type,omitempty"` - // Allow forced transfers - AllowForcedTransfer bool `json:"allow_forced_transfer,omitempty"` - // List of restricted attributes - RestrictedAttributes []string `json:"restricted_attributes,omitempty"` - // UsdCents used to initialize the net asset value of marker - UsdCents uint64 `json:"usd_cents,omitempty"` - // Volume for the net asset value of marker - Volume uint64 `json:"volume,omitempty"` -} - -// GrantAccessParams are params for encoding a MsgAddAccessRequest. -type GrantAccessParams struct { - // The marker denomination - Denom string `json:"denom"` - // The grant permissions - Permissions []string `json:"permissions"` - // The grant address - Address string `json:"address"` -} - -// RevokeAccessParams are params for encoding a MsgDeleteAccessRequest. -type RevokeAccessParams struct { - // The marker denom - Denom string `json:"denom"` - // The address to revoke - Address string `json:"address"` -} - -// FinalizeMarkerParams are params for encoding a MsgFinalizeRequest. -type FinalizeMarkerParams struct { - // The marker denomination - Denom string `json:"denom"` -} - -// ActivateMarkerParams are params for encoding a MsgActivateRequest. -type ActivateMarkerParams struct { - // The marker denomination - Denom string `json:"denom"` -} - -// CancelMarkerParams are params for encoding a MsgCancelRequest. -type CancelMarkerParams struct { - // The marker denomination - Denom string `json:"denom"` -} - -// DestroyMarkerParams are params for encoding a MsgDeleteRequest. -type DestroyMarkerParams struct { - // The marker denomination - Denom string `json:"denom"` -} - -// MintSupplyParams are params for encoding a MsgMintRequest. -type MintSupplyParams struct { - // The marker denomination and amount to mint - Coin sdk.Coin `json:"coin"` -} - -// BurnSupplyParams are params for encoding a MsgBurnRequest. -type BurnSupplyParams struct { - // The marker denomination and amount to burn - Coin sdk.Coin `json:"coin"` -} - -// WithdrawParams are params for encoding a MsgWithdrawRequest. -type WithdrawParams struct { - // The marker denomination - Denom string `json:"marker_denom"` - // The withdrawal denomination and amount - Coin sdk.Coin `json:"coin"` - // The recipient of the withdrawal - Recipient string `json:"recipient"` -} - -// TransferParams are params for encoding a MsgTransferRequest. -type TransferParams struct { - // The denomination and amount to transfer - Coin sdk.Coin `json:"coin"` - // The recipient of the transfer - To string `json:"to"` - // The sender of the transfer - From string `json:"from"` -} - -// Encoder returns a smart contract message encoder for the name module. -func Encoder(contract sdk.AccAddress, msg json.RawMessage, _ string) ([]sdk.Msg, error) { - wrapper := struct { - Params *MarkerMsgParams `json:"marker"` - }{} - if err := json.Unmarshal(msg, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: failed to unmarshal marker encode params: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil marker encode params") - } - switch { - case params.Create != nil: - return params.Create.Encode(contract) - case params.Grant != nil: - return params.Grant.Encode(contract) - case params.Revoke != nil: - return params.Revoke.Encode(contract) - case params.Finalize != nil: - return params.Finalize.Encode(contract) - case params.Activate != nil: - return params.Activate.Encode(contract) - case params.Cancel != nil: - return params.Cancel.Encode(contract) - case params.Destroy != nil: - return params.Destroy.Encode(contract) - case params.Mint != nil: - return params.Mint.Encode(contract) - case params.Burn != nil: - return params.Burn.Encode(contract) - case params.Withdraw != nil: - return params.Withdraw.Encode(contract) - case params.Transfer != nil: - return params.Transfer.Encode(contract) - default: - return nil, fmt.Errorf("wasm: invalid marker encode request: %s", string(msg)) - } -} - -// Encode creates a MsgAddMarkerRequest. -// The contract must be the signer (from address) and manager of the marker. -func (params *CreateMarkerParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if !params.Coin.IsValid() { - return nil, fmt.Errorf("wasm: invalid marker supply in CreateMarkerParams: coin is invalid") - } - if strings.TrimSpace(params.Type) == "" { - return nil, fmt.Errorf("wasm: missing marker type in CreateMarkerParams") - } - markerType, err := types.MarkerTypeFromString(params.Type) - if err != nil { - return nil, fmt.Errorf("wasm: invalid marker type in CreateMarkerParams: %w", err) - } - if params.AllowForcedTransfer && markerType != types.MarkerType_RestrictedCoin { - return nil, fmt.Errorf("wasm: allow_forced_transfer can only be set if marker type is restricted") - } - - msg := types.NewMsgAddMarkerRequest( - params.Coin.Denom, params.Coin.Amount, contract, contract, markerType, false, false, params.AllowForcedTransfer, params.RestrictedAttributes, params.UsdCents, params.Volume, - ) - - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgAddAccessRequest. -// The contract must be the administrator of the marker. -func (params *GrantAccessParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid address in GrantAccessParams: %w", err) - } - if strings.TrimSpace(params.Denom) == "" { - return nil, fmt.Errorf("wasm: empty denomination in GrantAccessParams") - } - access := make([]types.Access, len(params.Permissions)) - for i, perm := range params.Permissions { - access[i] = types.AccessByName(perm) - } - msg := types.NewMsgAddAccessRequest( - params.Denom, - contract, - *types.NewAccessGrant(address, access), - ) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgDeleteAccessRequest. -// The contract must be the administrator of the marker. -func (params *RevokeAccessParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid denomination in RevokeAccessParams: %w", err) - } - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid address in RevokeAccessParams: %w", err) - } - msg := types.NewDeleteAccessRequest(params.Denom, contract, address) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgFinalizeRequest. -// The contract must be the administrator of the marker. -func (params *FinalizeMarkerParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid denomination in FinalizeMarkerParams: %w", err) - } - msg := types.NewMsgFinalizeRequest(params.Denom, contract) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgActivateRequest. -// The contract must be the administrator of the marker. -func (params *ActivateMarkerParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid denomination in ActivateMarkerParams: %w", err) - } - msg := types.NewMsgActivateRequest(params.Denom, contract) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgCancelRequest. -// The contract must be the administrator of the marker. -func (params *CancelMarkerParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid denomination in CancelMarkerParams: %w", err) - } - msg := types.NewMsgCancelRequest(params.Denom, contract) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgDeleteRequest. -// The contract must be the administrator of the marker. -func (params *DestroyMarkerParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid denomination in DestroyMarkerParams: %w", err) - } - msg := types.NewMsgDeleteRequest(params.Denom, contract) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgMintRequest. -// The contract must be the administrator of the marker. -func (params *MintSupplyParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if !params.Coin.IsValid() { - return nil, fmt.Errorf("wasm: invalid MintSupplyParams: coin is invalid") - } - msg := types.NewMsgMintRequest(contract, params.Coin) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgBurnRequest. -// The contract must be the administrator of the marker. -func (params *BurnSupplyParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if !params.Coin.IsValid() { - return nil, fmt.Errorf("wasm: invalid BurnSupplyParams: coin is invalid") - } - msg := types.NewMsgBurnRequest(contract, params.Coin) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgWithdrawRequest. -// The contract must be the administrator of the marker. -func (params *WithdrawParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if err := sdk.ValidateDenom(params.Denom); err != nil { - return nil, fmt.Errorf("wasm: invalid marker denom in WithdrawParams: %w", err) - } - if !params.Coin.IsValid() { - return nil, fmt.Errorf("wasm: invalid WithdrawParams: coin is invalid") - } - recipient, err := sdk.AccAddressFromBech32(params.Recipient) - if err != nil { - return nil, fmt.Errorf("wasm: invalid recipient address: %w", err) - } - msg := types.NewMsgWithdrawRequest( - contract, recipient, params.Denom, sdk.NewCoins(params.Coin)) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgTransferRequest. -// The contract must be the administrator of the marker. -func (params *TransferParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - if !params.Coin.IsValid() { - return nil, fmt.Errorf("wasm: invalid TransferParams: coin is invalid") - } - to, err := sdk.AccAddressFromBech32(params.To) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'to' address in TransferParams: %w", err) - } - from, err := sdk.AccAddressFromBech32(params.From) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'from' address in TransferParams: %w", err) - } - msg := types.NewMsgTransferRequest(contract, from, to, params.Coin) - return []sdk.Msg{msg}, nil -} diff --git a/x/marker/wasm/query.go b/x/marker/wasm/query.go deleted file mode 100644 index 87f3b5c20a..0000000000 --- a/x/marker/wasm/query.go +++ /dev/null @@ -1,104 +0,0 @@ -// Package wasm supports smart contract integration with the provenance marker module. -package wasm - -import ( - "encoding/json" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/marker/keeper" - "github.com/provenance-io/provenance/x/marker/types" -) - -// MarkerQueryParams represent parameters used to query the marker module. -type MarkerQueryParams struct { - // Get a marker by address. - *GetMarkerByAddress `json:"get_marker_by_address,omitempty"` - // Get a marker by denomination. - *GetMarkerByDenom `json:"get_marker_by_denom,omitempty"` -} - -// GetMarkerByAddress represent a query request to get a marker by address. -type GetMarkerByAddress struct { - // The marker address - Address string `json:"address,omitempty"` -} - -// GetMarkerByDenom represent a query request to get a marker by denomination. -type GetMarkerByDenom struct { - // The marker denomination - Denom string `json:"denom,omitempty"` -} - -// Querier returns a smart contract querier for the name module. -func Querier(keeper keeper.Keeper) provwasm.Querier { - return func(ctx sdk.Context, query json.RawMessage, _ string) ([]byte, error) { - wrapper := struct { - Params *MarkerQueryParams `json:"marker"` - }{} - if err := json.Unmarshal(query, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: invalid query: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil marker query params") - } - switch { - case params.GetMarkerByAddress != nil: - return params.GetMarkerByAddress.Run(ctx, keeper) - case params.GetMarkerByDenom != nil: - return params.GetMarkerByDenom.Run(ctx, keeper) - default: - return nil, fmt.Errorf("wasm: invalid marker query: %s", string(query)) - } - } -} - -// Run gets a marker by address or denomination. -func (params *GetMarkerByAddress) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - if strings.TrimSpace(params.Address) == "" { - return nil, fmt.Errorf("wasm: marker address cannot be empty") - } - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: address is invalid: %w", err) - } - marker, err := keeper.GetMarker(ctx, address) - if err != nil { - return nil, fmt.Errorf("wasm: no marker found for address '%s': %w", params.Address, err) - } - markerAccount, ok := marker.(*types.MarkerAccount) - if !ok { - return nil, fmt.Errorf("wasm: unable to type-cast marker account") - } - balance := keeper.GetEscrow(ctx, marker) - bz, err := json.Marshal(createResponseType(markerAccount, balance)) - if err != nil { - return nil, fmt.Errorf("wasm: marshal marker query response failed: %w", err) - } - return bz, nil -} - -// Run gets a marker by address or denomination. -func (params *GetMarkerByDenom) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - if strings.TrimSpace(params.Denom) == "" { - return nil, fmt.Errorf("wasm: marker denomination cannot be empty") - } - marker, err := keeper.GetMarkerByDenom(ctx, params.Denom) - if err != nil { - return nil, fmt.Errorf("wasm: no marker found for denomination '%s': %w", params.Denom, err) - } - markerAccount, ok := marker.(*types.MarkerAccount) - if !ok { - return nil, fmt.Errorf("wasm: unable to type-cast marker account") - } - balance := keeper.GetEscrow(ctx, marker) - bz, err := json.Marshal(createResponseType(markerAccount, balance)) - if err != nil { - return nil, fmt.Errorf("wasm: marshal marker query response failed: %w", err) - } - return bz, nil -} diff --git a/x/marker/wasm/types.go b/x/marker/wasm/types.go deleted file mode 100644 index f30af21aa2..0000000000 --- a/x/marker/wasm/types.go +++ /dev/null @@ -1,174 +0,0 @@ -// Package wasm supports smart contract integration with the provenance marker module. -package wasm - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/x/marker/types" -) - -// Types in this file were generated using JSON schema: -// https://github.com/provenance-io/provwasm/blob/main/packages/bindings/schema/marker.json -// Naming has been tweaked slightly to remove dup names across types. - -// Marker represents a marker account in provwasm supported format. -type Marker struct { - AccountNumber uint64 `json:"account_number"` - Address string `json:"address"` - Coins sdk.Coins `json:"coins"` - Denom string `json:"denom"` - Manager string `json:"manager"` - MarkerType MarkerType `json:"marker_type"` - Permissions []*AccessGrant `json:"permissions,omitempty"` - Sequence uint64 `json:"sequence"` - Status MarkerStatus `json:"status"` - TotalSupply string `json:"total_supply"` - SupplyFixed bool `json:"supply_fixed"` - AllowForcedTransfer bool `json:"allow_forced_transfer"` -} - -// AccessGrant are marker permissions granted to an account. -type AccessGrant struct { - Address string `json:"address"` - Permissions []MarkerPermission `json:"permissions,omitempty"` -} - -// MarkerType defines types of markers. -type MarkerType string - -const ( - // MarkerTypeCoin is a concrete marker type - MarkerTypeCoin MarkerType = "coin" - // MarkerTypeRestricted is a concrete marker type - MarkerTypeRestricted MarkerType = "restricted" - // MarkerTypeUnspecified is a concrete marker type - MarkerTypeUnspecified MarkerType = "unspecified" -) - -// MarkerPermission defines marker permission types. -type MarkerPermission string - -const ( - // MarkerPermissionAdmin is a concrete marker permission type - MarkerPermissionAdmin MarkerPermission = "admin" - // MarkerPermissionBurn is a concrete marker permission type - MarkerPermissionBurn MarkerPermission = "burn" - // MarkerPermissionDelete is a concrete marker permission type - MarkerPermissionDelete MarkerPermission = "delete" - // MarkerPermissionDeposit is a concrete marker permission type - MarkerPermissionDeposit MarkerPermission = "deposit" - // MarkerPermissionForceTransfer is a concrete marker permission type - MarkerPermissionForceTransfer MarkerPermission = "force_transfer" - // MarkerPermissionMint is a concrete marker permission type - MarkerPermissionMint MarkerPermission = "mint" - // MarkerPermissionTransfer is a concrete marker permission type - MarkerPermissionTransfer MarkerPermission = "transfer" - // MarkerPermissionUnspecified is a concrete marker permission type - MarkerPermissionUnspecified MarkerPermission = "unspecified" - // MarkerPermissionWithdraw is a concrete marker permission type - MarkerPermissionWithdraw MarkerPermission = "withdraw" -) - -// MarkerStatus defines marker status types. -type MarkerStatus string - -const ( - // MarkerStatusActive is a concrete marker status type - MarkerStatusActive MarkerStatus = "active" - // MarkerStatusCancelled is a concrete marker status type - MarkerStatusCancelled MarkerStatus = "cancelled" - // MarkerStatusDestroyed is a concrete marker status type - MarkerStatusDestroyed MarkerStatus = "destroyed" - // MarkerStatusFinalized is a concrete marker status type - MarkerStatusFinalized MarkerStatus = "finalized" - // MarkerStatusProposed is a concrete marker status type - MarkerStatusProposed MarkerStatus = "proposed" - // MarkerStatusUnspecified is a concrete marker status type - MarkerStatusUnspecified MarkerStatus = "unspecified" -) - -// Convert a core marker type to provwasm supported format. -func createResponseType(input *types.MarkerAccount, balance sdk.Coins) *Marker { - marker := &Marker{ - AccountNumber: input.GetAccountNumber(), - Address: input.GetAddress().String(), - Coins: balance, - Denom: input.GetDenom(), - Manager: input.GetManager().String(), - MarkerType: markerTypeFor(input.GetMarkerType()), - Sequence: input.GetSequence(), - Status: markerStatusFor(input.GetStatus()), - TotalSupply: input.GetSupply().Amount.String(), - SupplyFixed: input.SupplyFixed, - AllowForcedTransfer: input.AllowForcedTransfer, - } - for _, ag := range input.GetAccessList() { - marker.Permissions = append(marker.Permissions, accessGrantFor(ag)) - } - return marker -} - -// Adapt the core marker type to provwasm format. -func markerTypeFor(input types.MarkerType) MarkerType { - switch input { - case types.MarkerType_Coin: - return MarkerTypeCoin - case types.MarkerType_RestrictedCoin: - return MarkerTypeRestricted - default: - return MarkerTypeUnspecified - } -} - -// Adapt the core marker status to provwasm format. -func markerStatusFor(input types.MarkerStatus) MarkerStatus { - switch input { - case types.StatusActive: - return MarkerStatusActive - case types.StatusCancelled: - return MarkerStatusCancelled - case types.StatusDestroyed: - return MarkerStatusDestroyed - case types.StatusFinalized: - return MarkerStatusFinalized - case types.StatusProposed: - return MarkerStatusProposed - default: - return MarkerStatusUnspecified - } -} - -// Adapt the core marker access grant type to provwasm format. -func accessGrantFor(input types.AccessGrant) *AccessGrant { - grant := &AccessGrant{ - Address: input.Address, - } - for _, a := range input.GetAccessList() { - grant.Permissions = append(grant.Permissions, permissionFor(a)) - } - return grant -} - -// Adapt the core marker access type to provwasm format. -func permissionFor(input types.Access) MarkerPermission { - switch input { - case types.Access_Admin: - return MarkerPermissionAdmin - case types.Access_Burn: - return MarkerPermissionBurn - case types.Access_Delete: - return MarkerPermissionDelete - case types.Access_Deposit: - return MarkerPermissionDeposit - case types.Access_ForceTransfer: - return MarkerPermissionForceTransfer - case types.Access_Mint: - return MarkerPermissionMint - case types.Access_Transfer: - return MarkerPermissionTransfer - case types.Access_Withdraw: - return MarkerPermissionWithdraw - default: - return MarkerPermissionUnspecified - } -} diff --git a/x/metadata/wasm/encode.go b/x/metadata/wasm/encode.go deleted file mode 100644 index fbc9b6e614..0000000000 --- a/x/metadata/wasm/encode.go +++ /dev/null @@ -1,67 +0,0 @@ -// Package wasm supports smart contract integration with the provenance metadata module. -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/x/metadata/types" -) - -// MetadataMsgParams are params for encoding []sdk.Msg types from the scope module. -// Only one field should be set per request. -type MetadataMsgParams struct { - // Params for encoding a MsgWriteScopeRequest - WriteScope *WriteScope `json:"write_scope,omitempty"` -} - -// WriteScope are params for encoding a MsgWriteScopeRequest. -type WriteScope struct { - // The scope we want to create/update. - Scope Scope `json:"scope"` - // The signers' addresses. - Signers []string `json:"signers"` - // UsdCents used to initialize the net asset value of scope - UsdMills uint64 `json:"usd_mills,omitempty"` -} - -// Encoder returns a smart contract message encoder for the metadata module. -func Encoder(_ sdk.AccAddress, msg json.RawMessage, _ string) ([]sdk.Msg, error) { - wrapper := struct { - Params *MetadataMsgParams `json:"metadata"` - }{} - if err := json.Unmarshal(msg, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: failed to unmarshal metadata encode params: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil metadata encode params") - } - switch { - case params.WriteScope != nil: - return params.WriteScope.Encode() - default: - return nil, fmt.Errorf("wasm: invalid metadata encode request: %s", string(msg)) - } -} - -// Encode creates a MsgAddScopeDataAccessRequest. -func (params *WriteScope) Encode() ([]sdk.Msg, error) { - // verify the signer addresses are valid - for _, addr := range params.Signers { - _, err := sdk.AccAddressFromBech32(addr) - if err != nil { - return nil, fmt.Errorf("wasm: signer address must be a Bech32 string: %w", err) - } - } - scope, err := params.Scope.convertToBaseType() - if err != nil { - return nil, err - } - - msg := types.NewMsgWriteScopeRequest(*scope, params.Signers, params.UsdMills) - - return []sdk.Msg{msg}, nil -} diff --git a/x/metadata/wasm/query.go b/x/metadata/wasm/query.go deleted file mode 100644 index ea38f3c846..0000000000 --- a/x/metadata/wasm/query.go +++ /dev/null @@ -1,114 +0,0 @@ -// Package wasm supports smart contract integration with the metadata module. -package wasm - -import ( - "encoding/json" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/metadata/keeper" - "github.com/provenance-io/provenance/x/metadata/types" -) - -// MetadataQueryParams represents the query request type for the metadata module sent by smart contracts. -// Only one query field should be set. -type MetadataQueryParams struct { - // Get a scope by ID. - GetScope *GetScopeParams `json:"get_scope,omitempty"` - // Get sessions by scope ID and name (optional). - GetSessions *GetSessionsParams `json:"get_sessions,omitempty"` - // Get records by scope ID and name (optional). - GetRecords *GetRecordsParams `json:"get_records,omitempty"` -} - -// GetScopeParams are the inputs for a scope query. -type GetScopeParams struct { - // The bech32 address of the scope we want to get. - ScopeID string `json:"scope_id"` -} - -// GetSessionsParams are the inputs for a session query. -type GetSessionsParams struct { - // The bech32 address of the scope we want to get sessions for. - ScopeID string `json:"scope_id"` -} - -// GetRecordsParams are the inputs for a records query. -type GetRecordsParams struct { - // The bech32 address of the scope we want to get records for. - ScopeID string `json:"scope_id"` - // The optional record name. - Name string `json:"name,omitempty"` -} - -// Querier returns a smart contract querier for the metadata module. -func Querier(keeper keeper.Keeper) provwasm.Querier { - return func(ctx sdk.Context, query json.RawMessage, _ string) ([]byte, error) { - wrapper := struct { - Params *MetadataQueryParams `json:"metadata"` - }{} - if err := json.Unmarshal(query, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: invalid metadata query params: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil metadata query params") - } - switch { - case params.GetScope != nil: - return params.GetScope.Run(ctx, keeper) - case params.GetSessions != nil: - return params.GetSessions.Run(ctx, keeper) - case params.GetRecords != nil: - return params.GetRecords.Run(ctx, keeper) - default: - return nil, fmt.Errorf("wasm: invalid metadata query: %s", string(query)) - } - } -} - -// Run gets a scope by ID. -func (params *GetScopeParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - scopeID, err := types.MetadataAddressFromBech32(params.ScopeID) - if err != nil { - return nil, fmt.Errorf("wasm: invalid scope ID: %w", err) - } - scope, found := keeper.GetScope(ctx, scopeID) - if !found { - return nil, fmt.Errorf("wasm: scope not found: %s", params.ScopeID) - } - return createScopeResponse(scope) -} - -// Run gets sessions by scope ID and name (optional) -func (params *GetSessionsParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - scopeID, err := types.MetadataAddressFromBech32(params.ScopeID) - if err != nil { - return nil, fmt.Errorf("wasm: invalid scope ID: %w", err) - } - var sessions []types.Session - err = keeper.IterateSessions(ctx, scopeID, func(s types.Session) bool { - sessions = append(sessions, s) - return false - }) - if err != nil { - return nil, fmt.Errorf("wasm: %w", err) - } - return createSessionsResponse(sessions) -} - -// Run gets records by scope ID and name (optional) -func (params *GetRecordsParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - scopeID, err := types.MetadataAddressFromBech32(params.ScopeID) - if err != nil { - return nil, fmt.Errorf("wasm: invalid scope ID: %w", err) - } - records, err := keeper.GetRecords(ctx, scopeID, strings.TrimSpace(params.Name)) - if err != nil { - return nil, fmt.Errorf("wasm: unable to get scope records: %w", err) - } - return createRecordsResponse(records) -} diff --git a/x/metadata/wasm/types.go b/x/metadata/wasm/types.go deleted file mode 100644 index ea7e55819b..0000000000 --- a/x/metadata/wasm/types.go +++ /dev/null @@ -1,497 +0,0 @@ -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/bech32" - - "github.com/provenance-io/provenance/x/metadata/types" -) - -// These are the Go struct that map to the Rust smart contract types defined by the provwasm JSON schema. -// The types in this file were generated using quicktype.io and slightly modified. - -// Scope is a root reference for a collection of records owned by one or more parties. -type Scope struct { - ScopeID string `json:"scope_id"` - SpecificationID string `json:"specification_id"` - DataAccess []string `json:"data_access,omitempty"` - Owners []*Party `json:"owners,omitempty"` - ValueOwnerAddress string `json:"value_owner_address"` -} - -// Sessions is a group of sessions. -type Sessions struct { - Sessions []*Session `json:"sessions"` -} - -// Session is the state of an execution context for a specification instance. -type Session struct { - SessionID string `json:"session_id"` - SpecificationID string `json:"specification_id"` - Name string `json:"name"` - Context []byte `json:"context"` - Parties []*Party `json:"parties,omitempty"` -} - -// PartyType defines roles that can be associated to a party. -type PartyType string - -const ( - // PartyTypeAffiliate is a concrete party type. - PartyTypeAffiliate PartyType = "affiliate" - // PartyTypeCustodian is a concrete party type. - PartyTypeCustodian PartyType = "custodian" - // PartyTypeInvestor is a concrete party type. - PartyTypeInvestor PartyType = "investor" - // PartyTypeOmnibus is a concrete party type. - PartyTypeOmnibus PartyType = "omnibus" - // PartyTypeOriginator is a concrete party type. - PartyTypeOriginator PartyType = "originator" - // PartyTypeOwner is a concrete party type. - PartyTypeOwner PartyType = "owner" - // PartyTypeProvenance is a concrete party type. - PartyTypeProvenance PartyType = "provenance" - // PartyTypeServicer is a concrete party type. - PartyTypeServicer PartyType = "servicer" - // PartyTypeController is a concrete party type. - PartyTypeController PartyType = "controller" - // PartyTypeValidator is a concrete party type. - PartyTypeValidator PartyType = "validator" - // PartyTypeUnspecified is a concrete party type. - PartyTypeUnspecified PartyType = "unspecified" -) - -// Party is an address with an associated role. -type Party struct { - Address string `json:"address"` - Role PartyType `json:"role"` -} - -// Records is a group of records. -type Records struct { - Records []*Record `json:"records"` -} - -// Record is a record of fact for a session. -type Record struct { - SessionID string `json:"session_id"` - SpecificationID string `json:"specification_id"` - Name string `json:"name"` - Process *Process `json:"process"` - Inputs []*RecordInput `json:"inputs,omitempty"` - Outputs []*RecordOutput `json:"outputs,omitempty"` -} - -// RecordInput is an input used to produce a record. -type RecordInput struct { - Name string `json:"name"` - TypeName string `json:"type_name"` - Source *RecordInputSource `json:"source"` - Status InputStatus `json:"status"` -} - -// RecordInputSource is a record input source. Either record or hash should be set, but not both. -type RecordInputSource struct { - Record *RecordInputSourceRecord `json:"record,omitempty"` - Hash *RecordInputSourceHash `json:"hash,omitempty"` -} - -// RecordInputSourceRecord is the address of a record on chain (established records). -type RecordInputSourceRecord struct { - RecordID string `json:"record_id"` -} - -// RecordInputSourceHash is the hash of an off-chain piece of information (proposed records). -type RecordInputSourceHash struct { - Hash string `json:"hash"` -} - -// RecordOutput is the output of a process. -type RecordOutput struct { - Hash string `json:"hash"` - Status ResultStatus `json:"status"` -} - -// Process is the entity that generated a record. -type Process struct { - ProcessID *ProcessID `json:"process_id"` - Name string `json:"name"` - Method string `json:"method"` -} - -// ProcessID is a process identifier. Either address or hash should be set, but not both. -type ProcessID struct { - Address *ProcessIDAddress `json:"address,omitempty"` - Hash *ProcessIDHash `json:"hash,omitempty"` -} - -// ProcessIDAddress is the on-chain address of a process. -type ProcessIDAddress struct { - Address string `json:"address"` -} - -// ProcessIDHash is the hash of an off-chain process. -type ProcessIDHash struct { - Hash string `json:"hash"` -} - -// InputStatus defines record input status types. -type InputStatus string - -const ( - // InputStatusRecord is a concrete record input status type. - InputStatusRecord InputStatus = "record" - // InputStatusProposed is a concrete record input status type. - InputStatusProposed InputStatus = "proposed" - // InputStatusUnspecified is a concrete record input status type. - InputStatusUnspecified InputStatus = "unspecified" -) - -// Result status types. -type ResultStatus string - -const ( - // ResultStatusPass is a concrete result status type. - ResultStatusPass ResultStatus = "pass" - // ResultStatusFail is a concrete result status type. - ResultStatusFail ResultStatus = "fail" - // ResultStatusSkip is a concrete result status type. - ResultStatusSkip ResultStatus = "skip" - // ResultStatusUnspecified is a concrete result status type. - ResultStatusUnspecified ResultStatus = "unspecified" -) - -// A slightly modified, non-panicing version of MetadataAddress.String(). Panics across FFI -// boundaries can crash the chain, so just fail the query. -func bech32Address(ma types.MetadataAddress) (string, error) { - if ma.Empty() { // cause a query failure for addresses we expect to be non-empty. - return "", fmt.Errorf("wasm: empty metadata address") - } - hrp, err := types.VerifyMetadataAddressFormat(ma) - if err != nil { - return "", fmt.Errorf("wasm: %w", err) - } - bech32Addr, err := bech32.ConvertAndEncode(hrp, ma.Bytes()) - if err != nil { - return "", fmt.Errorf("wasm: %w", err) - } - return bech32Addr, nil -} - -// Convert a provwasm scope into the baseType scope. -func (scope *Scope) convertToBaseType() (*types.Scope, error) { - scopeID, err := types.MetadataAddressFromBech32(scope.ScopeID) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'scope id': %w", err) - } - specificationID, err := types.MetadataAddressFromBech32(scope.SpecificationID) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'specification id': %w", err) - } - // verify the data_access addresses are valid - for _, addr := range scope.DataAccess { - _, err = sdk.AccAddressFromBech32(addr) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'data_access' address: %w", err) - } - } - baseType := &types.Scope{ - ScopeId: scopeID, - SpecificationId: specificationID, - Owners: make([]types.Party, len(scope.Owners)), - DataAccess: scope.DataAccess, - ValueOwnerAddress: scope.ValueOwnerAddress, - } - for i, o := range scope.Owners { - party, err := o.convertToBaseType() - if err != nil { - return nil, err - } - baseType.Owners[i] = *party - } - - return baseType, nil -} - -// Convert a provwasm party into the baseType party. -func (party *Party) convertToBaseType() (*types.Party, error) { - _, err := sdk.AccAddressFromBech32(party.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid 'data_access' address: %w", err) - } - return &types.Party{ - Address: party.Address, - Role: party.Role.convertToBaseType(), - }, nil -} - -// Convert a provwasm partytype into the baseType partytype. -func (partyType *PartyType) convertToBaseType() types.PartyType { - switch *partyType { - case PartyTypeOriginator: - return types.PartyType_PARTY_TYPE_ORIGINATOR - case PartyTypeServicer: - return types.PartyType_PARTY_TYPE_SERVICER - case PartyTypeInvestor: - return types.PartyType_PARTY_TYPE_INVESTOR - case PartyTypeCustodian: - return types.PartyType_PARTY_TYPE_CUSTODIAN - case PartyTypeOwner: - return types.PartyType_PARTY_TYPE_OWNER - case PartyTypeAffiliate: - return types.PartyType_PARTY_TYPE_AFFILIATE - case PartyTypeOmnibus: - return types.PartyType_PARTY_TYPE_OMNIBUS - case PartyTypeProvenance: - return types.PartyType_PARTY_TYPE_PROVENANCE - case PartyTypeController: - return types.PartyType_PARTY_TYPE_CONTROLLER - case PartyTypeValidator: - return types.PartyType_PARTY_TYPE_VALIDATOR - default: - return types.PartyType_PARTY_TYPE_UNSPECIFIED - } -} - -// Convert a scope into provwasm JSON format. -func createScopeResponse(baseType types.Scope) ([]byte, error) { - scopeID, err := bech32Address(baseType.ScopeId) - if err != nil { - return nil, err - } - specificationID, err := bech32Address(baseType.SpecificationId) - if err != nil { - return nil, err - } - scope := &Scope{ - ScopeID: scopeID, - SpecificationID: specificationID, - ValueOwnerAddress: baseType.ValueOwnerAddress, - DataAccess: baseType.DataAccess, - Owners: make([]*Party, len(baseType.Owners)), - } - for i, o := range baseType.Owners { - scope.Owners[i] = createParty(o) - } - bz, err := json.Marshal(scope) - if err != nil { - return nil, fmt.Errorf("wasm: marshal scope failed: %w", err) - } - return bz, nil -} - -// Convert a slice of sessions into provwasm JSON format. -func createSessionsResponse(baseTypeSlice []types.Session) ([]byte, error) { - sessions := &Sessions{ - Sessions: make([]*Session, len(baseTypeSlice)), - } - for i, baseType := range baseTypeSlice { - session, err := createSession(baseType) - if err != nil { - return nil, err - } - sessions.Sessions[i] = session - } - bz, err := json.Marshal(sessions) - if err != nil { - return nil, fmt.Errorf("wasm: marshal sessions failed: %w", err) - } - return bz, nil -} - -// Convert a session into its provwasm type. -func createSession(baseType types.Session) (*Session, error) { - sessionID, err := bech32Address(baseType.SessionId) - if err != nil { - return nil, err - } - specificationID, err := bech32Address(baseType.SpecificationId) - if err != nil { - return nil, err - } - session := &Session{ - SessionID: sessionID, - SpecificationID: specificationID, - Name: baseType.Name, - Context: baseType.Context, - Parties: make([]*Party, len(baseType.Parties)), - } - for i, p := range baseType.Parties { - session.Parties[i] = createParty(p) - } - return session, nil -} - -// Convert a slice of records into provwasm JSON format. -func createRecordsResponse(baseTypeSlice []*types.Record) ([]byte, error) { - records := &Records{ - Records: make([]*Record, len(baseTypeSlice)), - } - for i, baseType := range baseTypeSlice { - record, err := createRecord(baseType) - if err != nil { - return nil, err - } - records.Records[i] = record - } - bz, err := json.Marshal(records) - if err != nil { - return nil, fmt.Errorf("wasm: marshal records failed: %w", err) - } - return bz, nil -} - -// Convert a record into its provwasm type. -func createRecord(baseType *types.Record) (*Record, error) { - sessionID, err := bech32Address(baseType.SessionId) - if err != nil { - return nil, err - } - specID, err := bech32Address(baseType.SpecificationId) - if err != nil { - return nil, err - } - process, err := createProcess(baseType.Process) - if err != nil { - return nil, err - } - record := &Record{ - SessionID: sessionID, - SpecificationID: specID, - Name: baseType.Name, - Process: process, - Inputs: make([]*RecordInput, len(baseType.Inputs)), - Outputs: make([]*RecordOutput, len(baseType.Outputs)), - } - for i, in := range baseType.Inputs { - input, err := createRecordInput(in) - if err != nil { - return nil, err - } - record.Inputs[i] = input - } - for i, out := range baseType.Outputs { - record.Outputs[i] = &RecordOutput{ - Hash: out.Hash, - Status: createResultStatus(out.Status), - } - } - return record, nil -} - -// Convert a process to its provwasm type. -func createProcess(baseType types.Process) (*Process, error) { - address := baseType.GetAddress() - hash := baseType.GetHash() - processID := &ProcessID{} - switch { - case address != "": - processID.Address = &ProcessIDAddress{Address: address} - case hash != "": - processID.Hash = &ProcessIDHash{Hash: hash} - default: - return nil, fmt.Errorf("wasm: address or hash must be defined for a process id") - } - return &Process{ - ProcessID: processID, - Name: baseType.Name, - Method: baseType.Method, - }, nil -} - -// Convert a record input into its provwasm type. -func createRecordInput(baseType types.RecordInput) (*RecordInput, error) { - source, err := createSource(baseType) - if err != nil { - return nil, err - } - return &RecordInput{ - Name: baseType.Name, - TypeName: baseType.TypeName, - Source: source, - Status: createRecordInputStatus(baseType.Status), - }, nil -} - -// Convert a record input source to its provwasm type. -func createSource(baseType types.RecordInput) (*RecordInputSource, error) { - source := &RecordInputSource{} - if s, ok := baseType.GetSource().(*types.RecordInput_Hash); ok { - source.Hash = &RecordInputSourceHash{Hash: s.Hash} - return source, nil - } - if s, ok := baseType.GetSource().(*types.RecordInput_RecordId); ok { - recordID, err := bech32Address(s.RecordId) - if err != nil { - return nil, err - } - source.Record = &RecordInputSourceRecord{RecordID: recordID} - return source, nil - } - return nil, fmt.Errorf("wasm: hash or record id must be defined for a source") -} - -// Convert a party to its provwasm type. -func createParty(baseType types.Party) *Party { - return &Party{ - Address: baseType.Address, - Role: createRole(baseType.Role), - } -} - -// Convert a party type to its provwasm type. -func createRole(baseType types.PartyType) PartyType { - switch baseType { - case types.PartyType_PARTY_TYPE_ORIGINATOR: - return PartyTypeOriginator - case types.PartyType_PARTY_TYPE_SERVICER: - return PartyTypeServicer - case types.PartyType_PARTY_TYPE_INVESTOR: - return PartyTypeInvestor - case types.PartyType_PARTY_TYPE_CUSTODIAN: - return PartyTypeCustodian - case types.PartyType_PARTY_TYPE_OWNER: - return PartyTypeOwner - case types.PartyType_PARTY_TYPE_AFFILIATE: - return PartyTypeAffiliate - case types.PartyType_PARTY_TYPE_OMNIBUS: - return PartyTypeOmnibus - case types.PartyType_PARTY_TYPE_PROVENANCE: - return PartyTypeProvenance - case types.PartyType_PARTY_TYPE_CONTROLLER: - return PartyTypeController - case types.PartyType_PARTY_TYPE_VALIDATOR: - return PartyTypeValidator - default: - return PartyTypeUnspecified - } -} - -// Convert a record input status to its provwasm type. -func createRecordInputStatus(baseType types.RecordInputStatus) InputStatus { - switch baseType { - case types.RecordInputStatus_Proposed: - return InputStatusProposed - case types.RecordInputStatus_Record: - return InputStatusRecord - default: - return InputStatusUnspecified - } -} - -// Convert a result status to its provwasm type. -func createResultStatus(baseType types.ResultStatus) ResultStatus { - switch baseType { - case types.ResultStatus_RESULT_STATUS_PASS: - return ResultStatusPass - case types.ResultStatus_RESULT_STATUS_FAIL: - return ResultStatusFail - case types.ResultStatus_RESULT_STATUS_SKIP: - return ResultStatusSkip - default: - return ResultStatusUnspecified - } -} diff --git a/x/msgfees/wasm/encode.go b/x/msgfees/wasm/encode.go deleted file mode 100644 index d5d6306ee6..0000000000 --- a/x/msgfees/wasm/encode.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package wasm supports smart contract integration with the provenance name module. -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/msgfees/types" -) - -// Compile time interface check -var _ provwasm.Encoder = Encoder - -// MsgFeesMsgParams are params for encoding []sdk.Msg types from the msgfees module. -type MsgFeesMsgParams struct { - // Params for encoding a MsgAddMarkerRequest - AssessCustomFee *AssessCustomFeeParams `json:"assess_custom_fee,omitempty"` -} - -// AssessCustomFeeParams are params for encoding a MsgAssessCustomMsgFeeRequest. -type AssessCustomFeeParams struct { - // The fee amount to assess - Amount sdk.Coin `json:"amount"` - // The signer of the message - From string `json:"from"` - // An optional short name - Name string `json:"name,omitempty"` - // An optional address to receive the fees. if present, the split amount from basis points is sent to address. - Recipient string `json:"recipient,omitempty"` - // An optional recipient basis points (0 - 10,000). if not present, defaults to 10,000 - RecipientBasisPoints string `recipient_basis_points:"recipient,omitempty"` -} - -// Encoder returns a smart contract message encoder for the name module. -func Encoder(contract sdk.AccAddress, msg json.RawMessage, _ string) ([]sdk.Msg, error) { - wrapper := struct { - Params *MsgFeesMsgParams `json:"msgfees"` - }{} - if err := json.Unmarshal(msg, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: failed to unmarshal name encode params: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil msgfees encode params") - } - switch { - case params != nil: - return params.AssessCustomFee.Encode(contract) - default: - return nil, fmt.Errorf("wasm: invalid msgfees encode request: %s", string(msg)) - } -} - -// Encode creates a MsgAssessCustomMsgFeeRequest. -func (params *AssessCustomFeeParams) Encode(_ sdk.AccAddress) ([]sdk.Msg, error) { - // Create message request - msg := types.NewMsgAssessCustomMsgFeeRequest(params.Name, params.Amount, params.Recipient, params.From, params.RecipientBasisPoints) - err := msg.ValidateBasic() - if err != nil { - return nil, err - } - return []sdk.Msg{&msg}, nil -} diff --git a/x/name/wasm/encode.go b/x/name/wasm/encode.go deleted file mode 100644 index b52e79d0d5..0000000000 --- a/x/name/wasm/encode.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package wasm supports smart contract integration with the provenance name module. -package wasm - -import ( - "encoding/json" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/name/types" -) - -// Compile time interface check -var _ provwasm.Encoder = Encoder - -// NameMsgParams are params for encoding []sdk.Msg types from the name module. -// Only one field should be set. -type NameMsgParams struct { - // Encode a MsgBindName - Bind *BindNameParams `json:"bind_name,omitempty"` - // Encode a MsgUnBindName - Delete *DeleteNameParams `json:"delete_name,omitempty"` - // Encode a MsgModifyName - Modify *ModifyNameParams `json:"modify_name,omitempty"` -} - -// BindNameParams are params for encoding a MsgBindName. -type BindNameParams struct { - // The combined name and root name (eg in x.y.z : name = x, root_name = y.z) - Name string `json:"name"` - // The address to bind - Address string `json:"address"` - // Whether to restrict binding child names to the owner - Restrict bool `json:"restrict"` -} - -// DeleteNameParams are params for encoding a MsgDeleteNameRequest. -type DeleteNameParams struct { - // The name to unbind from the contract address. - Name string `json:"name"` -} - -// DeleteNameParams are params for encoding a MsgModifyNameRequest. -type ModifyNameParams struct { - // The existing name to modify - Authority string `json:"authority"` - // The existing name to modify - Name string `json:"name"` - // The address to bind - Address string `json:"address"` - // Whether to restrict binding child names to the owner - Restrict bool `json:"restrict"` -} - -// Encoder returns a smart contract message encoder for the name module. -func Encoder(contract sdk.AccAddress, msg json.RawMessage, _ string) ([]sdk.Msg, error) { - wrapper := struct { - Params *NameMsgParams `json:"name"` - }{} - if err := json.Unmarshal(msg, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: failed to unmarshal name encode params: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil name encode params") - } - switch { - case params.Bind != nil: - return params.Bind.Encode(contract) - case params.Delete != nil: - return params.Delete.Encode(contract) - case params.Modify != nil: - return params.Modify.Encode(contract) - default: - return nil, fmt.Errorf("wasm: invalid name encode request: %s", string(msg)) - } -} - -// Encode creates a MsgBindNameRequest. -// The parent address is required to be the signer. But, in x/wasm the contract address must be the signer. -// This means that contract instances should have a parent name they own, or the parent name must be unrestricted. -func (params *BindNameParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid bind address: %w", err) - } - // Extract the name and parent name (eg in x.y.z : name = x, parent_name = y.z) - names := strings.SplitN(params.Name, ".", 2) - if len(names) != 2 { - return nil, fmt.Errorf("wasm: invalid name: %s", params.Name) - } - // Create message request - record := types.NewNameRecord(names[0], address, params.Restrict) - parent := types.NewNameRecord(names[1], contract, false) - msg := types.NewMsgBindNameRequest(record, parent) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgDeleteNameRequest. -func (params *DeleteNameParams) Encode(contract sdk.AccAddress) ([]sdk.Msg, error) { - record := types.NewNameRecord(params.Name, contract, false) - msg := types.NewMsgDeleteNameRequest(record) - return []sdk.Msg{msg}, nil -} - -// Encode creates a MsgModifyNameRequest. -func (params *ModifyNameParams) Encode(_ sdk.AccAddress) ([]sdk.Msg, error) { - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid bind address: %w", err) - } - msg := types.NewMsgModifyNameRequest(params.Authority, params.Name, address, params.Restrict) - return []sdk.Msg{msg}, nil -} diff --git a/x/name/wasm/query.go b/x/name/wasm/query.go deleted file mode 100644 index beee620dc9..0000000000 --- a/x/name/wasm/query.go +++ /dev/null @@ -1,100 +0,0 @@ -// Package wasm supports smart contract integration with the name module. -package wasm - -import ( - "encoding/json" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/provenance-io/provenance/internal/provwasm" - "github.com/provenance-io/provenance/x/name/keeper" - "github.com/provenance-io/provenance/x/name/types" -) - -// NameQueryParams represents the request type for the name module sent by a smart contracts. -// Only one query field should be set. -type NameQueryParams struct { - // Resolve the address bound to the given name. - Resolve *ResolveQueryParams `json:"resolve,omitempty"` - // Lookup all names an address is bound to. - Lookup *LookupQueryParams `json:"lookup,omitempty"` -} - -// ResolveQueryParams are the inputs for a resolve name query. -type ResolveQueryParams struct { - // The name we want to resolve the address for. - Name string `json:"name"` -} - -// LookupQueryParams are the inpust for a lookup query. -type LookupQueryParams struct { - // Find all names bound to this address. - Address string `json:"address"` -} - -// Querier returns a smart contract querier for the name module. -func Querier(keeper keeper.Keeper) provwasm.Querier { - return func(ctx sdk.Context, query json.RawMessage, _ string) ([]byte, error) { - wrapper := struct { - Params *NameQueryParams `json:"name"` - }{} - if err := json.Unmarshal(query, &wrapper); err != nil { - return nil, fmt.Errorf("wasm: invalid query: %w", err) - } - params := wrapper.Params - if params == nil { - return nil, fmt.Errorf("wasm: nil name query params") - } - switch { - case params.Resolve != nil: - return params.Resolve.Run(ctx, keeper) - case params.Lookup != nil: - return params.Lookup.Run(ctx, keeper) - default: - return nil, fmt.Errorf("wasm: invalid name query: %s", string(query)) - } - } -} - -// Run resolves the address for a name. -func (params *ResolveQueryParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - record, err := keeper.GetRecordByName(ctx, params.Name) - if err != nil { - return nil, fmt.Errorf("wasm: resolve query failed: %w", err) - } - return createResponse(types.NameRecords{*record}) -} - -// Run looks up all names bound to a given address. -func (params *LookupQueryParams) Run(ctx sdk.Context, keeper keeper.Keeper) ([]byte, error) { - acc, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, fmt.Errorf("wasm: invalid address: %w", err) - } - records, err := keeper.GetRecordsByAddress(ctx, acc) - if err != nil { - return nil, fmt.Errorf("wasm: lookup query failed: %w", err) - } - return createResponse(records) -} - -// A helper function for converting name module record types into local query response types. -func createResponse(records types.NameRecords) ([]byte, error) { - rep := &QueryResNames{} - for _, r := range records { - rep.Records = append( - rep.Records, - QueryResName{ - Name: r.Name, - Address: r.Address, - Restricted: r.Restricted, - }, - ) - } - bz, err := json.Marshal(rep) - if err != nil { - return nil, fmt.Errorf("wasm: marshal response failed: %w", err) - } - return bz, nil -} diff --git a/x/name/wasm/types.go b/x/name/wasm/types.go deleted file mode 100644 index 11f2926ff1..0000000000 --- a/x/name/wasm/types.go +++ /dev/null @@ -1,14 +0,0 @@ -// Package wasm supports smart contract integration with the provenance name module. -package wasm - -// QueryResName contains the address from a name query. -type QueryResName struct { - Name string `json:"name"` - Address string `json:"address"` - Restricted bool `json:"restricted"` -} - -// QueryResNames contains a sequence of name records. -type QueryResNames struct { - Records []QueryResName `json:"records,omitempty"` -} From ac02a3e991fcd18e0b4ca4b18275ccfb5808450c Mon Sep 17 00:00:00 2001 From: kwt <4344285+kwtalley@users.noreply.github.com> Date: Thu, 8 Aug 2024 22:28:41 -0500 Subject: [PATCH 2/5] remove deprecated wasm bindings from app --- app/app.go | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/app/app.go b/app/app.go index 85a741bb35..71bfbd58fb 100644 --- a/app/app.go +++ b/app/app.go @@ -145,7 +145,6 @@ import ( "github.com/provenance-io/provenance/x/attribute" attributekeeper "github.com/provenance-io/provenance/x/attribute/keeper" attributetypes "github.com/provenance-io/provenance/x/attribute/types" - attributewasm "github.com/provenance-io/provenance/x/attribute/wasm" "github.com/provenance-io/provenance/x/exchange" exchangekeeper "github.com/provenance-io/provenance/x/exchange/keeper" exchangemodule "github.com/provenance-io/provenance/x/exchange/module" @@ -161,19 +160,15 @@ import ( "github.com/provenance-io/provenance/x/marker" markerkeeper "github.com/provenance-io/provenance/x/marker/keeper" markertypes "github.com/provenance-io/provenance/x/marker/types" - markerwasm "github.com/provenance-io/provenance/x/marker/wasm" "github.com/provenance-io/provenance/x/metadata" metadatakeeper "github.com/provenance-io/provenance/x/metadata/keeper" metadatatypes "github.com/provenance-io/provenance/x/metadata/types" - metadatawasm "github.com/provenance-io/provenance/x/metadata/wasm" msgfeeskeeper "github.com/provenance-io/provenance/x/msgfees/keeper" msgfeesmodule "github.com/provenance-io/provenance/x/msgfees/module" msgfeestypes "github.com/provenance-io/provenance/x/msgfees/types" - msgfeeswasm "github.com/provenance-io/provenance/x/msgfees/wasm" "github.com/provenance-io/provenance/x/name" namekeeper "github.com/provenance-io/provenance/x/name/keeper" nametypes "github.com/provenance-io/provenance/x/name/types" - namewasm "github.com/provenance-io/provenance/x/name/wasm" oraclekeeper "github.com/provenance-io/provenance/x/oracle/keeper" oraclemodule "github.com/provenance-io/provenance/x/oracle/module" oracletypes "github.com/provenance-io/provenance/x/oracle/types" @@ -631,18 +626,9 @@ func New( // Init CosmWasm encoder integrations encoderRegistry := provwasm.NewEncoderRegistry() - encoderRegistry.RegisterEncoder(nametypes.RouterKey, namewasm.Encoder) - encoderRegistry.RegisterEncoder(attributetypes.RouterKey, attributewasm.Encoder) - encoderRegistry.RegisterEncoder(markertypes.RouterKey, markerwasm.Encoder) - encoderRegistry.RegisterEncoder(metadatatypes.RouterKey, metadatawasm.Encoder) - encoderRegistry.RegisterEncoder(msgfeestypes.RouterKey, msgfeeswasm.Encoder) // Init CosmWasm query integrations querierRegistry := provwasm.NewQuerierRegistry() - querierRegistry.RegisterQuerier(nametypes.RouterKey, namewasm.Querier(app.NameKeeper)) - querierRegistry.RegisterQuerier(attributetypes.RouterKey, attributewasm.Querier(app.AttributeKeeper)) - querierRegistry.RegisterQuerier(markertypes.RouterKey, markerwasm.Querier(app.MarkerKeeper)) - querierRegistry.RegisterQuerier(metadatatypes.RouterKey, metadatawasm.Querier(app.MetadataKeeper)) // Add the capabilities and indicate that provwasm contracts can be run on this chain. // Capabilities defined here: https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md From 3914e4456772be2c075907c33d4ef8e40343e19d Mon Sep 17 00:00:00 2001 From: kwt <4344285+kwtalley@users.noreply.github.com> Date: Fri, 9 Aug 2024 14:00:08 -0500 Subject: [PATCH 3/5] remove deprecated wasm message encoders and request handlers --- internal/provwasm/message_encoders.go | 75 --------------------------- internal/provwasm/requests.go | 27 ---------- 2 files changed, 102 deletions(-) delete mode 100644 internal/provwasm/message_encoders.go delete mode 100644 internal/provwasm/requests.go diff --git a/internal/provwasm/message_encoders.go b/internal/provwasm/message_encoders.go deleted file mode 100644 index 47000d9723..0000000000 --- a/internal/provwasm/message_encoders.go +++ /dev/null @@ -1,75 +0,0 @@ -// Package provwasm allows CosmWasm smart contracts to communicate with custom provenance modules. -package provwasm - -import ( - "encoding/json" - "fmt" - - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - - "cosmossdk.io/log" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - internalsdk "github.com/provenance-io/provenance/internal/sdk" -) - -// Encoder describes behavior for provenance smart contract message encoding. -// The contract address must ALWAYS be set as the Msg signer. -type Encoder func(contract sdk.AccAddress, data json.RawMessage, version string) ([]sdk.Msg, error) - -// EncoderRegistry maps routes to encoders. -type EncoderRegistry struct { - encoders map[string]Encoder -} - -// NewEncoderRegistry creates a new registry for message encoders. -func NewEncoderRegistry() *EncoderRegistry { - return &EncoderRegistry{ - encoders: make(map[string]Encoder), - } -} - -// RegisterEncoder adds a message encoder for the given route. -func (qr *EncoderRegistry) RegisterEncoder(route string, encoder Encoder) { - if _, exists := qr.encoders[route]; exists { - panic(fmt.Sprintf("wasm: encoder already registered for route: %s", route)) - } - qr.encoders[route] = encoder -} - -// MessageEncoders provides provenance message encoding support for smart contracts. -func MessageEncoders(registry *EncoderRegistry, logger log.Logger) *wasmkeeper.MessageEncoders { - return &wasmkeeper.MessageEncoders{ - Custom: customEncoders(registry, logger), - } -} - -// Custom provenance encoders for CosmWasm integration. -func customEncoders(registry *EncoderRegistry, logger log.Logger) wasmkeeper.CustomEncoder { - return func(contract sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - req := EncodeRequest{} - if err := json.Unmarshal(msg, &req); err != nil { - logger.Error("failed to unmarshal encode request", "err", err) - return nil, sdkerrors.ErrJSONUnmarshal.Wrap(err.Error()) - } - encode, exists := registry.encoders[req.Route] - if !exists { - logger.Error("encoder not found", "route", req.Route) - return nil, sdkerrors.ErrInvalidRequest.Wrapf("encoder not found for route: %s", req.Route) - } - msgs, err := encode(contract, req.Params, req.Version) - if err != nil { - logger.Error("failed to encode message", "err", err) - return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) - } - for _, msg := range msgs { - if err := internalsdk.ValidateBasic(msg); err != nil { - logger.Error("message validation failed", "err", err) - return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) - } - } - return msgs, nil - } -} diff --git a/internal/provwasm/requests.go b/internal/provwasm/requests.go deleted file mode 100644 index 9e8a5a0298..0000000000 --- a/internal/provwasm/requests.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package provwasm allows CosmWasm smart contracts to communicate with custom provenance modules. -package provwasm - -import ( - "encoding/json" -) - -// RequestFields contains fields shared between query requests and encode requests. -// Version should be the semantic data format version of the provenance rust bindings (eg 1.2.3). -type RequestFields struct { - // The router key of the module - Route string `json:"route"` - // The module-specific inputs represented as JSON. - Params json.RawMessage `json:"params"` - // Enables smart contract backwards compatibility. - Version string `json:"version,omitempty"` -} - -// QueryRequest is the top-level type for provenance query support in CosmWasm smart contracts. -type QueryRequest struct { - RequestFields -} - -// EncodeRequest is the top-level type for provenance message encoding support in CosmWasm smart contracts. -type EncodeRequest struct { - RequestFields -} From 2d55d8088d3b12736adab9098c23f849c2661179 Mon Sep 17 00:00:00 2001 From: kwt <4344285+kwtalley@users.noreply.github.com> Date: Fri, 9 Aug 2024 14:02:01 -0500 Subject: [PATCH 4/5] remove old custom query plugin handler --- .../2119-remove-deprecated-bindings.md | 1 + app/app.go | 9 +---- internal/provwasm/query_plugins.go | 35 +------------------ 3 files changed, 3 insertions(+), 42 deletions(-) create mode 100644 .changelog/unreleased/client-breaking/2119-remove-deprecated-bindings.md diff --git a/.changelog/unreleased/client-breaking/2119-remove-deprecated-bindings.md b/.changelog/unreleased/client-breaking/2119-remove-deprecated-bindings.md new file mode 100644 index 0000000000..bf39bc24da --- /dev/null +++ b/.changelog/unreleased/client-breaking/2119-remove-deprecated-bindings.md @@ -0,0 +1 @@ +* remove old provwasm bindings [#2119](https://github.com/provenance-io/provenance/pull/2119). diff --git a/app/app.go b/app/app.go index 71bfbd58fb..ce7c4a1329 100644 --- a/app/app.go +++ b/app/app.go @@ -624,12 +624,6 @@ func New( } wasmConfig := wasmWrap.Wasm - // Init CosmWasm encoder integrations - encoderRegistry := provwasm.NewEncoderRegistry() - - // Init CosmWasm query integrations - querierRegistry := provwasm.NewQuerierRegistry() - // Add the capabilities and indicate that provwasm contracts can be run on this chain. // Capabilities defined here: https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md supportedFeatures := []string{"staking", "provenance", "stargate", "iterator", "cosmwasm_1_1", "cosmwasm_1_2", "cosmwasm_1_3", "cosmwasm_1_4", "cosmwasm_2_0", "cosmwasm_2_1"} @@ -654,8 +648,7 @@ func New( wasmConfig, supportedFeatures, govAuthority, - wasmkeeper.WithQueryPlugins(provwasm.QueryPlugins(querierRegistry, *app.GRPCQueryRouter(), appCodec)), - wasmkeeper.WithMessageEncoders(provwasm.MessageEncoders(encoderRegistry, logger)), + wasmkeeper.WithQueryPlugins(provwasm.QueryPlugins(*app.GRPCQueryRouter(), appCodec)), ) app.WasmKeeper = &wasmKeeperInstance diff --git a/internal/provwasm/query_plugins.go b/internal/provwasm/query_plugins.go index f1de46fdaa..5ef0d3a2f2 100644 --- a/internal/provwasm/query_plugins.go +++ b/internal/provwasm/query_plugins.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/gogoproto/proto" provwasmtypes "github.com/provenance-io/provenance/x/wasm/types" @@ -46,7 +45,7 @@ func (qr *QuerierRegistry) RegisterQuerier(route string, querier Querier) { } // QueryPlugins provides provenance query support for smart contracts. -func QueryPlugins(registry *QuerierRegistry, queryRouter baseapp.GRPCQueryRouter, cdc codec.Codec) *wasmkeeper.QueryPlugins { +func QueryPlugins(queryRouter baseapp.GRPCQueryRouter, cdc codec.Codec) *wasmkeeper.QueryPlugins { protoCdc, ok := cdc.(*codec.ProtoCodec) if !ok { panic(fmt.Errorf("codec must be *codec.ProtoCodec type: actual: %T", cdc)) @@ -55,43 +54,11 @@ func QueryPlugins(registry *QuerierRegistry, queryRouter baseapp.GRPCQueryRouter stargateCdc := codec.NewProtoCodec(provwasmtypes.NewWasmInterfaceRegistry(protoCdc.InterfaceRegistry())) return &wasmkeeper.QueryPlugins{ - Custom: customPlugins(registry), Stargate: StargateQuerier(queryRouter, stargateCdc), Grpc: GrpcQuerier(queryRouter), } } -// Custom provenance queriers for CosmWasm integration. -func customPlugins(registry *QuerierRegistry) wasmkeeper.CustomQuerier { - return func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { - req := QueryRequest{} - if err := json.Unmarshal(request, &req); err != nil { - ctx.Logger().Error("failed to unmarshal query request", "err", err) - return nil, sdkerrors.ErrJSONUnmarshal.Wrap(err.Error()) - } - query, exists := registry.queriers[req.Route] - if !exists { - ctx.Logger().Error("querier not found", "route", req.Route) - return nil, sdkerrors.ErrInvalidRequest.Wrapf("querier not found for route: %s", req.Route) - } - bz, err := query(ctx, req.Params, req.Version) - if err != nil { - ctx.Logger().Error("failed to execute query", "err", err) - return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error()) - } - if len(bz) > maxQueryResultSize { - errm := "query result size limit exceeded" - ctx.Logger().Error(errm, "maxQueryResultSize", maxQueryResultSize) - return nil, sdkerrors.ErrInvalidRequest.Wrap(errm) - } - if !json.Valid(bz) { - ctx.Logger().Error("invalid querier JSON", "route", req.Route) - return nil, sdkerrors.ErrJSONMarshal.Wrapf("invalid querier JSON from route: %s", req.Route) - } - return bz, nil - } -} - // StargateQuerier dispatches whitelisted stargate queries func StargateQuerier(queryRouter baseapp.GRPCQueryRouter, cdc codec.Codec) func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { From 684ceab5b46f356f13ab4359fdabaadc7f1f5088 Mon Sep 17 00:00:00 2001 From: kwt <4344285+kwtalley@users.noreply.github.com> Date: Fri, 9 Aug 2024 16:56:59 -0500 Subject: [PATCH 5/5] lint fix --- internal/provwasm/query_plugins.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/provwasm/query_plugins.go b/internal/provwasm/query_plugins.go index 5ef0d3a2f2..415b6ec6ed 100644 --- a/internal/provwasm/query_plugins.go +++ b/internal/provwasm/query_plugins.go @@ -18,9 +18,6 @@ import ( provwasmtypes "github.com/provenance-io/provenance/x/wasm/types" ) -// The maximum querier result size allowed, ~10MB. -const maxQueryResultSize = (10 << 20) - 1 - // Querier describes behavior for provenance smart contract query support. type Querier func(ctx sdk.Context, query json.RawMessage, version string) ([]byte, error)