@agoric/cosmos 0.34.2-dev-96dbb12.0 → 0.34.2-dev-ceec1d5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/git-revision.txt CHANGED
@@ -1 +1 @@
1
- 96dbb12
1
+ ceec1d5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agoric/cosmos",
3
- "version": "0.34.2-dev-96dbb12.0+96dbb12",
3
+ "version": "0.34.2-dev-ceec1d5.0+ceec1d5",
4
4
  "description": "Connect JS to the Cosmos blockchain SDK",
5
5
  "parsers": {
6
6
  "js": "mjs"
@@ -39,5 +39,5 @@
39
39
  "typeCoverage": {
40
40
  "atLeast": 0
41
41
  },
42
- "gitHead": "96dbb12270373863270e7efa724f9835ca1316c1"
42
+ "gitHead": "ceec1d5655ab909bfa85e312d53cddeee64623f3"
43
43
  }
@@ -0,0 +1,38 @@
1
+ package vm
2
+
3
+ import (
4
+ "encoding/json"
5
+
6
+ "github.com/gogo/protobuf/jsonpb"
7
+ "github.com/gogo/protobuf/proto"
8
+ )
9
+
10
+ // We need jsonpb for its access to the global registry.
11
+ var marshaller = jsonpb.Marshaler{EmitDefaults: true}
12
+
13
+ func ProtoJSONMarshal(val interface{}) ([]byte, error) {
14
+ if pm, ok := val.(proto.Message); ok {
15
+ var s string
16
+ s, err := marshaller.MarshalToString(pm)
17
+ return []byte(s), err
18
+ }
19
+
20
+ // Marshal a non-proto value to JSON.
21
+ return json.Marshal(val)
22
+ }
23
+
24
+ // ProtoJSONMarshalSlice marshals a slice of proto messages and non-proto values to
25
+ // a single JSON byte slice.
26
+ func ProtoJSONMarshalSlice(vals []interface{}) ([]byte, error) {
27
+ var err error
28
+ jsonSlice := make([]json.RawMessage, len(vals))
29
+ for i, val := range vals {
30
+ jsonSlice[i], err = ProtoJSONMarshal(val)
31
+ if err != nil {
32
+ return nil, err
33
+ }
34
+ }
35
+
36
+ // Marshal the JSON array to a single JSON byte slice.
37
+ return json.Marshal(jsonSlice)
38
+ }
@@ -0,0 +1,103 @@
1
+ package vm_test
2
+
3
+ import (
4
+ "bytes"
5
+ "strings"
6
+ "testing"
7
+
8
+ "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
9
+
10
+ sdk "github.com/cosmos/cosmos-sdk/types"
11
+
12
+ banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
13
+ stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
14
+ )
15
+
16
+ func TestProtoJSONMarshal(t *testing.T) {
17
+ accAddr, err := sdk.AccAddressFromHexUnsafe("0123456789")
18
+ if err != nil {
19
+ panic(err)
20
+ }
21
+ valAddr, err := sdk.ValAddressFromHex("9876543210")
22
+ if err != nil {
23
+ panic(err)
24
+ }
25
+ coin := sdk.NewInt64Coin("uatom", 1234567)
26
+
27
+ testCases := []struct {
28
+ name string
29
+ create func() interface{}
30
+ expected string
31
+ }{
32
+ {
33
+ "nil",
34
+ func() interface{} {
35
+ return nil
36
+ },
37
+ `null`,
38
+ },
39
+ {
40
+ "primitive number",
41
+ func() interface{} {
42
+ return 12345
43
+ },
44
+ `12345`,
45
+ },
46
+ {
47
+ "MsgDelegate",
48
+ func() interface{} {
49
+ return stakingtypes.NewMsgDelegate(accAddr, valAddr, coin)
50
+ },
51
+ `{"delegatorAddress":"cosmos1qy352eufjjmc9c","validatorAddress":"cosmosvaloper1npm9gvss52mlmk","amount":{"denom":"uatom","amount":"1234567"}}`,
52
+ },
53
+ {
54
+ "QueryDenomOwnersResponse",
55
+ func() interface{} {
56
+ return &banktypes.QueryDenomOwnersResponse{
57
+ DenomOwners: []*banktypes.DenomOwner{
58
+ {
59
+ Address: accAddr.String(),
60
+ Balance: coin,
61
+ },
62
+ {
63
+ Address: valAddr.String(),
64
+ Balance: coin.Add(coin),
65
+ },
66
+ },
67
+ }
68
+ },
69
+ `{"denomOwners":[{"address":"cosmos1qy352eufjjmc9c","balance":{"denom":"uatom","amount":"1234567"}},{"address":"cosmosvaloper1npm9gvss52mlmk","balance":{"denom":"uatom","amount":"2469134"}}],"pagination":null}`,
70
+ },
71
+ }
72
+
73
+ for _, tc := range testCases {
74
+ t.Run(tc.name, func(t *testing.T) {
75
+ val := tc.create()
76
+ bz, err := vm.ProtoJSONMarshal(val)
77
+ if err != nil {
78
+ t.Errorf("ProtoJSONMarshal of %q failed %v", val, err)
79
+ }
80
+ if !bytes.Equal(bz, []byte(tc.expected)) {
81
+ t.Errorf("ProtoJSONMarshal of %q returned %q, expected %q", val, string(bz), tc.expected)
82
+ }
83
+ })
84
+ }
85
+
86
+ t.Run("all in a slice", func(t *testing.T) {
87
+ vals := make([]interface{}, len(testCases))
88
+ expectedJson := make([]string, len(testCases))
89
+ for i, tc := range testCases {
90
+ vals[i] = tc.create()
91
+ expectedJson[i] = tc.expected
92
+ }
93
+ bz, err := vm.ProtoJSONMarshalSlice(vals)
94
+ if err != nil {
95
+ t.Errorf("ProtoJSONMarshalSlice of %q failed %v", vals, err)
96
+ }
97
+
98
+ expected := "[" + strings.Join(expectedJson, ",") + "]"
99
+ if !bytes.Equal(bz, []byte(expected)) {
100
+ t.Errorf("ProtoJSONMarshalSlice of %q returned %q, expected %q", vals, string(bz), expected)
101
+ }
102
+ })
103
+ }
@@ -1,6 +1,15 @@
1
1
  package keeper
