Storage staking
On NEAR, state costs locked NEAR — roughly 1 NEAR per 100 KB — not one-time gas. The contract measures bytes used and makes the caller cover them.
Beginner5 min read3-question check
The EVM charges gas for SSTORE once, at write time. NEAR instead locks NEAR for as long as the data lives on-chain — about 1 NEAR per 100 KB. That balance is staked, not spent, and is released when the data is deleted.
So whoever grows the state should pay for it. The pattern: measure storage before and after the write, and require the caller to attach at least the cost.
use near_sdk::{near, env, AccountId, NearToken, require};
use near_sdk::store::LookupMap;
#[near(contract_state)]
pub struct Guestbook {
messages: LookupMap<AccountId, String>,
}
impl Default for Guestbook {
fn default() -> Self {
Self { messages: LookupMap::new(b"m") }
}
}
#[near]
impl Guestbook {
#[payable]
pub fn post(&mut self, message: String) {
let before = env::storage_usage();
self.messages.insert(env::predecessor_account_id(), message);
// store collections cache writes until flushed — write them now
// so storage_usage() actually reflects the new entry
self.messages.flush();
let added = env::storage_usage().saturating_sub(before);
let cost = env::storage_byte_cost().saturating_mul(added as u128);
require!(
env::attached_deposit() >= cost,
"attach more deposit to cover storage"
);
}
}There is no Solidity analog: the EVM has no notion of an ongoing storage deposit you can reclaim. This is why NEAR contracts ask for an attached deposit on writes and why token standards include storage registration (NEP-145).
env::storage_usage() is the account’s byte count; env::storage_byte_cost() is the price per byte as a NearToken. Multiply the delta and compare against env::attached_deposit().
near_sdk::store collections buffer writes in memory and only persist them when flushed (automatically at the end of the call). To measure the bytes an insert adds, call .flush() before reading env::storage_usage() again — otherwise the delta is zero.
Refund any excess (and release the stake on deletion) to be a good citizen — production contracts track each user’s storage balance so they can withdraw it when they leave.
Check yourself
3 questions · progress saved in this browser