# Migrating from sdk.Context to Core Services
## Overview
This document outlines the migration process from the `sdk.Context` in the Cosmos SDK to the new core services architecture. The new approach eliminates the need for context unwrapping and introduces an `appmodule.Environment` struct, in cosmossdk.io/core v1, that contains all core services.
## Key Changes
1. The `sdk.Context` is being phased out in favor of core services.
2. An `Environment` struct now contains all core services.
3. Context unwrapping is no longer necessary.
4. The migration is required before using `runtime/v2`.
## Migration Guide
### 1. Replace Context with Environment
Instead of using `sdk.Context`, your modules should now use the `Environment` struct. This struct provides access to all core services.
### 2. Mapping of Context Methods to Core Services
The following table shows the mapping between common `sdk.Context` methods and their corresponding core services:
| Old (sdk.Context) | New (Core Service) |
| -------------------- | -------------------------------------- |
| `ctx.ExecMode()` | `TransactionService` |
| `ctx.HeaderInfo()` | `HeaderService` |
| `ctx.GasMeter()` | `GasService` |
| `ctx.EventManager()` | `EventService` |
| `ctx.KVStore` | `KVStoreService` / `MemKVStoreService` |
| `ctx.CacheContext` | `BranchService` |
Additionally some services have been created to replace other components that weren't on `sdk.Context`
| Old | New (Core Service) |
| ----------------------- | -------------------- |
| `baseapp.MessageRouter` | `MsgRouterService` |
| `baseapp.QueryRouter` | `QueryRouterService` |
### 3. Updating Your Code
Embed the environment in your keeper struct:
```go
type Keeper struct {
appmodule.Environment
// ...
}
```
Replace calls to `sdk.Context` methods with the appropriate core service from the `Environment` struct. For example:
```go
// Old
func (k Keeper) MyMethod(ctx sdk.Context) {
mode := ctx.ExecMode()
headerInfo := ctx.HeaderInfo()
// ...
}
// New
func (k Keeper) MyMethod(ctx context.Context) {
mode := k.TransactionService..ExecMode(ctx)
headerInfo := k.HeaderService.HeaderInfo(ctx)
// ...
}
```
### 4. Advantages of the New Approach
- **Improved Modularity**: Core services are now decoupled from the context, allowing for better separation of concerns.
- **Enhanced Testability**: Easier to mock individual services for unit testing.
- **Clearer Dependencies**: The `Environment` struct makes it explicit what a module can use.
## Conclusion
Migrating from `sdk.Context` to core services via the `Environment` struct simplifies the Cosmos SDK architecture and provides more flexibility for developers. By following this guide, you can update your modules to use the new core services effectively.