/
api.go
78 lines (62 loc) · 2.02 KB
/
api.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
package keeper
import (
"math"
cosmwasm "github.com/CosmWasm/wasmvm"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/terra-money/core/x/wasm/types"
)
func (k Keeper) getCosmWasmAPI(ctx sdk.Context) cosmwasm.GoAPI {
return cosmwasm.GoAPI{
HumanAddress: func(canon []byte) (humanAddr string, usedGas uint64, err error) {
humanizeCost := types.HumanizeWasmGasCost * types.GasMultiplier
err = sdk.VerifyAddressFormat(canon)
if err != nil {
return "", humanizeCost, nil
}
return sdk.AccAddress(canon).String(), humanizeCost, nil
},
CanonicalAddress: func(human string) (canonicalAddr []byte, usedGas uint64, err error) {
canonicalizeCost := types.CanonicalizeWasmGasCost * types.GasMultiplier
addr, err := sdk.AccAddressFromBech32(human)
if err != nil {
return nil, canonicalizeCost, err
}
return addr, canonicalizeCost, nil
},
}
}
// wasmGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier
type wasmGasMeter struct {
originalMeter sdk.GasMeter
gasMultiplier uint64
}
var _ cosmwasm.GasMeter = wasmGasMeter{}
func (m wasmGasMeter) GasConsumed() sdk.Gas {
return types.ToWasmVMGas(m.originalMeter.GasConsumed())
}
// return gas meter interface for wasm gas meter
func (k Keeper) getWasmVMGasMeter(ctx sdk.Context) wasmGasMeter {
return wasmGasMeter{
originalMeter: ctx.GasMeter(),
gasMultiplier: types.GasMultiplier,
}
}
// return remaining gas in wasm gas unit
func (k Keeper) getWasmVMGasRemaining(ctx sdk.Context) uint64 {
meter := ctx.GasMeter()
// avoid integer overflow
if meter.IsOutOfGas() {
return 0
}
// infinite gas meter with limit=0 and not out of gas
if meter.Limit() == 0 {
return math.MaxUint64
}
remaining := (meter.Limit() - meter.GasConsumed())
return types.ToWasmVMGas(remaining)
}
// converts contract gas usage to sdk gas and consumes it
func (k Keeper) consumeWasmVMGas(ctx sdk.Context, wasmVMGas uint64, descriptor string) {
consumed := types.FromWasmVMGas(wasmVMGas)
ctx.GasMeter().ConsumeGas(consumed, descriptor)
}