> ## Documentation Index
> Fetch the complete documentation index at: https://cosmos-docs-sync-security-docs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Context

<Note>
  **Synopsis**
  The `context` is a data structure intended to be passed from function to function that carries information about the current state of the application. It provides access to a branched storage (a safe branch of the entire state) as well as useful objects and information like `gasMeter`, `block height`, `consensus parameters` and more.
</Note>

<Note>
  **Pre-requisite Readings**

  * [Anatomy of a Cosmos SDK Application](/sdk/v0.50/learn/beginner/app-anatomy)
  * [Lifecycle of a Transaction](/sdk/v0.50/learn/beginner/tx-lifecycle)
</Note>

## Context Definition

The Cosmos SDK `Context` is a custom data structure that contains Go's stdlib [`context`](https://pkg.go.dev/context) as its base, and has many additional types within its definition that are specific to the Cosmos SDK. The `Context` is integral to transaction processing in that it allows modules to easily access their respective [store](/sdk/v0.50/learn/advanced/store#base-layer-kvstores) in the [`multistore`](/sdk/v0.50/learn/advanced/store#multistore) and retrieve transactional context such as the block header and gas meter.

```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
package types

import (
    
	"context"
    "time"
    "cosmossdk.io/log"
	abci "github.com/cometbft/cometbft/abci/types"
	cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
    "github.com/cosmos/gogoproto/proto"
    "cosmossdk.io/store/gaskv"
	storetypes "cosmossdk.io/store/types"
    "cosmossdk.io/core/comet"
    "cosmossdk.io/core/header"
)

// ExecMode defines the execution mode which can be set on a Context.
type ExecMode uint8

// All possible execution modes.
const (
	ExecModeCheck ExecMode = iota
	ExecModeReCheck
	ExecModeSimulate
	ExecModePrepareProposal
	ExecModeProcessProposal
	ExecModeVoteExtension
	ExecModeFinalize
)

/*
Context is an immutable object contains all information needed to
process a request.

It contains a context.Context object inside if you want to use that,
but please do not over-use it. We try to keep all data structured
and standard additions here would be better just to add to the Context struct
*/
type Context struct {
    baseCtx context.Context
	ms      storetypes.MultiStore
	// Deprecated: Use HeaderService for height, time, and chainID and CometService for the rest
	header cmtproto.Header
	// Deprecated: Use HeaderService for hash
	headerHash []byte
	// Deprecated: Use HeaderService for chainID and CometService for the rest
	chainID              string
	txBytes              []byte
	logger               log.Logger
	voteInfo             []abci.VoteInfo
	gasMeter             storetypes.GasMeter
	blockGasMeter        storetypes.GasMeter
	checkTx              bool
	recheckTx            bool // if recheckTx == true, then checkTx must also be true
	execMode             ExecMode
	minGasPrice          DecCoins
	consParams           cmtproto.ConsensusParams
	eventManager         EventManagerI
	priority             int64 // The tx priority, only relevant in CheckTx
	kvGasConfig          storetypes.GasConfig
	transientKVGasConfig storetypes.GasConfig
	streamingManager     storetypes.StreamingManager
	cometInfo            comet.BlockInfo
	headerInfo           header.Info
}

// Proposed rename, not done to avoid API breakage
type Request = Context

// Read-only accessors
func (c Context)

Context()

context.Context                      {
    return c.baseCtx
}

func (c Context)

MultiStore()

storetypes.MultiStore             {
    return c.ms
}

func (c Context)

BlockHeight()

int64                            {
    return c.header.Height
}

func (c Context)

BlockTime()

time.Time                          {
    return c.header.Time
}

func (c Context)

ChainID()

string                               {
    return c.chainID
}

func (c Context)

TxBytes() []byte                               {
    return c.txBytes
}

func (c Context)

Logger()

log.Logger                            {
    return c.logger
}

func (c Context)

VoteInfos() []abci.VoteInfo                    {
    return c.voteInfo
}

func (c Context)

GasMeter()

storetypes.GasMeter                 {
    return c.gasMeter
}

func (c Context)

BlockGasMeter()

storetypes.GasMeter            {
    return c.blockGasMeter
}

func (c Context)

IsCheckTx()

bool                               {
    return c.checkTx
}

func (c Context)

IsReCheckTx()

bool                             {
    return c.recheckTx
}

func (c Context)

ExecMode()

ExecMode                            {
    return c.execMode
}

func (c Context)

MinGasPrices()

DecCoins                        {
    return c.minGasPrice
}

func (c Context)

EventManager()

EventManagerI                   {
    return c.eventManager
}

func (c Context)

Priority()

int64                               {
    return c.priority
}

func (c Context)

KVGasConfig()

storetypes.GasConfig             {
    return c.kvGasConfig
}

func (c Context)

TransientKVGasConfig()

storetypes.GasConfig    {
    return c.transientKVGasConfig
}

func (c Context)

StreamingManager()

storetypes.StreamingManager {
    return c.streamingManager
}

func (c Context)

CometInfo()

comet.BlockInfo                    {
    return c.cometInfo
}

func (c Context)

HeaderInfo()

header.Info                       {
    return c.headerInfo
}

// clone the header before returning
func (c Context)

BlockHeader()

cmtproto.Header {
    msg := proto.Clone(&c.header).(*cmtproto.Header)

return *msg
}

// HeaderHash returns a copy of the header hash obtained during abci.RequestBeginBlock
func (c Context)

HeaderHash() []byte {
    hash := make([]byte, len(c.headerHash))

copy(hash, c.headerHash)

return hash
}

func (c Context)

ConsensusParams()

cmtproto.ConsensusParams {
    return c.consParams
}

func (c Context)

Deadline() (deadline time.Time, ok bool) {
    return c.baseCtx.Deadline()
}

func (c Context)

Done() <-chan struct{
} {
    return c.baseCtx.Done()
}

func (c Context)

Err()

error {
    return c.baseCtx.Err()
}

// create a new context
func NewContext(ms storetypes.MultiStore, header cmtproto.Header, isCheckTx bool, logger log.Logger)

Context {
	// https://github.com/gogo/protobuf/issues/519
	header.Time = header.Time.UTC()

return Context{
    baseCtx:              context.Background(),
		ms:                   ms,
		header:               header,
		chainID:              header.ChainID,
		checkTx:              isCheckTx,
		logger:               logger,
		gasMeter:             storetypes.NewInfiniteGasMeter(),
		minGasPrice:          DecCoins{
},
		eventManager:         NewEventManager(),
		kvGasConfig:          storetypes.KVGasConfig(),
		transientKVGasConfig: storetypes.TransientGasConfig(),
}
}

// WithContext returns a Context with an updated context.Context.
func (c Context)

WithContext(ctx context.Context)

Context {
    c.baseCtx = ctx
	return c
}

// WithMultiStore returns a Context with an updated MultiStore.
func (c Context)

WithMultiStore(ms storetypes.MultiStore)

Context {
    c.ms = ms
	return c
}

// WithBlockHeader returns a Context with an updated CometBFT block header in UTC time.
func (c Context)

WithBlockHeader(header cmtproto.Header)

Context {
	// https://github.com/gogo/protobuf/issues/519
	header.Time = header.Time.UTC()

c.header = header
	return c
}

// WithHeaderHash returns a Context with an updated CometBFT block header hash.
func (c Context)

WithHeaderHash(hash []byte)

Context {
    temp := make([]byte, len(hash))

copy(temp, hash)

c.headerHash = temp
	return c
}

// WithBlockTime returns a Context with an updated CometBFT block header time in UTC with no monotonic component.
// Stripping the monotonic component is for time equality.
func (c Context)

WithBlockTime(newTime time.Time)

Context {
    newHeader := c.BlockHeader()
	// https://github.com/gogo/protobuf/issues/519
	newHeader.Time = newTime.Round(0).UTC()

return c.WithBlockHeader(newHeader)
}

// WithProposer returns a Context with an updated proposer consensus address.
func (c Context)

WithProposer(addr ConsAddress)

Context {
    newHeader := c.BlockHeader()

newHeader.ProposerAddress = addr.Bytes()

return c.WithBlockHeader(newHeader)
}

// WithBlockHeight returns a Context with an updated block height.
func (c Context)

WithBlockHeight(height int64)

Context {
    newHeader := c.BlockHeader()

newHeader.Height = height
	return c.WithBlockHeader(newHeader)
}

// WithChainID returns a Context with an updated chain identifier.
func (c Context)

WithChainID(chainID string)

Context {
    c.chainID = chainID
	return c
}

// WithTxBytes returns a Context with an updated txBytes.
func (c Context)

WithTxBytes(txBytes []byte)

Context {
    c.txBytes = txBytes
	return c
}

// WithLogger returns a Context with an updated logger.
func (c Context)

WithLogger(logger log.Logger)

Context {
    c.logger = logger
	return c
}

// WithVoteInfos returns a Context with an updated consensus VoteInfo.
func (c Context)

WithVoteInfos(voteInfo []abci.VoteInfo)

Context {
    c.voteInfo = voteInfo
	return c
}

// WithGasMeter returns a Context with an updated transaction GasMeter.
func (c Context)

WithGasMeter(meter storetypes.GasMeter)

Context {
    c.gasMeter = meter
	return c
}

// WithBlockGasMeter returns a Context with an updated block GasMeter
func (c Context)

WithBlockGasMeter(meter storetypes.GasMeter)

Context {
    c.blockGasMeter = meter
	return c
}

// WithKVGasConfig returns a Context with an updated gas configuration for
// the KVStore
func (c Context)

WithKVGasConfig(gasConfig storetypes.GasConfig)

Context {
    c.kvGasConfig = gasConfig
	return c
}

// WithTransientKVGasConfig returns a Context with an updated gas configuration for
// the transient KVStore
func (c Context)

WithTransientKVGasConfig(gasConfig storetypes.GasConfig)

Context {
    c.transientKVGasConfig = gasConfig
	return c
}

// WithIsCheckTx enables or disables CheckTx value for verifying transactions and returns an updated Context
func (c Context)

WithIsCheckTx(isCheckTx bool)

Context {
    c.checkTx = isCheckTx
	c.execMode = ExecModeCheck
	return c
}

// WithIsRecheckTx called with true will also set true on checkTx in order to
// enforce the invariant that if recheckTx = true then checkTx = true as well.
func (c Context)

WithIsReCheckTx(isRecheckTx bool)

Context {
    if isRecheckTx {
    c.checkTx = true
}

c.recheckTx = isRecheckTx
	c.execMode = ExecModeReCheck
	return c
}

// WithExecMode returns a Context with an updated ExecMode.
func (c Context)

WithExecMode(m ExecMode)

Context {
    c.execMode = m
	return c
}

// WithMinGasPrices returns a Context with an updated minimum gas price value
func (c Context)

WithMinGasPrices(gasPrices DecCoins)

Context {
    c.minGasPrice = gasPrices
	return c
}

// WithConsensusParams returns a Context with an updated consensus params
func (c Context)

WithConsensusParams(params cmtproto.ConsensusParams)

Context {
    c.consParams = params
	return c
}

// WithEventManager returns a Context with an updated event manager
func (c Context)

WithEventManager(em EventManagerI)

Context {
    c.eventManager = em
	return c
}

// WithPriority returns a Context with an updated tx priority
func (c Context)

WithPriority(p int64)

Context {
    c.priority = p
	return c
}

// WithStreamingManager returns a Context with an updated streaming manager
func (c Context)

WithStreamingManager(sm storetypes.StreamingManager)

Context {
    c.streamingManager = sm
	return c
}

// WithCometInfo returns a Context with an updated comet info
func (c Context)

WithCometInfo(cometInfo comet.BlockInfo)

Context {
    c.cometInfo = cometInfo
	return c
}

// WithHeaderInfo returns a Context with an updated header info
func (c Context)

WithHeaderInfo(headerInfo header.Info)

Context {
	// Settime to UTC
	headerInfo.Time = headerInfo.Time.UTC()

c.headerInfo = headerInfo
	return c
}

// TODO: remove???
func (c Context)

IsZero()

bool {
    return c.ms == nil
}

func (c Context)

WithValue(key, value interface{
})

Context {
    c.baseCtx = context.WithValue(c.baseCtx, key, value)

return c
}

func (c Context)

Value(key interface{
})

interface{
} {
    if key == SdkContextKey {
    return c
}

return c.baseCtx.Value(key)
}

// ----------------------------------------------------------------------------
// Store / Caching
// ----------------------------------------------------------------------------

// KVStore fetches a KVStore from the MultiStore.
func (c Context)

KVStore(key storetypes.StoreKey)

storetypes.KVStore {
    return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.kvGasConfig)
}

// TransientStore fetches a TransientStore from the MultiStore.
func (c Context)

TransientStore(key storetypes.StoreKey)

storetypes.KVStore {
    return gaskv.NewStore(c.ms.GetKVStore(key), c.gasMeter, c.transientKVGasConfig)
}

// CacheContext returns a new Context with the multi-store cached and a new
// EventManager. The cached context is written to the context when writeCache
// is called. Note, events are automatically emitted on the parent context's
// EventManager when the caller executes the write.
func (c Context)

CacheContext() (cc Context, writeCache func()) {
    cms := c.ms.CacheMultiStore()

cc = c.WithMultiStore(cms).WithEventManager(NewEventManager())

writeCache = func() {
    c.EventManager().EmitEvents(cc.EventManager().Events())

cms.Write()
}

return cc, writeCache
}

var (
	_ context.Context    = Context{
}
	_ storetypes.Context = Context{
}
)

// ContextKey defines a type alias for a stdlib Context key.
type ContextKey string

// SdkContextKey is the key in the context.Context which holds the sdk.Context.
const SdkContextKey ContextKey = "sdk-context"

// WrapSDKContext returns a stdlib context.Context with the provided sdk.Context's internal
// context as a value. It is useful for passing an sdk.Context  through methods that take a
// stdlib context.Context parameter such as generated gRPC methods. To get the original
// sdk.Context back, call UnwrapSDKContext.
//
// Deprecated: there is no need to wrap anymore as the Cosmos SDK context implements context.Context.
func WrapSDKContext(ctx Context)

context.Context {
    return ctx
}

// UnwrapSDKContext retrieves a Context from a context.Context instance
// attached with WrapSDKContext. It panics if a Context was not properly
// attached
func UnwrapSDKContext(ctx context.Context)

Context {
    if sdkCtx, ok := ctx.(Context); ok {
    return sdkCtx
}

return ctx.Value(SdkContextKey).(Context)
}
```

