forked from CosmWasm/wasmd
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathquery_plugins.go
620 lines (564 loc) · 20.9 KB
/
query_plugins.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
package keeper
import (
"encoding/json"
"errors"
"fmt"
abci "github.com/tendermint/tendermint/abci/types"
baseapp "github.com/Finschia/finschia-sdk/baseapp"
"github.com/Finschia/finschia-sdk/codec"
sdk "github.com/Finschia/finschia-sdk/types"
sdkerrors "github.com/Finschia/finschia-sdk/types/errors"
distributiontypes "github.com/Finschia/finschia-sdk/x/distribution/types"
stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types"
wasmvmtypes "github.com/Finschia/wasmvm/types"
channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types"
"github.com/Finschia/wasmd/x/wasm/types"
)
type QueryHandler struct {
Ctx sdk.Context
Plugins WasmVMQueryHandler
Caller sdk.AccAddress
gasRegister GasRegister
}
func NewQueryHandler(ctx sdk.Context, vmQueryHandler WasmVMQueryHandler, caller sdk.AccAddress, gasRegister GasRegister) QueryHandler {
return QueryHandler{
Ctx: ctx,
Plugins: vmQueryHandler,
Caller: caller,
gasRegister: gasRegister,
}
}
type GRPCQueryRouter interface {
Route(path string) baseapp.GRPCQueryHandler
}
// -- end baseapp interfaces --
var _ wasmvmtypes.Querier = QueryHandler{}
func (q QueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ([]byte, error) {
// set a limit for a subCtx
sdkGas := q.gasRegister.FromWasmVMGas(gasLimit)
// discard all changes/ events in subCtx by not committing the cached context
subCtx, _ := q.Ctx.WithGasMeter(sdk.NewGasMeter(sdkGas)).CacheContext()
// make sure we charge the higher level context even on panic
defer func() {
q.Ctx.GasMeter().ConsumeGas(subCtx.GasMeter().GasConsumed(), "contract sub-query")
}()
res, err := q.Plugins.HandleQuery(subCtx, q.Caller, request)
if err == nil {
// short-circuit, the rest is dealing with handling existing errors
return res, nil
}
// special mappings to system error (which are not redacted)
var noSuchContract *types.ErrNoSuchContract
if ok := errors.As(err, &noSuchContract); ok {
err = wasmvmtypes.NoSuchContract{Addr: noSuchContract.Addr}
}
// Issue #759 - we don't return error string for worries of non-determinism
return nil, redactError(err)
}
func (q QueryHandler) GasConsumed() uint64 {
return q.Ctx.GasMeter().GasConsumed()
}
type CustomQuerier func(ctx sdk.Context, request json.RawMessage) ([]byte, error)
type QueryPlugins struct {
Bank func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error)
Custom CustomQuerier
IBC func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error)
Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error)
Stargate func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error)
Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error)
}
type contractMetaDataSource interface {
GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo
}
type wasmQueryKeeper interface {
contractMetaDataSource
QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte
QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error)
IsPinnedCode(ctx sdk.Context, codeID uint64) bool
}
func DefaultQueryPlugins(
bank types.BankViewKeeper,
staking types.StakingKeeper,
distKeeper types.DistributionKeeper,
channelKeeper types.ChannelKeeper,
queryRouter GRPCQueryRouter,
wasm wasmQueryKeeper,
) QueryPlugins {
return QueryPlugins{
Bank: BankQuerier(bank),
Custom: CustomQuerierImpl(queryRouter),
IBC: IBCQuerier(wasm, channelKeeper),
Staking: StakingQuerier(staking, distKeeper),
Stargate: RejectStargateQuerier(),
Wasm: WasmQuerier(wasm),
}
}
func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins {
// only update if this is non-nil and then only set values
if o == nil {
return e
}
if o.Bank != nil {
e.Bank = o.Bank
}
if o.Custom != nil {
e.Custom = o.Custom
}
if o.IBC != nil {
e.IBC = o.IBC
}
if o.Staking != nil {
e.Staking = o.Staking
}
if o.Stargate != nil {
e.Stargate = o.Stargate
}
if o.Wasm != nil {
e.Wasm = o.Wasm
}
return e
}
// HandleQuery executes the requested query
func (e QueryPlugins) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) {
// do the query
if request.Bank != nil {
return e.Bank(ctx, request.Bank)
}
if request.Custom != nil {
return e.Custom(ctx, request.Custom)
}
if request.IBC != nil {
return e.IBC(ctx, caller, request.IBC)
}
if request.Staking != nil {
return e.Staking(ctx, request.Staking)
}
if request.Stargate != nil {
return e.Stargate(ctx, request.Stargate)
}
if request.Wasm != nil {
return e.Wasm(ctx, request.Wasm)
}
return nil, wasmvmtypes.Unknown{}
}
func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) {
return func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) {
if request.AllBalances != nil {
addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address)
}
coins := bankKeeper.GetAllBalances(ctx, addr)
res := wasmvmtypes.AllBalancesResponse{
Amount: ConvertSdkCoinsToWasmCoins(coins),
}
return json.Marshal(res)
}
if request.Balance != nil {
addr, err := sdk.AccAddressFromBech32(request.Balance.Address)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address)
}
coin := bankKeeper.GetBalance(ctx, addr, request.Balance.Denom)
res := wasmvmtypes.BalanceResponse{
Amount: wasmvmtypes.Coin{
Denom: coin.Denom,
Amount: coin.Amount.String(),
},
}
return json.Marshal(res)
}
if request.Supply != nil {
coin := bankKeeper.GetSupply(ctx, request.Supply.Denom)
res := wasmvmtypes.SupplyResponse{
Amount: wasmvmtypes.Coin{
Denom: coin.Denom,
Amount: coin.Amount.String(),
},
}
return json.Marshal(res)
}
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown BankQuery variant"}
}
}
func NoCustomQuerier(sdk.Context, json.RawMessage) ([]byte, error) {
return nil, wasmvmtypes.UnsupportedRequest{Kind: "custom"}
}
func CustomQuerierImpl(queryRouter GRPCQueryRouter) func(ctx sdk.Context, querierJson json.RawMessage) ([]byte, error) {
return func(ctx sdk.Context, querierJson json.RawMessage) ([]byte, error) {
var linkQueryWrapper types.LinkQueryWrapper
err := json.Unmarshal(querierJson, &linkQueryWrapper)
if err != nil {
return nil, err
}
route := queryRouter.Route(linkQueryWrapper.Path)
if route == nil {
return nil, wasmvmtypes.UnsupportedRequest{Kind: "Unknown encode module"}
}
req := abci.RequestQuery{
Data: linkQueryWrapper.Data,
Path: linkQueryWrapper.Path,
}
res, err := route(ctx, req)
if err != nil {
return nil, err
}
return res.Value, nil
}
}
func IBCQuerier(wasm contractMetaDataSource, channelKeeper types.ChannelKeeper) func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) {
return func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) {
if request.PortID != nil {
contractInfo := wasm.GetContractInfo(ctx, caller)
res := wasmvmtypes.PortIDResponse{
PortID: contractInfo.IBCPortID,
}
return json.Marshal(res)
}
if request.ListChannels != nil {
portID := request.ListChannels.PortID
channels := make(wasmvmtypes.IBCChannels, 0)
channelKeeper.IterateChannels(ctx, func(ch channeltypes.IdentifiedChannel) bool {
// it must match the port and be in open state
if (portID == "" || portID == ch.PortId) && ch.State == channeltypes.OPEN {
newChan := wasmvmtypes.IBCChannel{
Endpoint: wasmvmtypes.IBCEndpoint{
PortID: ch.PortId,
ChannelID: ch.ChannelId,
},
CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{
PortID: ch.Counterparty.PortId,
ChannelID: ch.Counterparty.ChannelId,
},
Order: ch.Ordering.String(),
Version: ch.Version,
ConnectionID: ch.ConnectionHops[0],
}
channels = append(channels, newChan)
}
return false
})
res := wasmvmtypes.ListChannelsResponse{
Channels: channels,
}
return json.Marshal(res)
}
if request.Channel != nil {
channelID := request.Channel.ChannelID
portID := request.Channel.PortID
if portID == "" {
contractInfo := wasm.GetContractInfo(ctx, caller)
portID = contractInfo.IBCPortID
}
got, found := channelKeeper.GetChannel(ctx, portID, channelID)
var channel *wasmvmtypes.IBCChannel
// it must be in open state
if found && got.State == channeltypes.OPEN {
channel = &wasmvmtypes.IBCChannel{
Endpoint: wasmvmtypes.IBCEndpoint{
PortID: portID,
ChannelID: channelID,
},
CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{
PortID: got.Counterparty.PortId,
ChannelID: got.Counterparty.ChannelId,
},
Order: got.Ordering.String(),
Version: got.Version,
ConnectionID: got.ConnectionHops[0],
}
}
res := wasmvmtypes.ChannelResponse{
Channel: channel,
}
return json.Marshal(res)
}
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown IBCQuery variant"}
}
}
// RejectStargateQuerier rejects all stargate queries
func RejectStargateQuerier() func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) {
return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) {
return nil, wasmvmtypes.UnsupportedRequest{Kind: "Stargate queries are disabled"}
}
}
// AcceptedStargateQueries define accepted Stargate queries as a map with path as key and response type as value.
// For example:
// acceptList["/cosmos.auth.v1beta1.Query/Account"]= &authtypes.QueryAccountResponse{}
type AcceptedStargateQueries map[string]codec.ProtoMarshaler
// AcceptListStargateQuerier supports a preconfigured set of stargate queries only.
// All arguments must be non nil.
//
// Warning: Chains need to test and maintain their accept list carefully.
// There were critical consensus breaking issues in the past with non-deterministic behaviour in the SDK.
//
// This queries can be set via WithQueryPlugins option in the wasm keeper constructor:
// WithQueryPlugins(&QueryPlugins{Stargate: AcceptListStargateQuerier(acceptList, queryRouter, codec)})
func AcceptListStargateQuerier(acceptList AcceptedStargateQueries, queryRouter GRPCQueryRouter, codec codec.Codec) func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) {
return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) {
protoResponse, accepted := acceptList[request.Path]
if !accepted {
return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("'%s' path is not allowed from the contract", request.Path)}
}
route := queryRouter.Route(request.Path)
if route == nil {
return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("No route to query '%s'", request.Path)}
}
res, err := route(ctx, abci.RequestQuery{
Data: request.Data,
Path: request.Path,
})
if err != nil {
return nil, err
}
return ConvertProtoToJSONMarshal(codec, protoResponse, res.Value)
}
}
func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKeeper) func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) {
return func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) {
if request.BondedDenom != nil {
denom := keeper.BondDenom(ctx)
res := wasmvmtypes.BondedDenomResponse{
Denom: denom,
}
return json.Marshal(res)
}
if request.AllValidators != nil {
validators := keeper.GetBondedValidatorsByPower(ctx)
// validators := keeper.GetAllValidators(ctx)
wasmVals := make([]wasmvmtypes.Validator, len(validators))
for i, v := range validators {
wasmVals[i] = wasmvmtypes.Validator{
Address: v.OperatorAddress,
Commission: v.Commission.Rate.String(),
MaxCommission: v.Commission.MaxRate.String(),
MaxChangeRate: v.Commission.MaxChangeRate.String(),
}
}
res := wasmvmtypes.AllValidatorsResponse{
Validators: wasmVals,
}
return json.Marshal(res)
}
if request.Validator != nil {
valAddr, err := sdk.ValAddressFromBech32(request.Validator.Address)
if err != nil {
return nil, err
}
v, found := keeper.GetValidator(ctx, valAddr)
res := wasmvmtypes.ValidatorResponse{}
if found {
res.Validator = &wasmvmtypes.Validator{
Address: v.OperatorAddress,
Commission: v.Commission.Rate.String(),
MaxCommission: v.Commission.MaxRate.String(),
MaxChangeRate: v.Commission.MaxChangeRate.String(),
}
}
return json.Marshal(res)
}
if request.AllDelegations != nil {
delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator)
}
sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator)
delegations, err := sdkToDelegations(ctx, keeper, sdkDels)
if err != nil {
return nil, err
}
res := wasmvmtypes.AllDelegationsResponse{
Delegations: delegations,
}
return json.Marshal(res)
}
if request.Delegation != nil {
delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator)
}
validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator)
}
var res wasmvmtypes.DelegationResponse
d, found := keeper.GetDelegation(ctx, delegator, validator)
if found {
res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d)
if err != nil {
return nil, err
}
}
return json.Marshal(res)
}
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Staking variant"}
}
}
func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations []stakingtypes.Delegation) (wasmvmtypes.Delegations, error) {
result := make([]wasmvmtypes.Delegation, len(delegations))
bondDenom := keeper.BondDenom(ctx)
for i, d := range delegations {
delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress)
if err != nil {
return nil, sdkerrors.Wrap(err, "delegator address")
}
valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress)
if err != nil {
return nil, sdkerrors.Wrap(err, "validator address")
}
// shares to amount logic comes from here:
// https://github.com/cosmos/cosmos-sdk/blob/v0.38.3/x/staking/keeper/querier.go#L404
val, found := keeper.GetValidator(ctx, valAddr)
if !found {
return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation")
}
amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt())
result[i] = wasmvmtypes.Delegation{
Delegator: delAddr.String(),
Validator: valAddr.String(),
Amount: ConvertSdkCoinToWasmCoin(amount),
}
}
return result, nil
}
func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) (*wasmvmtypes.FullDelegation, error) {
delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress)
if err != nil {
return nil, sdkerrors.Wrap(err, "delegator address")
}
valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)
if err != nil {
return nil, sdkerrors.Wrap(err, "validator address")
}
val, found := keeper.GetValidator(ctx, valAddr)
if !found {
return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation")
}
bondDenom := keeper.BondDenom(ctx)
amount := sdk.NewCoin(bondDenom, val.TokensFromShares(delegation.Shares).TruncateInt())
delegationCoins := ConvertSdkCoinToWasmCoin(amount)
// FIXME: this is very rough but better than nothing...
// https://github.com/CosmWasm/wasmd/issues/282
// if this (val, delegate) pair is receiving a redelegation, it cannot redelegate more
// otherwise, it can redelegate the full amount
// (there are cases of partial funds redelegated, but this is a start)
redelegateCoins := wasmvmtypes.NewCoin(0, bondDenom)
if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) {
redelegateCoins = delegationCoins
}
// FIXME: make a cleaner way to do this (modify the sdk)
// we need the info from `distKeeper.calculateDelegationRewards()`, but it is not public
// neither is `queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper)`
// so we go through the front door of the querier....
accRewards, err := getAccumulatedRewards(ctx, distKeeper, delegation)
if err != nil {
return nil, err
}
return &wasmvmtypes.FullDelegation{
Delegator: delAddr.String(),
Validator: valAddr.String(),
Amount: delegationCoins,
AccumulatedRewards: accRewards,
CanRedelegate: redelegateCoins,
}, nil
}
// FIXME: simplify this enormously when
// https://github.com/cosmos/cosmos-sdk/issues/7466 is merged
func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) {
// Try to get *delegator* reward info!
params := distributiontypes.QueryDelegationRewardsRequest{
DelegatorAddress: delegation.DelegatorAddress,
ValidatorAddress: delegation.ValidatorAddress,
}
cache, _ := ctx.CacheContext()
qres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), ¶ms)
if err != nil {
return nil, err
}
// now we have it, convert it into wasmvm types
rewards := make([]wasmvmtypes.Coin, len(qres.Rewards))
for i, r := range qres.Rewards {
rewards[i] = wasmvmtypes.Coin{
Denom: r.Denom,
Amount: r.Amount.TruncateInt().String(),
}
}
return rewards, nil
}
func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) {
return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) {
switch {
case request.Smart != nil:
addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr)
}
msg := types.RawContractMessage(request.Smart.Msg)
if err := msg.ValidateBasic(); err != nil {
return nil, sdkerrors.Wrap(err, "json msg")
}
return k.QuerySmart(ctx, addr, msg)
case request.Raw != nil:
addr, err := sdk.AccAddressFromBech32(request.Raw.ContractAddr)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr)
}
return k.QueryRaw(ctx, addr, request.Raw.Key), nil
case request.ContractInfo != nil:
addr, err := sdk.AccAddressFromBech32(request.ContractInfo.ContractAddr)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.ContractInfo.ContractAddr)
}
info := k.GetContractInfo(ctx, addr)
if info == nil {
return nil, &types.ErrNoSuchContract{Addr: request.ContractInfo.ContractAddr}
}
res := wasmvmtypes.ContractInfoResponse{
CodeID: info.CodeID,
Creator: info.Creator,
Admin: info.Admin,
Pinned: k.IsPinnedCode(ctx, info.CodeID),
IBCPort: info.IBCPortID,
}
return json.Marshal(res)
}
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"}
}
}
// ConvertSdkCoinsToWasmCoins covert sdk type to wasmvm coins type
func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {
converted := make(wasmvmtypes.Coins, len(coins))
for i, c := range coins {
converted[i] = ConvertSdkCoinToWasmCoin(c)
}
return converted
}
// ConvertSdkCoinToWasmCoin covert sdk type to wasmvm coin type
func ConvertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin {
return wasmvmtypes.Coin{
Denom: coin.Denom,
Amount: coin.Amount.String(),
}
}
// ConvertProtoToJSONMarshal unmarshals the given bytes into a proto message and then marshals it to json.
// This is done so that clients calling stargate queries do not need to define their own proto unmarshalers,
// being able to use response directly by json marshalling, which is supported in cosmwasm.
func ConvertProtoToJSONMarshal(cdc codec.Codec, protoResponse codec.ProtoMarshaler, bz []byte) ([]byte, error) {
// unmarshal binary into stargate response data structure
err := cdc.Unmarshal(bz, protoResponse)
if err != nil {
return nil, sdkerrors.Wrap(err, "to proto")
}
bz, err = cdc.MarshalJSON(protoResponse)
if err != nil {
return nil, sdkerrors.Wrap(err, "to json")
}
return bz, nil
}
var _ WasmVMQueryHandler = WasmVMQueryHandlerFn(nil)
// WasmVMQueryHandlerFn is a helper to construct a function based query handler.
type WasmVMQueryHandlerFn func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error)
// HandleQuery delegates call into wrapped WasmVMQueryHandlerFn
func (w WasmVMQueryHandlerFn) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) {
return w(ctx, caller, request)
}