cosmos-sdk/plugins/counter/counter.go

99 lines
2.4 KiB
Go
Raw Normal View History

package counter
import (
"fmt"
abci "github.com/tendermint/abci/types"
"github.com/tendermint/basecoin/types"
"github.com/tendermint/go-wire"
)
type CounterPluginState struct {
Counter int
2017-01-28 17:01:07 -08:00
TotalFees types.Coins
}
type CounterTx struct {
Valid bool
2017-01-28 17:01:07 -08:00
Fee types.Coins
}
//--------------------------------------------------------------------------------
type CounterPlugin struct {
}
func (cp *CounterPlugin) Name() string {
2017-02-12 19:01:17 -08:00
return "counter"
}
func (cp *CounterPlugin) StateKey() []byte {
2017-02-12 19:01:17 -08:00
return []byte(fmt.Sprintf("CounterPlugin.State"))
}
2017-02-07 13:12:18 -08:00
func New() *CounterPlugin {
2017-02-12 19:01:17 -08:00
return &CounterPlugin{}
}
func (cp *CounterPlugin) SetOption(store types.KVStore, key, value string) (log string) {
return ""
}
func (cp *CounterPlugin) RunTx(store types.KVStore, ctx types.CallContext, txBytes []byte) (res abci.Result) {
// Decode tx
var tx CounterTx
err := wire.ReadBinaryBytes(txBytes, &tx)
if err != nil {
2017-01-29 15:32:38 -08:00
return abci.ErrBaseEncodingError.AppendLog("Error decoding tx: " + err.Error()).PrependLog("CounterTx Error: ")
}
// Validate tx
if !tx.Valid {
return abci.ErrInternalError.AppendLog("CounterTx.Valid must be true")
}
2017-01-28 17:01:07 -08:00
if !tx.Fee.IsValid() {
return abci.ErrInternalError.AppendLog("CounterTx.Fee is not sorted or has zero amounts")
}
2017-01-28 17:01:07 -08:00
if !tx.Fee.IsNonnegative() {
return abci.ErrInternalError.AppendLog("CounterTx.Fee must be nonnegative")
}
// Did the caller provide enough coins?
2017-01-28 17:01:07 -08:00
if !ctx.Coins.IsGTE(tx.Fee) {
return abci.ErrInsufficientFunds.AppendLog("CounterTx.Fee was not provided")
}
// TODO If there are any funds left over, return funds.
2017-01-28 17:01:07 -08:00
// e.g. !ctx.Coins.Minus(tx.Fee).IsZero()
// ctx.CallerAccount is synced w/ store, so just modify that and store it.
// Load CounterPluginState
var cpState CounterPluginState
cpStateBytes := store.Get(cp.StateKey())
if len(cpStateBytes) > 0 {
err = wire.ReadBinaryBytes(cpStateBytes, &cpState)
if err != nil {
return abci.ErrInternalError.AppendLog("Error decoding state: " + err.Error())
}
}
// Update CounterPluginState
cpState.Counter += 1
2017-01-28 17:01:07 -08:00
cpState.TotalFees = cpState.TotalFees.Plus(tx.Fee)
// Save CounterPluginState
store.Set(cp.StateKey(), wire.BinaryBytes(cpState))
return abci.OK
}
func (cp *CounterPlugin) InitChain(store types.KVStore, vals []*abci.Validator) {
}
2017-02-04 14:47:51 -08:00
func (cp *CounterPlugin) BeginBlock(store types.KVStore, hash []byte, header *abci.Header) {
}
2017-02-04 14:47:51 -08:00
func (cp *CounterPlugin) EndBlock(store types.KVStore, height uint64) (res abci.ResponseEndBlock) {
return
}