* **Base Context:** The base type is a Go [Context](https://pkg.go.dev/context), which is explained further in the [Go Context Package](#go-context-package) section below.
* **Multistore:** Every application's `BaseApp` contains a [`CommitMultiStore`](/sdk/v0.50/learn/advanced/store#multistore) which is provided when a `Context` is created. Calling the `KVStore()` and `TransientStore()` methods allows modules to fetch their respective [`KVStore`](/sdk/v0.50/learn/advanced/store#base-layer-kvstores) using their unique `StoreKey`.
* **Header:** The [header](/cometbft/v0.38/spec/core/Data_structures#header) is a Blockchain type. It carries important information about the state of the blockchain, such as block height and proposer of the current block.
* **Header Hash:** The current block header hash, obtained during `abci.FinalizeBlock`.
* **Chain ID:** The unique identification number of the blockchain a block pertains to.
* **Transaction Bytes:** The `[]byte` representation of a transaction being processed using the context. Every transaction is processed by various parts of the Cosmos SDK and consensus engine (e.g. CometBFT) throughout its [lifecycle](/sdk/v0.50/learn/beginner/tx-lifecycle), some of which do not have any understanding of transaction types. Thus, transactions are marshaled into the generic `[]byte` type using some kind of [encoding format](/sdk/v0.50/learn/advanced/encoding) such as [Amino](/sdk/v0.50/learn/advanced/encoding).
* **Logger:** A `logger` from the CometBFT libraries. Learn more about logs [here](/cometbft/v0.38/docs/core/configuration). Modules call this method to create their own unique module-specific logger.
* **VoteInfo:** A list of the ABCI type [`VoteInfo`](/cometbft/v0.38/spec/abci/Methods#voteinfo), which includes the name of a validator and a boolean indicating whether they have signed the block.
* **Gas Meters:** Specifically, a [`gasMeter`](/sdk/v0.50/learn/beginner/gas-fees#main-gas-meter) for the transaction currently being processed using the context and a [`blockGasMeter`](/sdk/v0.50/learn/beginner/gas-fees#block-gas-meter) for the entire block it belongs to. Users specify how much in fees they wish to pay for the execution of their transaction; these gas meters keep track of how much [gas](/sdk/v0.50/learn/beginner/gas-fees) has been used in the transaction or block so far. If the gas meter runs out, execution halts.
* **CheckTx Mode:** A boolean value indicating whether a transaction should be processed in `CheckTx` or `DeliverTx` mode.
* **Min Gas Price:** The minimum [gas](/sdk/v0.50/learn/beginner/gas-fees) price a node is willing to take in order to include a transaction in its block. This price is a local value configured by each node individually, and should therefore **not be used in any functions used in sequences leading to state-transitions**.
* **Consensus Params:** The ABCI type [Consensus Parameters](/cometbft/v0.38/spec/abci/Methods#consensus-parameters), which specify certain limits for the blockchain, such as maximum gas for a block.
* **Event Manager:** The event manager allows any caller with access to a `Context` to emit [`Events`](/sdk/v0.50/learn/advanced/events). Modules may define module specific
  `Events` by defining various `Types` and `Attributes` or use the common definitions found in `types/`. Clients can subscribe or query for these `Events`. These `Events` are collected throughout `FinalizeBlock` and are returned to CometBFT for indexing.
* **Priority:** The transaction priority, only relevant in `CheckTx`.
* **KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the `KVStore`.
* **Transient KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the transiant `KVStore`.
* **StreamingManager:** The streamingManager field provides access to the streaming manager, which allows modules to subscribe to state changes emitted by the blockchain. The streaming manager is used by the state listening API, which is described in [ADR 038](/sdk/v0.53/build/architecture/adr-038-state-listening).
* **CometInfo:** A lightweight field that contains information about the current block, such as the block height, time, and hash. This information can be used for validating evidence, providing historical data, and enhancing the user experience. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/comet/service.go#L14).
* **HeaderInfo:** The `headerInfo` field contains information about the current block header, such as the chain ID, gas limit, and timestamp. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/header/service.go#L14).

## Go Context Package

A basic `Context` is defined in the [Golang Context Package](https://pkg.go.dev/context). A `Context`
is an immutable data structure that carries request-scoped data across APIs and processes. Contexts
are also designed to enable concurrency and to be used in goroutines.

Contexts are intended to be **immutable**; they should never be edited. Instead, the convention is
to create a child context from its parent using a `With` function. For example:

```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
childCtx = parentCtx.WithBlockHeader(header)
```

The [Golang Context Package](https://pkg.go.dev/context) documentation instructs developers to
explicitly pass a context `ctx` as the first argument of a process.

## Store branching

The `Context` contains a `MultiStore`, which allows for branching and caching functionality using `CacheMultiStore`
(queries in `CacheMultiStore` are cached to avoid future round trips).
Each `KVStore` is branched in a safe and isolated ephemeral storage. Processes are free to write changes to
the `CacheMultiStore`. If a state-transition sequence is performed without issue, the store branch can
be committed to the underlying store at the end of the sequence or disregard them if something
goes wrong. The pattern of usage for a Context is as follows:

1. A process receives a Context `ctx` from its parent process, which provides information needed to
   perform the process.
2. The `ctx.ms` is a **branched store**, i.e. a branch of the [multistore](/sdk/v0.50/learn/advanced/store#multistore) is made so that the process can make changes to the state as it executes, without changing the original`ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution.
3. The process may read and write from `ctx` as it is executing. It may call a subprocess and pass
   `ctx` to it as needed.
4. When a subprocess returns, it checks if the result is a success or failure. If a failure, nothing
   needs to be done - the branch `ctx` is simply discarded. If successful, the changes made to
   the `CacheMultiStore` can be committed to the original `ctx.ms` via `Write()`.

For example, here is a snippet from the [`runTx`](/sdk/v0.50/learn/advanced/baseapp#runtx-antehandler-runmsgs-posthandler) function in [`baseapp`](/sdk/v0.50/learn/advanced/baseapp):

```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes)

result = app.runMsgs(runMsgCtx, msgs, mode)

result.GasWanted = gasWanted
    if mode != runTxModeDeliver {
    return result
}
    if result.IsOK() {
    msCache.Write()
}
```

Here is the process:

1. Prior to calling `runMsgs` on the message(s) in the transaction, it uses `app.cacheTxContext()`
   to branch and cache the context and multistore.
2. `runMsgCtx` - the context with branched store, is used in `runMsgs` to return a result.
3. If the process is running in [`checkTxMode`](/sdk/v0.50/learn/advanced/baseapp#checktx), there is no need to write the
   changes - the result is returned immediately.
4. If the process is running in [`deliverTxMode`](/sdk/v0.50/learn/advanced/baseapp#delivertx) and the result indicates
   a successful run over all the messages, the branched multistore is written back to the original.