2
2
 
3
- import "testing"
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/stretchr/testify/require"
7
+
8
+ "github.com/Agoric/agoric-sdk/golang/cosmos/app/params"
9
+ sdk "github.com/cosmos/cosmos-sdk/types"
10
+ banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
11
+ )
12
+
4
13
 
5
14
  func TestKeeper_ParseRequestTypeURL(t *testing.T) {
6
15
  testCases := []struct {
@@ -30,3 +39,59 @@ func TestKeeper_ParseRequestTypeURL(t *testing.T) {
30
39
  })
31
40
  }
32
41
  }
42
+
43
+ func TestKeeper_DeserializeTxMessages(t *testing.T) {
44
+ encodingConfig := params.MakeEncodingConfig()
45
+ cdc := encodingConfig.Marshaler
46
+
47
+ banktypes.RegisterInterfaces(encodingConfig.InterfaceRegistry)
48
+
49
+ keeper := NewKeeper(cdc, nil, nil, nil)
50
+
51
+ expectedMsgSend := []sdk.Msg{
52
+ &banktypes.MsgSend{
53
+ FromAddress: "cosmos1abc",
54
+ ToAddress: "cosmos1xyz",
55
+ Amount: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100))),
56
+ },
57
+ }
58
+
59
+ testCases := []struct {
60
+ name string
61
+ json string
62
+ expected []sdk.Msg
63
+ wantErr bool
64
+ }{
65
+ {
66
+ name: "camelCase keys",
67
+ json: `{"messages":[{"@type":"/cosmos.bank.v1beta1.MsgSend","fromAddress":"cosmos1abc","toAddress":"cosmos1xyz","amount":[{"denom":"stake","amount":"100"}]}]}`,
68
+ expected: expectedMsgSend,
69
+ wantErr: false,
70
+ },
71
+ {
72
+ name: "snake_case keys",
73
+ json: `{"messages":[{"@type":"/cosmos.bank.v1beta1.MsgSend","from_address":"cosmos1abc","to_address":"cosmos1xyz","amount":[{"denom":"stake","amount":"100"}]}]}`,
74
+ expected: expectedMsgSend,
75
+ wantErr: false,
76
+ },
77
+ {
78
+ name: "misspelled key",
79
+ json: `{"messages":[{"@type":"/cosmos.bank.v1beta1.MsgSend","from_addresss":"cosmos1abc","to_address":"cosmos1xyz","amount":[{"denom":"stake","amount":"100"}]}]}`,
80
+ expected: expectedMsgSend,
81
+ wantErr: true,
82
+ },
83
+ }
84
+
85
+ for _, tc := range testCases {
86
+ t.Run(tc.name, func(t *testing.T) {
87
+ msgs, err := keeper.DeserializeTxMessages([]byte(tc.json))
88
+
89
+ if tc.wantErr {
90
+ require.Error(t, err)
91
+ } else {
92
+ require.NoError(t, err)
93
+ require.Equal(t, tc.expected, msgs)
94
+ }
95
+ })
96
+ }
97
+ }
@@ -6,7 +6,6 @@ import (
6
6
  "fmt"
7
7
 
8
8
  sdk "github.com/cosmos/cosmos-sdk/types"
9
- "github.com/gogo/protobuf/jsonpb"
10
9
 
11
10
  "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
12
11
  "github.com/Agoric/agoric-sdk/golang/cosmos/x/vlocalchain/keeper"
@@ -56,28 +55,36 @@ func (h portHandler) Receive(cctx context.Context, str string) (ret string, err
56
55
  return
57
56
  }
58
57
 
59
- // We need jsonpb for its access to the global registry.
60
- marshaller := jsonpb.Marshaler{EmitDefaults: true, OrigName: true}
61
-
62
- var s string
63
- resps := make([]json.RawMessage, len(qms))
58
+ var errs []error
59
+ resps := make([]interface{}, len(qms))
64
60
  for i, qm := range qms {
65
61
  var qr *types.QueryResponse
66
62
  qr, err = h.keeper.Query(cctx, qm)
67
- if err != nil {
68
- return
69
- }
70
- if s, err = marshaller.MarshalToString(qr); err != nil {
71
- return
63
+ if err == nil {
64
+ // Only fill out the response if the query was successful.
65
+ resps[i] = qr
66
+ } else {
67
+ errs = append(errs, err) // Accumulate errors
68
+ resps[i] = &types.QueryResponse{Error: err.Error()}
72
69
  }
73
- resps[i] = []byte(s)
74
70
  }
75
71
 
76
- var bz []byte
77
- if bz, err = json.Marshal(resps); err != nil {
78
- return
72
+ bz, err := vm.ProtoJSONMarshalSlice(resps)
73
+ if err != nil {
74
+ return "", err
79
75
  }
80
- ret = string(bz)
76
+
77
+ switch len(errs) {
78
+ case 0:
79
+ err = nil
80
+ case 1:
81
+ err = errs[0]
82
+ case len(resps):
83
+ err = fmt.Errorf("all queries in batch failed: %v", errs)
84
+ default:
85
+ // Let them inspect the individual errors manually.
86
+ }
87
+ return string(bz), err
81
88
 
82
89
  case "VLOCALCHAIN_EXECUTE_TX":
83
90
  origCtx := sdk.UnwrapSDKContext(cctx)
@@ -97,11 +104,9 @@ func (h portHandler) Receive(cctx context.Context, str string) (ret string, err
97
104
  return
98
105
  }
99
106
 
100
- var bz []byte
101
- if bz, err = json.Marshal(resps); err != nil {
102
- return
103
- }
104
- ret = string(bz)
107
+ // Marshal the responses to proto3 JSON.
108
+ bz, e := vm.ProtoJSONMarshalSlice(resps)
109
+ return string(bz), e
105
110
  default:
106
111
  err = fmt.Errorf("unrecognized message type %s", msg.Type)
107
112
  }
@@ -5,6 +5,7 @@ import (
5
5
  "encoding/json"
6
6
  "strings"
7
7
  "testing"
8
+ "time"
8
9
 
9
10
  "github.com/Agoric/agoric-sdk/golang/cosmos/app/params"
10
11
  "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
@@ -16,6 +17,7 @@ import (
16
17
  storetypes "github.com/cosmos/cosmos-sdk/store/types"
17
18
  sdk "github.com/cosmos/cosmos-sdk/types"
18
19
  banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
20
+ stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
19
21
  transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
20
22
  "github.com/tendermint/tendermint/libs/log"
21
23
 
@@ -77,8 +79,36 @@ func (t *mockTransfer) Transfer(cctx context.Context, msg *transfertypes.MsgTran
77
79
  return &transfertypes.MsgTransferResponse{Sequence: 1}, nil
78
80
  }
79
81
 
82
+ type mockStaking struct {
83
+ stakingtypes.UnimplementedMsgServer
84
+ stakingtypes.UnimplementedQueryServer
85
+ }
86
+
87
+ var _ stakingtypes.MsgServer = (*mockStaking)(nil)
88
+ var _ stakingtypes.QueryServer = (*mockStaking)(nil)
89
+
90
+ func (s *mockStaking) Undelegate(cctx context.Context, msg *stakingtypes.MsgUndelegate) (*stakingtypes.MsgUndelegateResponse, error) {
91
+ return &stakingtypes.MsgUndelegateResponse{CompletionTime: time.Now().UTC()}, nil
92
+ }
93
+
94
+ func (s *mockStaking) UnbondingDelegation(cctx context.Context, req *stakingtypes.QueryUnbondingDelegationRequest) (*stakingtypes.QueryUnbondingDelegationResponse, error) {
95
+ unbondingDelegation := stakingtypes.UnbondingDelegation{
96
+ DelegatorAddress: req.DelegatorAddr,
97
+ ValidatorAddress: "cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj",
98
+ Entries: []stakingtypes.UnbondingDelegationEntry{
99
+ {
100
+ CreationHeight: 100,
101
+ CompletionTime: time.Now().UTC().Add(time.Hour * 24 * 7),
102
+ InitialBalance: sdk.NewInt(1000),
103
+ Balance: sdk.NewInt(500),
104
+ },
105
+ },
106
+ }
107
+ return &stakingtypes.QueryUnbondingDelegationResponse{Unbond: unbondingDelegation}, nil
108
+ }
109
+
80
110
  // makeTestKit creates a minimal Keeper and Context for use in testing.
81
- func makeTestKit(bank *mockBank, transfer *mockTransfer) (vm.PortHandler, context.Context) {
111
+ func makeTestKit(bank *mockBank, transfer *mockTransfer, staking *mockStaking) (vm.PortHandler, context.Context) {
82
112
  encodingConfig := params.MakeEncodingConfig()
83
113
  cdc := encodingConfig.Marshaler
84
114
 
@@ -93,6 +123,10 @@ func makeTestKit(bank *mockBank, transfer *mockTransfer) (vm.PortHandler, contex
93
123
  transfertypes.RegisterInterfaces(encodingConfig.InterfaceRegistry)
94
124
  transfertypes.RegisterMsgServer(txRouter, transfer)
95
125
  transfertypes.RegisterQueryServer(queryRouter, transfer)
126
+ stakingtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry)
127
+ stakingtypes.RegisterMsgServer(txRouter, staking)
128
+ stakingtypes.RegisterQueryServer(queryRouter, staking)
129
+
96
130
 
97
131
  // create a new Keeper
98
132
  keeper := vlocalchain.NewKeeper(cdc, vlocalchainStoreKey, txRouter, queryRouter)
@@ -118,7 +152,8 @@ func makeTestKit(bank *mockBank, transfer *mockTransfer) (vm.PortHandler, contex
118
152
  func TestAllocateAddress(t *testing.T) {
119
153
  bank := &mockBank{}
120
154
  transfer := &mockTransfer{}
121
- handler, cctx := makeTestKit(bank, transfer)
155
+ staking := &mockStaking{}
156
+ handler, cctx := makeTestKit(bank, transfer, staking)
122
157
 
123
158
  addrs := map[string]bool{
124
159
  firstAddr: false,
@@ -161,7 +196,8 @@ func TestQuery(t *testing.T) {
161
196
  alreadyAddr: []sdk.Coin{sdk.NewCoin("stale", sdk.NewInt(321))},
162
197
  }}
163
198
  transfer := &mockTransfer{}
164
- handler, cctx := makeTestKit(bank, transfer)
199
+ staking := &mockStaking{}
200
+ handler, cctx := makeTestKit(bank, transfer, staking)
165
201
 
166
202
  // get balances
167
203
  testCases := []struct {
@@ -230,6 +266,68 @@ func TestQuery(t *testing.T) {
230
266
  }
231
267
  })
232
268
  }
269
+
270
+ t.Run("UnbondingDelegation", func(t *testing.T) {
271
+ // create a new message
272
+ msg := `{"type":"VLOCALCHAIN_QUERY_MANY","messages":[{"@type":"/cosmos.staking.v1beta1.QueryUnbondingDelegationRequest","delegator_addr":"` + firstAddr + `","validator_addr":"cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj"}]}`
273
+ t.Logf("query request: %v", msg)
274
+ ret, err := handler.Receive(cctx, msg)
275
+ t.Logf("query response: %v", ret)
276
+ if err != nil {
277
+ t.Fatalf("unexpected error: %v", err)
278
+ }
279
+ if ret == "" {
280
+ t.Fatalf("expected non-empty json")
281
+ }
282
+
283
+ // Unmarshal the JSON response
284
+ var respJSON []map[string]interface{}
285
+ if err := json.Unmarshal([]byte(ret), &respJSON); err != nil {
286
+ t.Fatalf("unexpected error unmarshalling JSON response: %v", err)
287
+ }
288
+
289
+ // Check the response fields
290
+ if len(respJSON) != 1 {
291
+ t.Fatalf("expected 1 response, got %d", len(respJSON))
292
+ }
293
+ resp := respJSON[0]
294
+
295
+ replyAny, ok := resp["reply"].(map[string]interface{})
296
+ if !ok {
297
+ t.Fatalf("expected reply field to be a map, got %v", resp["reply"])
298
+ }
299
+
300
+ unbond, ok := replyAny["unbond"].(map[string]interface{})
301
+ if !ok {
302
+ t.Fatalf("expected unbond field to be a map, got %v", replyAny["unbond"])
303
+ }
304
+
305
+ // Check the field names and values
306
+ if unbond["delegatorAddress"] != firstAddr {
307
+ t.Errorf("expected delegatorAddress %s, got %v", firstAddr, unbond["delegator_address"])
308
+ }
309
+ if unbond["validatorAddress"] != "cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj" {
310
+ t.Errorf("expected validatorAddress cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj, got %v", unbond["validator_address"])
311
+ }
312
+
313
+ entries, ok := unbond["entries"].([]interface{})
314
+ if !ok || len(entries) != 1 {
315
+ t.Fatalf("expected 1 unbonding delegation entry, got %v", entries)
316
+ }
317
+ entry, ok := entries[0].(map[string]interface{})
318
+ if !ok {
319
+ t.Fatalf("expected unbonding delegation entry to be a map, got %v", entries[0])
320
+ }
321
+ if entry["creationHeight"] != "100" {
322
+ t.Errorf("expected creationHeight \"100\", got %v", entry["creation_height"])
323
+ }
324
+ if entry["balance"] != "500" {
325
+ t.Errorf("expected balance \"500\", got %v", entry["balance"])
326
+ }
327
+ if _, ok := entry["completionTime"]; !ok {
328
+ t.Error("expected completionTime field in the response")
329
+ }
330
+ })
233
331
  }
234
332
 
235
333
  func TestExecuteTx(t *testing.T) {
@@ -239,7 +337,8 @@ func TestExecuteTx(t *testing.T) {
239
337
  alreadyAddr: []sdk.Coin{sdk.NewCoin("stale", sdk.NewInt(321))},
240
338
  }}
241
339
  transfer := &mockTransfer{}
242
- handler, cctx := makeTestKit(bank, transfer)
340
+ staking := &mockStaking{}
341
+ handler, cctx := makeTestKit(bank, transfer, staking)
243
342
 
244
343
  // create a new message
245
344
  msg := `{"type":"VLOCALCHAIN_ALLOCATE_ADDRESS"}`
@@ -302,4 +401,34 @@ func TestExecuteTx(t *testing.T) {
302
401
  }
303
402
  })
304
403
  }
404
+
405
+ t.Run("MsgUndelegate", func(t *testing.T) {
406
+ // create a new message
407
+ msg := `{"type":"VLOCALCHAIN_EXECUTE_TX","address":"` + addr +
408
+ `","messages":[{"@type":"/cosmos.staking.v1beta1.MsgUndelegate","delegatorAddress":"` +
409
+ addr + `","validatorAddress":"cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj","amount":{"denom":"stake","amount":"100"}}]}`
410
+
411
+ ret, err := handler.Receive(cctx, msg)
412
+ if err != nil {
413
+ t.Fatalf("unexpected error: %s", err)
414
+ }
415
+ if ret == "" {
416
+ t.Fatalf("expected non-empty json")
417
+ }
418
+
419
+ // Unmarshal the response
420
+ var resp []map[string]interface{}
421
+ if err := json.Unmarshal([]byte(ret), &resp); err != nil {
422
+ t.Fatalf("unexpected error unmarshalling response: %v", err)
423
+ }
424
+
425
+ // Check the response fields
426
+ if len(resp) != 1 {
427
+ t.Fatalf("expected 1 response, got %d", len(resp))
428
+ }
429
+
430
+ if _, ok := resp[0]["completionTime"]; !ok {
431
+ t.Error("expected 'completionTime' field in response")
432
+ }
433
+ })
305
434
  }