Created
June 16, 2023 03:37
-
-
Save larry0x/ee0fcfb3ee99746347c4e24412fa35a4 to your computer and use it in GitHub Desktop.
json.RawMessage to sdk.Msg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"reflect" | |
"cosmossdk.io/simapp" | |
"github.com/cosmos/cosmos-sdk/codec" | |
codectypes "github.com/cosmos/cosmos-sdk/codec/types" | |
sdk "github.com/cosmos/cosmos-sdk/types" | |
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" | |
) | |
// this is the json raw message we want to unmarshal | |
var rawMsg json.RawMessage = []byte(` | |
{ | |
"@type": "/cosmos.bank.v1beta1.MsgSend", | |
"from_address": "cosmos1f3ugm8xjcq0g5acgp5smpu940f9pzk5d50c608x8r7nenyjyl0lszukf5v", | |
"to_address": "cosmos1qskahqekuvwmyqgmusfdlg62eptczc4rd05mc2", | |
"amount": [ | |
{ | |
"denom": "utoken", | |
"amount": "12345" | |
} | |
] | |
} | |
`) | |
func main() { | |
// initialize an empty interface registry | |
ir := codectypes.NewInterfaceRegistry() | |
// register basic cosmos-sdk interfaces | |
simapp.ModuleBasics.RegisterInterfaces(ir) | |
// create codec | |
cdc := codec.NewProtoCodec(ir) | |
// json raw message --> any | |
var any codectypes.Any | |
if err := cdc.UnmarshalJSON(rawMsg, &any); err != nil { | |
panic(err) | |
} | |
// any --> msg | |
var msg sdk.Msg | |
if err := ir.UnpackAny(&any, &msg); err != nil { | |
panic(err) | |
} | |
// check whether the unmarshaled msg is correct | |
expected := banktypes.NewMsgSend( | |
sdk.MustAccAddressFromBech32("cosmos1f3ugm8xjcq0g5acgp5smpu940f9pzk5d50c608x8r7nenyjyl0lszukf5v"), | |
sdk.MustAccAddressFromBech32("cosmos1qskahqekuvwmyqgmusfdlg62eptczc4rd05mc2"), | |
sdk.NewCoins(sdk.NewCoin("utoken", sdk.NewInt(12345))), | |
) | |
fmt.Println("equal?", reflect.DeepEqual(msg, expected)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment