cron

package
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2024 License: Apache-2.0 Imports: 19 Imported by: 0

README

Cron

Abstract

This module enables smart contracts on chain to receive callbacks at the beginning and end of each block. Useful for scheduling actions which need to happen every block.

Concepts

Priviledged contracts

An existing contract instantiated on chain which has been elevated to the status of priviledged contract via on-chain governance proposal or via whitelisted admin addresses. Privileged contracts receive some extra superpowers where they can receive callbacks from the BeginBlocker & EndBlocker into their sudo entrypoint. More details on how to use this in here

State

The module state is quite simple. It stores the bech32 address of all the Cosmwasm smart contracts that have been elevated via governance or admins. Once the contract priviledge is demoted via governance, it is removed from state.

Storage keys:

  • PriviledgedContract: 0x01 | contractAddress -> []byte{1}

Params

  • AdminAddress: List of sdk.AccAddress for accounts which are whitelisted to promote and demote contracts

Begin Blockers

In the ABCI beginblock, the module fetches the list of all priviledged contracts and loops through them and calls the sudo entry point with the BeginBlocker msg. None of the abci.RequestBeginBlock values are passed in.

End Blockers

In the ABCI endblock, the module fetches the list of all priviledged contracts and loops through them and calls the sudo entry point with the EndBlocker msg.

Events

The module emits the following events:

Source type Source name
Keeper SetContractPriviledge
Keeper UnsetContractPriviledge

Client

CLI - Query
list-privileged
starsd q cron list-privileged

List all privileged contract addresses in bech32 format

params
starsd q cron params

List the module params

CLI - Gov
starsd tx gov submit-proposal proposal.json --from {user}

You will need the x/gov module address to set as authority for the proposal. You can fetch it by running:

starsd q auth module-account gov

This will get you the following response

account:
  '@type': /cosmos.auth.v1beta1.ModuleAccount
  base_account:
    account_number: "7"
    address: stars10d07y265gmmuvt4z0w9aw880jnsr700jw7ycaz // This is the address you need to use for authority value
    pub_key: null
    sequence: "0"
  name: gov
  permissions:
  - burner

The expected format of the proposal.json is below.

Promote Contract
{
    "messages": [
     {
      "@type": "/publicawesome.stargaze.cron.v1.MsgPromoteToPrivilegedContract",
      "authority": "stars10d07y265gmmuvt4z0w9aw880jnsr700jw7ycaz", // x/gov address
      "contract": "stars14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9srsl6sm" // the contract to promote
     }
    ],
    "metadata": "metadata",
    "deposit": "1000stake",
    "title": "Promote contract",
    "summary": "Contract will get begin and end blocker callbacks"
}
Demote Contract
{
    "messages": [
     {
      "@type": "/publicawesome.stargaze.cron.v1.MsgDemoteFromPrivilegedContract",
      "authority": "stars10d07y265gmmuvt4z0w9aw880jnsr700jw7ycaz", // x/gov address
      "contract": "stars14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9srsl6sm" // the contract to demote
     }
    ],
    "metadata": "metadata",
    "deposit": "1000stake",
    "title": "Demote contract",
    "summary": "Contract will lose begin and end blocker callbacks"
}
Update Params
{
    "messages": [
     {
      "@type": "/publicawesome.stargaze.cron.v1.MsgUpdateParams",
      "authority": "stars10d07y265gmmuvt4z0w9aw880jnsr700jw7ycaz", // x/gov address
      "params": { // note: the entire params field needs to be filled
        "admin_address": [
            "stars1mzgucqnfr2l8cj5apvdpllhzt4zeuh2cyt4fdd" 
        ]
      }
     }
    ],
    "metadata": "metadata",
    "deposit": "1000stake",
    "title": "Update module params",
    "summary": "This will add or remove the module admins"
}
CLI - Tx

Note Only whitelisted admin addresses can execute the following txs

promote-to-privilege-contract || promote-contract
starsd tx cron promote-contract {contractAddr} --from {adminUser}
starsd tx cron promote-contract stars19jq6mj84cnt9p7sagjxqf8hxtczwc8wlpuwe4sh62w45aheseues57n420 --from admin

Immediately adds the given contract address to the priviledged contract list

demote-from-privilege-contract || demote-contract
starsd tx cron demote-contract {contractAddr} --from {adminUser}
starsd tx cron demote-contract stars19jq6mj84cnt9p7sagjxqf8hxtczwc8wlpuwe4sh62w45aheseues57n420 --from admin

Immediately removes the given contract address to the priviledged contract list

How to use in CW contract

To use the BeginBlocker & EndBlocker callback from this module, you need to add the following msg type to your contract msgs.

// msg.rs

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SudoMsg {
    BeginBlock {},
    EndBlock {},
}
// contract.rs

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn sudo(deps: DepsMut, env: Env, msg: SudoMsg) -> Result<Response, ContractError> {
    match msg {
        SudoMsg::BeginBlock {} => !unimplemented(),
        SudoMsg::EndBlock {} => !unimplemented(),
    }
}

Ensure you have a sudo entrypoint in your contract and add your code to be called by the SudoMsg::BeginBlock & SudoMsg::EndBlock. Both endpoints are hit for every privileged contract in the block lifecycle, so ensure both are implemented.

This endpoint is hit at the beginning and end of every block by the x/cron module. The deps and env values are set as expected. It is not possible to receive any input in the BeginBlock & EndBlock call and as such the contract must maintain any relevant state it needs to use.

Attribution

Thanks to Confio and the Tgrade open source project for providing a base for x/cron where most of it's bits were extracted and adapted to only do begin_blocker & end_blocker callbacks.

Found more about Tgrade's twasm module:

x/twasm

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BeginBlocker

func BeginBlocker(ctx sdk.Context, k keeper.Keeper, w types.WasmKeeper)

BeginBlocker sends a BeginBlock SudoMsg to all privileged contracts

func EndBlocker

func EndBlocker(ctx sdk.Context, k keeper.Keeper, w types.WasmKeeper) []abci.ValidatorUpdate

EndBlocker sends a EndBlock SudoMsg to all privileged contracts

func ExportGenesis

func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState

ExportGenesis returns the module's exported genesis

func InitGenesis

func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState)

InitGenesis initializes the module's state from a provided genesis state.

func RecoverToLog

func RecoverToLog(logger log.Logger, contractAddr sdk.AccAddress) func()

RecoverToLog catches panic and logs cause to error

Types

type AppModule

type AppModule struct {
	AppModuleBasic
	// contains filtered or unexported fields
}

AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement

func NewAppModule

func NewAppModule(
	cdc codec.Codec,
	keeper keeper.Keeper,
	wasmKeeper types.WasmKeeper,
) AppModule

func (AppModule) BeginBlock

func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock)

BeginBlock contains the logic that is automatically triggered at the beginning of each block

func (AppModule) ConsensusVersion

func (AppModule) ConsensusVersion() uint64

ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1

func (AppModule) EndBlock

EndBlock contains the logic that is automatically triggered at the end of each block

func (AppModule) ExportGenesis

func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage

ExportGenesis returns the module's exported genesis state as raw JSON bytes.

func (AppModule) InitGenesis

func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate

InitGenesis performs the module's genesis initialization. It returns no validator updates.

func (AppModule) QuerierRoute deprecated

func (AppModule) QuerierRoute() string

Deprecated: use RegisterServices

func (AppModule) RegisterInvariants

func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry)

RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted)

func (AppModule) RegisterServices

func (am AppModule) RegisterServices(cfg module.Configurator)

RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries

type AppModuleBasic

type AppModuleBasic struct {
	// contains filtered or unexported fields
}

AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement.

func NewAppModuleBasic

func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic

func (AppModuleBasic) DefaultGenesis

func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage

DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage. The default GenesisState need to be defined by the module developer and is primarily used for testing

func (AppModuleBasic) GetQueryCmd

func (AppModuleBasic) GetQueryCmd() *cobra.Command

GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module

func (AppModuleBasic) GetTxCmd

func (a AppModuleBasic) GetTxCmd() *cobra.Command

GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module

func (AppModuleBasic) Name

func (AppModuleBasic) Name() string

Name returns the name of the module as a string

func (AppModuleBasic) RegisterGRPCGatewayRoutes

func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux)

RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module

func (AppModuleBasic) RegisterInterfaces

func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry)

RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message

func (AppModuleBasic) RegisterLegacyAminoCodec

func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)

RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore

func (AppModuleBasic) ValidateGenesis

ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form

Directories

Path Synopsis
client
cli
Package types is a reverse proxy.
Package types is a reverse proxy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL