Design overview
This guide is for Rust smart contract developers who already know CosmWasm and want to make sound Solana architecture decisions instead of trying to preserve patterns that do not translate cleanly. Four Solana concepts shape the whole rewrite: a program is executable onchain code, an account is the state object the runtime stores and loads, an instruction is a request to run one program handler, and a transaction is the signed bundle of instructions that succeeds or fails atomically. Before touching code, internalize the two chains’ core bets:| Dimension | CosmWasm | Solana / Anchor |
|---|---|---|
| Scaling strategy | Horizontal app-chain ecosystem connected by IBC | One high-throughput chain with parallel execution |
| Typical block cadence | Seconds | Sub-second slots, which are Solana’s leader-scheduled time windows |
| Execution VM | WASM bytecode | sBPF bytecode, Solana’s executable program format |
| Nondeterminism | Disallowed | Disallowed |
| Contract instances | Many instances per uploaded code | One deployed program; many state accounts |
| Scaling consequence | Application isolation by chain | Parallel execution through explicit account locks |
The fundamental shift: The account model
This is the hardest concept to internalize and the one that explains almost every other difference.CosmWasm mental model
Terminal
deps.storage is the contract’s private namespace.
Solana mental model
Terminal
Why this matters in practice
- A CosmWasm factory often stores deployed child addresses. A Solana program usually derives addresses deterministically instead of storing them.
- A CosmWasm contract owns one isolated KV store. A Solana program looks more like a database engine that defines schemas and rules for many rows stored as separate accounts.
- Transactions declare all accounts they will read or write. That declaration is what unlocks parallelism.
Program Derived Addresses
Program Derived Addresses (PDAs) are the cornerstone of Solana state management. They are deterministic, off-curve account addresses derived from seeds plus the program ID and a bump seed. “Off-curve” means no private key exists for the address, so only the deriving program can sign for it through the runtime. One note before the first program snippet: Solana has several frameworks for writing programs. This guide’s Rust examples use Anchor, a framework that expands declarative macros like#[derive(Accounts)] and #[account(...)] into the
account-validation and serialization code you would otherwise write by hand.
Anchor is the most widely used choice, but not the only one: you can also build
with the lower-level Pinocchio or with
no framework at all; the Toolchain section compares the
options.
Solana PDA
Cosmos map lookup
Client-side derivation
The derivation is not program-only: any client can compute the same address off-chain and fetch the account directly, so frontends and indexers never need an on-chain registry. With @solana/kit, the TypeScript equivalent of the seeds above is:Project structure & toolchain
CosmWasm and Solana are both Rust ecosystems, but the build pipeline, deployment model, and testing workflow differ substantially. Solana programs compile to sBPF, the Solana bytecode format executed by the runtime.CosmWasm toolchain
Terminal
cosmwasm-std, cw-storage-plus, cw-multi-test, and thiserror.
Solana toolchain options
Most Solana Rust teams choose between Anchor and Pinocchio. Both target Solana’s runtime, but they optimize for different tradeoffs.Anchor toolchain
Terminal
solana-program, anchor-lang, anchor-spl, and SPL
Token libraries such as spl-token.
Pinocchio toolchain
Terminal
Directory layout comparison
Entry points: Messages vs instructions
CosmWasm exposes distinct entry points for different classes of work. Native Solana exposes one instruction processor that you dispatch yourself, and Anchor rebuilds a multi-handler abstraction on top. There is no separate instantiate step on Solana. Initialization is just another instruction, usually one that creates state accounts and derives any PDA addresses they use. Queries are off-chain RPC reads, not on-chain handlers; clients fetch account data from an RPC node and decode it locally. Kit’s codecs give TypeScript clients composable decoders for turning those raw account bytes back into structured data.Compare the entry points
match on the first byte is Solana’s replacement for CosmWasm’s
ExecuteMsg enum dispatch: instruction data begins with a discriminator that
assigns the payload to a handler. In Pinocchio you define and read it yourself:
here a single byte. Anchor abstracts the same mechanism: it derives an 8-byte
discriminator from each handler’s name and routes on it automatically, which is
why the snippet below has no visible dispatch.
Anchor
State management: Contract storage vs PDAs
EveryItem or Map you used in CosmWasm needs an explicit account model on
Solana. In practice, each logical entry often becomes its own program-owned
account: an account whose owner
field is set to your program
ID, which lets your program write that account’s data.
Compare state management
Rent and space allocation
Solana storage is not abstracted away. Accounts must carry enough lamports, the smallest unit of SOL, to remain rent-exempt. Rent exemption means the account has the minimum balance required to stay onchain for its allocated data size, and you must allocate enough space up front for the layout you intend to store. Despite the name, rent is a refundable deposit, not a fee: the lamports sit escrowed in the account to hold its state and come back in full when the account is closed. The CLI prints the deposit for any data size: here 49 bytes, the 8-byte discriminator plusUserBalance::INIT_SPACE:
Terminal
realloc or migration
path: the realloc program
example
shows the resize flow.
Reallocation changes an existing account’s data length, but it has runtime
limits and may require extra lamports to keep the account rent-exempt. Existing
Solana accounts do not automatically grow the way contract-local storage feels
like it does in CosmWasm.
Cross-contract communication: Sub-messages vs CPIs
CosmWasm composes contracts through asynchronous messages. Solana composes programs through synchronous cross-program invocations (CPIs). A CPI is one Solana program calling an instruction on another program during the same transaction.Compare contract calls
| Dimension | CosmWasm | Solana |
|---|---|---|
| Execution | Asynchronous message queue | Synchronous call stack |
| Return values | Observed through reply | Available immediately |
| Accounts known up front | No | Yes, across the whole call chain |
| Nesting limit | Flexible application-level design | CPI depth is limited |
Token handling: Bank module / CW20 vs SPL tokens
CosmWasm splits native-denom flows and CW20 flows. Solana standardizes fungible tokens around the SPL Token program, where a mint account defines a token and token accounts hold balances for one owner and one mint. SOL itself moves through the System Program, the built-in program that creates accounts, transfers SOL, allocates data, and assigns ownership. Every Solana snippet below is a CPI from the previous section into the System or Token Program. The other term to know is authority: the account or PDA that a program recognizes as allowed to perform an action such as transferring tokens, minting tokens, or changing settings. The examples below cover the three common transfer cases: moving SOL with the System Program, moving SPL tokens with the Token Program, and moving tokens from a program-controlled vault by signing with PDA seeds.Compare token handling
| Concern | CosmWasm | Solana |
|---|---|---|
| Receiving tokens | info.funds or CW20 receive hook | User token account or ATA is passed explicitly |
| Sending tokens | BankMsg::Send or CW20 execute | System Program CPI or SPL Token CPI |
| Token standard | CW20 contract per token | Shared token program plus mint accounts |
| Program escrow | Contract balance or tracked allowances | PDA-controlled vault token accounts |
init_if_needed constraint) makes it
safe to include in every transfer flow.
A vault token account is a normal token account whose authority is a PDA instead
of a user’s wallet. Your program can move tokens out of that vault only when it
proves the PDA seeds to the runtime with
invoke_signed or Anchor’s
signer-seed helpers.
Serialization: JSON / serde vs binary data
CosmWasm messages are JSON-first and CLI-friendly. Solana instruction data and account data are binary-first: programs receive byte arrays and interpret those bytes according to the program’s own layout. Anchor prepends an 8-byte discriminator to each instruction and each account type so it can route handlers and validate layouts automatically. For instructions, a discriminator identifies which handler should run; for accounts, it identifies which account type is being decoded. One practical upside over JSON is that integers stay integers. You do not need the string-encodedUint128 convention that exists to protect precision in JSON
tooling.
If you are writing native Solana instruction enums without Anchor’s IDL layer,
choose a deterministic binary codec such as wincode or borsh, then document
that format so clients can encode the same bytes.
The tradeoff is debuggability: instruction bytes are not naturally
human-readable at the CLI layer, so your client, IDL, and tests become part of
the interface contract.
Compare serialization
Deserialization
Deserialization mirrors this on both sides of the RPC boundary. Inside the program, Anchor’sAccount<'info, T> checks the discriminator and borsh-decodes
the bytes before your handler runs, so deserialization is part of account
validation. In Pinocchio or native code you do it yourself, either with borsh’s
try_from_slice or by reinterpreting raw bytes against a #[repr(C)] layout
the way the State section’s try_from_bytes example does.
On the client, account data comes back from the RPC as raw bytes and must be
decoded against the same layout. Anchor clients decode through the IDL
(program.account.userBalance.fetch(pda)); Kit clients compose the layout from
the same codecs used for encoding, and
Codama can generate these decoders from
your IDL.
Invoking your program: Generated clients
On Cosmos, a client sends a JSON message through CosmJS and the chain routes it to the contract. On Solana, the client assembles the whole transaction: it picks the instruction, encodes its data, and lists every account the instruction touches. Nobody writes that by hand per instruction; clients are generated from the IDL, and the generated code does the account bookkeeping for you.Compare invocation
Standalone clients with Codama
Codama generates framework-free clients from the same IDL: TypeScript builders compatible with @solana/kit through@codama/renderers-js,
and Rust clients through @codama/renderers-rust. Each generated instruction
builder validates inputs, resolves default and derivable accounts, encodes
arguments, and returns a ready-to-send instruction, with account decoders and
PDA helpers alongside; Kit’s own program clients are generated this way.
Terminal
anchor codama generate -l js,rust -p clients target/idl/counter.json, or set [clients] auto = true in
Anchor.toml so every anchor build regenerates the clients.
Error handling
Both ecosystems lean on Rust error types, but Solana makes it more important to avoid panics because a panic often collapses into an unhelpful runtime failure. Prefer explicit Anchor#[error_code] values or native ProgramError variants
so callers and tests can identify the failure path.
Compare error handling
CosmWasm
Anchor
Anchor
Time & block information
CosmWasm gives you consensus time and block height inenv. Solana exposes time
and slot data through sysvars,
which are read-only system accounts that expose cluster state to programs. The
most common one here is Clock.
clock.slot for ordering
and sequencing. A slot is Solana’s logical time unit for leader-scheduled block
production. Use clock.unix_timestamp for approximate wall-clock checks such as
unlock windows or expiries. Treat the timestamp as good enough for time-based
UX, not as a perfect monotonic clock.
Testing
On Solana, transaction assembly is part of the product surface. Good tests exercise accounts, signers, PDA derivation, token accounts, and CPI behavior in addition to pure business logic. A signer is an account whose private key authorized the transaction, and signer status is one of the account privileges the runtime checks before execution.CosmWasm
LiteSVM
LiteSVM
LiteSVM
litesvm: the core in-process VM.litesvm-utils: general helpers for setup, assertions, and repetitive test plumbing.litesvm-token: helpers for SPL token mint, account, and transfer scenarios.anchor-litesvm: Anchor-aware helpers when your program and accounts use Anchor types and patterns.
Surfpool
Surfpool
Deployment & upgrades
CosmWasm separates code upload from instantiation and supports explicit migrate handlers. Solana deploys one program address and upgrades it in place under an upgrade authority. The upgrade authority is the signer allowed to replace the program’s bytecode; revoking it makes the program immutable.Costs, addresses, and free devnet rehearsals
Deployment locks a rent deposit sized to the program binary: usually a few SOL, and by far the largest cost of going live. Check it up front, and note that closing a program withsolana program close returns the deposit:
Terminal
Terminal
Terminal
| Concern | CosmWasm | Solana |
|---|---|---|
| Upload vs instantiate | Separate steps | One deployed program, many state accounts |
| Upgrade mechanism | migrate entry point | Replace program bytecode in place |
| Upgrade authority | Admin address on instance | Program upgrade authority key |
| Immutability | Unset admin | Finalize upgrade authority |
Full side-by-side example: Counter contract
A counter contract is a useful migration seed because it forces you to model state layout, authority, initialization, and off-chain reads without too much noise. Authority means the account or PDA your program treats as allowed to perform an action, usually enforced with a signer check, PDA seed check, or stored public key comparison.CosmWasm
init_if_needed, which creates the PDA account if
it does not exist and otherwise loads the existing account. That is convenient
for a small example, but production code should still validate the existing
account’s authority, seeds, and state version before trusting it.
Anchor
Anchor
Pinocchio
Porting a DEX: Lessons from the real world
DEX ports expose the biggest architectural differences quickly because they touch factories, pools, vaults, LP tokens, pricing state, and multi-hop account graphs. In Solana programs, a vault is usually a PDA-controlled token account that holds assets for a pool or escrow. A multi-hop account graph is the full list of accounts needed for every swap leg in one transaction.| Pattern | CosmWasm | Solana |
|---|---|---|
| Factory | Stores child contract addresses | Derives pool PDAs from mint seeds |
| Pool creation | Instantiate one contract per pool | Create one pool account plus vault accounts |
| LP token | Instantiate a CW20 contract | Create an SPL mint, often PDA-controlled |
| Pool discovery | Read factory state | Filter program accounts off-chain |
getProgramAccounts or an
indexer to find accounts owned by a program. The payoff is explicitness and
parallel-friendly execution.
This is why a factory port is not just a contract rewrite. It is also a client
rewrite and a state-discovery rewrite.
Common pitfalls & mental traps
- Do not forget to include every required account in the transaction. If an account is not passed in, the program cannot touch it.
- Do not try to deploy a new program per user or per pool. One program usually serves many accounts.
- Treat
init_if_neededas a sharp tool. This Anchor constraint initializes an account only when it is missing, so pair it with clear authority, seed, and state-version validation so it cannot silently reuse an account in an invalid state. - Store bump seeds you will need later for PDA signing instead of recomputing them everywhere.
- Always include the 8-byte Anchor discriminator in space calculations.
- Do not use floating-point arithmetic. Use integers and scaled units such as basis points.
- Translate auth checks into account constraints, not just inline handler code.
- Remember that CPI nesting is limited. Very deep call graphs may need to be flattened or split across transactions.
- Account size is fixed unless you explicitly reallocate it.
- Use
clock.slotfor sequencing andclock.unix_timestampfor approximate wall-clock logic.
Migration checklist
Use this checklist when porting a CosmWasm contract to Solana with Anchor.Architecture
- Identify every
ItemandMapand decide which PDA or account type will replace it. - Replace
instantiatewith one or more initialization instructions. - Remove on-chain query assumptions. Reads happen through RPC.
- Map each
ExecuteMsgvariant to an instruction handler and an account graph.
State
- Define
#[account]structs with explicit sizing. - Add bump fields where PDA signing or validation will need them.
- Budget for rent and for variable-length data.
- Plan reallocation or forward-compatible spare space if layouts may evolve.
Tokens
- Replace bank sends with System Program transfers where the asset is SOL.
- Replace CW20 flows with SPL Token CPIs and token-account modeling.
- Add ATA creation for holders that need token accounts.
- Replace LP-token contracts with SPL mint accounts plus mint authority policy.
- For CW721-style assets, choose whether the Solana version uses Metaplex metadata, Metaplex Core, or another NFT standard before you finalize account layouts.
Security, testing, and deployment
- Move
info.senderchecks into signer and account constraints where possible. - Test PDA derivation, account substitution resistance, stale reads after CPI, and account initialization paths.
- Define a state-migration strategy before the first production upgrade.
- Decide whether upgrade authority will remain active, move to multisig, or be finalized away.
- Work through the production readiness guide before launch: redundant RPC, priority fees and compute budgets for transaction landing, retry and confirmation strategy, key management, and monitoring.
Quick reference table
Use this as a fast translation map when you are porting familiar CosmWasm primitives into Solana-native account and instruction patterns. The linked sections above define the Solana terms used in this table.| CosmWasm | Anchor / Solana |
|---|---|
Item<T> | Singleton PDA account |
Map<K, V> | PDA per key with deterministic seeds |
IndexedMap | PDAs plus off-chain filtering or secondary index accounts |
SnapshotMap | Versioned accounts or custom history model |
instantiate | initialize instruction with init or init_if_needed |
execute | Instruction handlers in #[program] |
query | RPC account reads and client-side decoding |
migrate | Program upgrade plus explicit migration instruction |
reply | Usually unnecessary because CPI is synchronous |
BankMsg::Send | System Program transfer CPI or SPL token CPI |
WasmMsg::Execute | Anchor CPI or raw invoke |
ContractError | Anchor #[error_code] enum or ProgramError |
env.block.time | Clock::get()?.unix_timestamp |
env.block.height | Clock::get()?.slot |
info.sender | Signer plus account constraints |
CW20 | SPL mint plus token accounts or ATAs |
CW721 | SPL mint plus Metaplex metadata or Core |
cw-multi-test | anchor test, local validator, LiteSVM |
Contract instance | Program plus one or more owned accounts |
Contract admin | Stored authority plus upgrade authority policy |