Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: json codec to use custom json marshal unmarshal #118

Merged
merged 1 commit into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions x/ophost/types/bridge_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
"cosmossdk.io/core/address"
"cosmossdk.io/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/gogoproto/jsonpb"
)

var _ jsonpb.JSONPBMarshaler = (*BatchInfo_ChainType)(nil)
var _ jsonpb.JSONPBUnmarshaler = (*BatchInfo_ChainType)(nil)

func (config BridgeConfig) Validate(ac address.Codec) error {
if _, err := ac.StringToBytes(config.Challenger); err != nil {
return err
Expand Down Expand Up @@ -101,6 +105,16 @@
return nil
}

// MarshalJSONPB marshals the BatchInfo_ChainType to JSON
func (cy BatchInfo_ChainType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) {
return cy.MarshalJSON()

Check warning on line 110 in x/ophost/types/bridge_config.go

View check run for this annotation

Codecov / codecov/patch

x/ophost/types/bridge_config.go#L109-L110

Added lines #L109 - L110 were not covered by tests
}

// UnmarshalJSONPB unmarshals the BatchInfo_ChainType from JSON
func (cy *BatchInfo_ChainType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, inputBz []byte) error {
return cy.UnmarshalJSON(inputBz)
}

// StringWithoutPrefix returns the string representation of a BatchInfo_ChainType without the prefix
func (cy BatchInfo_ChainType) StringWithoutPrefix() string {
return cy.String()[len(chainTypePrefix):]
Expand Down
38 changes: 38 additions & 0 deletions x/ophost/types/bridge_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,19 @@ package types

import (
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/require"

"cosmossdk.io/x/tx/signing"
"github.com/cosmos/cosmos-sdk/codec"
codecaddress "github.com/cosmos/cosmos-sdk/codec/address"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/gogoproto/proto"
)

func Test_JSONMarshalUnmarshal(t *testing.T) {
Expand Down Expand Up @@ -45,3 +55,31 @@ func Test_ValidateBridgeConfig(t *testing.T) {
config.BatchInfo.ChainType = 100
require.Error(t, config.ValidateWithNoAddrValidation())
}

func TestGoGoProtoJsonPB(t *testing.T) {
interfaceRegistry, err := codectypes.NewInterfaceRegistryWithOptions(codectypes.InterfaceRegistryOptions{
ProtoFiles: proto.HybridResolver,
SigningOptions: signing.Options{
AddressCodec: codecaddress.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()),
ValidatorAddressCodec: codecaddress.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()),
},
})
if err != nil {
panic(err)
}
Comment on lines +67 to +69
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Replace panic with proper test error handling.

Using panic in tests is not recommended. Instead, use require.NoError for consistency with the rest of the test file.

-	if err != nil {
-		panic(err)
-	}
+	require.NoError(t, err)

Committable suggestion skipped: line range outside the PR's diff.

RegisterInterfaces(interfaceRegistry)
std.RegisterInterfaces(interfaceRegistry)
appCodec := codec.NewProtoCodec(interfaceRegistry)
const CHAIN_TYPE = "CELESTIA"
jsonText := fmt.Sprintf(`{"body":{"messages":[{"@type":"/opinit.ophost.v1.MsgCreateBridge","creator":"init1fgwvmvr8y5ul03aty9647vny7uj0uzt4g5zxev","config":{"challenger":"init1n8x7h4l96wmazlmxpqurccfg37fayrdafpmhfr","proposer":"init1knt8ehj03wk6hrzr4j35rmx2m7gqf4mwwcmrze","batch_info":{"submitter":"celestia13ycasdutemyk6pw6dy3ct3rxwknxrz6ygzjmu7","chain_type":"%s"},"submission_interval":"60s","finalization_period":"604800s","submission_start_height":"1","oracle_enabled":true,"metadata":"eyJwZXJtX2NoYW5uZWxzIjpbeyJwb3J0X2lkIjoibmZ0LXRyYW5zZmVyIiwiY2hhbm5lbF9pZCI6ImNoYW5uZWwtMzUzIn0seyJwb3J0X2lkIjoidHJhbnNmZXIiLCJjaGFubmVsX2lkIjoiY2hhbm5lbC0zNTIifV19"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[{"public_key":{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"AwKanlZ3AymXu7E54dOD5gL5kSrSBvTdrcow/vOsTVfl"},"mode_info":{"single":{"mode":"SIGN_MODE_DIRECT"}},"sequence":"7"}],"fee":{"amount":[{"denom":"uinit","amount":"3000"}],"gas_limit":"200000","payer":"","granter":""},"tip":null},"signatures":["4x52q4ac4+Xbg/7PXzz73vhQrZgnL+FKsLuCYDK4f1EFOnsXvFAtyn+cqXwzXTJiKY+ZUoi4QfC4u+LEj0IZtg=="]}`, CHAIN_TYPE)

var tx tx.Tx
err = appCodec.UnmarshalJSON([]byte(jsonText), &tx)
require.NoError(t, err)
require.Len(t, tx.Body.Messages, 1)

var msg sdk.Msg
err = appCodec.UnpackAny(tx.Body.Messages[0], &msg)
require.NoError(t, err)
require.Equal(t, BatchInfo_CHAIN_TYPE_CELESTIA, msg.(*MsgCreateBridge).Config.BatchInfo.ChainType)
}
Loading