GameFi Energy/Stamina System Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
GameFi Energy/Stamina System Development
Medium
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Development of a GameFi Energy/Stamina System

We have faced the task of creating an on-chain energy system that does not burn gas on regeneration. The usual approach—updating storage every second—kills the economy and makes the game unplayable. Our implementation uses lazy evaluation, allowing current energy to be computed without writing. With over 5 years of experience, we have developed an architecture that balances gas economy and cheat protection. This article covers key mechanics: time-based regen without writes, NFT binding, tradeable energy, and anti-cheat.

An energy system limits player activity. Players spend energy on actions (battles, farming, crafting), and energy replenishes over time or through purchases. In Web2, this is a simple counter in a database. In Web3, it’s an on-chain resource, creating opportunities (tradeable energy, verifiable regen) and problems (gas per update, cheating prevention). Proper architecture of the energy system is a key engineering challenge in GameFi. An incorrect implementation either makes the game unplayable (too many on-chain operations) or opens exploits (free energy via manipulation).

How does lazy evaluation reduce gas costs?

The intuitive solution: store energy in a mapping and update it every second. This is bad—endless transactions. The correct approach is lazy evaluation. Store not the current energy, but the last update moment and the value at that moment. Current energy is computed on-the-fly on each read:

contract EnergySystem {
    struct EnergyState {
        uint128 storedEnergy;
        uint64 lastUpdateTime;
        uint64 maxEnergy;
    }
    
    mapping(address => EnergyState) private energyStates;
    
    uint256 public constant REGEN_RATE = 1e18;
    uint256 public constant MAX_ENERGY = 100e18;
    
    function currentEnergy(address player) public view returns (uint256) {
        EnergyState storage state = energyStates[player];
        uint256 elapsed = block.timestamp - state.lastUpdateTime;
        uint256 regenerated = elapsed * REGEN_RATE;
        uint256 total = uint256(state.storedEnergy) + regenerated;
        uint256 max = state.maxEnergy == 0 ? MAX_ENERGY : uint256(state.maxEnergy);
        return total > max ? max : total;
    }
    
    function _updateEnergyState(address player) internal {
        EnergyState storage state = energyStates[player];
        state.storedEnergy = uint128(currentEnergy(player));
        state.lastUpdateTime = uint64(block.timestamp);
    }
    
    function spendEnergy(address player, uint256 amount) internal {
        uint256 current = currentEnergy(player);
        require(current >= amount, "Insufficient energy");
        _updateEnergyState(player);
        energyStates[player].storedEnergy -= uint128(amount);
    }
    
    function addEnergy(address player, uint256 amount) internal {
        _updateEnergyState(player);
        uint256 max = energyStates[player].maxEnergy == 0 
            ? MAX_ENERGY 
            : energyStates[player].maxEnergy;
        uint256 newEnergy = uint256(energyStates[player].storedEnergy) + amount;
        energyStates[player].storedEnergy = uint128(newEnergy > max ? max : newEnergy);
    }
}

The key point: currentEnergy() is a view function, consuming no gas. Storage updates only occur on spendEnergy/addEnergy—i.e., on actual game actions. Lazy evaluation reduces gas consumption by 10 times compared to constant storage updates. According to Solidity documentation, packed structs save storage gas.

Parameter Lazy evaluation Constant update
Write operations 0 in background, only on action Every second (millions of TX)
Gas cost per action ~50,000 gas ~100,000 gas + background
Implementation complexity Medium Low
Suitable for High-traffic GameFi Simple simulations

Using lazy evaluation reduces gas consumption by 90% compared to naive approaches. For a game with 10,000 daily active users, this can save over $120,000 annually in gas fees.

Energy Binding to an NFT

Energy is bound to a specific NFT, not an EOA wallet. This is important: a player can have multiple characters with independent energy, and trade characters along with their current energy.

contract CharacterEnergySystem {
    struct CharacterEnergy {
        uint128 storedEnergy;
        uint64 lastUpdate;
        uint8 tier;
    }
    
    mapping(uint256 => CharacterEnergy) public characterEnergy;
    
    function regenRateForTier(uint8 tier) public pure returns (uint256) {
        if (tier == 3) return 3e18;
        if (tier == 2) return 2e18;
        return 1e18;
    }
    
    function maxEnergyForTier(uint8 tier) public pure returns (uint256) {
        return 100e18 + uint256(tier) * 50e18;
    }
    
    function currentEnergy(uint256 tokenId) public view returns (uint256) {
        CharacterEnergy storage ce = characterEnergy[tokenId];
        uint8 tier = nftContract.getTier(tokenId);
        uint256 elapsed = block.timestamp - ce.lastUpdate;
        uint256 regen = elapsed * regenRateForTier(tier);
        uint256 total = uint256(ce.storedEnergy) + regen;
        uint256 max = maxEnergyForTier(tier);
        return total > max ? max : total;
    }
}

When an NFT is transferred, the energy moves with the character automatically, as it is stored in the mapping by tokenId.

Anti-Cheat Criticality

Without protection, players can manipulate regeneration via re-org or replay attacks. Our solution uses signed actions with nonce:

struct GameAction {
    uint256 characterId;
    uint256 actionType;
    uint256 energyCost;
    uint256 nonce;
    uint256 deadline;
}

mapping(address => uint256) public actionNonces;

function executeAction(
    GameAction calldata action,
    bytes calldata serverSignature
) external {
    bytes32 digest = _hashTypedData(action);
    address signer = ECDSA.recover(digest, serverSignature);
    require(signer == GAME_SERVER_SIGNER, "Invalid signature");
    require(action.nonce == actionNonces[msg.sender], "Invalid nonce");
    actionNonces[msg.sender]++;
    require(block.timestamp <= action.deadline, "Expired");
    spendEnergy(action.characterId, action.energyCost);
    _processAction(action);
}

Additionally, we introduce a cooldown modifier for frequent actions:

mapping(uint256 => mapping(uint8 => uint256)) public lastActionTime;

uint256 public constant BOSS_FIGHT_COOLDOWN = 4 hours;

modifier withCooldown(uint256 charId, uint8 actionType, uint256 cooldown) {
    require(
        block.timestamp >= lastActionTime[charId][actionType] + cooldown,
        "Action on cooldown"
    );
    _;
    lastActionTime[charId][actionType] = block.timestamp;
}

function fightBoss(uint256 charId) external withCooldown(charId, ACTION_BOSS, BOSS_FIGHT_COOLDOWN) {
    spendEnergy(charId, BOSS_FIGHT_ENERGY_COST);
    // ...
}

Risks of ERC-20 Energy

A more complex model: a separate ERC-20 token as energy, which can be bought/sold. Trade-off: players can buy energy on a DEX → pay-to-win risk. If acceptable, ERC-20 energy provides economic value; if not, energy should be non-transferable (internal accounting, not a token).

Economic Model: Sinks and Sources

The energy system acts as an economy regulator. It is important to balance sources and sinks. Recommended parameters:

Parameter Recommendations
Regen rate Fill from 0 to max in 8–12 hours
Max energy 1–3 game sessions of 2–3 hours each
Premium refill No more than 2–3 full refills per day
Tier multiplier Max 2x–3x, not more

Timeline and Cost Estimates

Basic system (lazy regen, spend, cooldowns): 2–3 weeks, estimated cost $5,000–$10,000. Full system (tier-based regen, ERC-20 energy token, DEX integration, anti-cheat signed actions, dashboard analytics): 5–7 weeks, estimated cost $15,000–$25,000. Cost is calculated individually after analyzing your mechanics.

What Is Included in the Delivery

  • Audit of existing mechanics
  • Smart contract design with gas optimization in mind
  • Development and unit tests (Foundry with vm.warp)
  • Contract deployment and verification
  • Integration with game backend (ethers.js, viem)
  • API documentation and usage examples
  • Post-release support (1 month)
  • Training session for your development team
  • Access to all source code and deployment scripts

Step-by-Step Implementation Guide

  1. Analyze your game mechanics and define energy parameters (regen rate, max energy, actions).
  2. Design smart contract architecture with lazy evaluation and optional ERC-20 energy.
  3. Develop and test contracts using Foundry (with vm.warp for time travel).
  4. Deploy contracts to testnet and verify security with an audit.
  5. Integrate with your game backend via ethers.js or viem.
  6. Deploy to mainnet and monitor gas usage.
  7. Conduct beta testing with users and adjust parameters.
Example Regeneration Test in Foundry ```solidity function test_energyRegenOverTime() public { uint256 tokenId = 1; vm.prank(player); game.spendAllEnergy(tokenId); assertEq(energy.currentEnergy(tokenId), 0); vm.warp(block.timestamp + 50); assertEq(energy.currentEnergy(tokenId), 50e18); vm.warp(block.timestamp + 200); assertEq(energy.currentEnergy(tokenId), 100e18); } ```

We guarantee no reentrancy and use proven patterns (OpenZeppelin). Our experience: 5+ years in Web3, 30+ implemented projects. Contact us for a consultation on your GameFi mechanics. Order a turnkey energy system development.

Game Economy, Contracts, and On-Chain Mechanics

We’ve seen this scenario multiple times. Axie Infinity generated substantial revenue monthly at its peak, but within 18 months the token crashed by 98% and the audience by 95%. The cause—lack of sinks: players earned SLP and cashed out, while burn mechanisms were insufficient. An analysis of Axie’s economy (Collins Dictionary) confirmed the model turned into a Ponzi scheme. We provide end-to-end GameFi development: from tokenomics to smart contracts, so your economy doesn’t repeat this mistake. Let’s evaluate your project at a meetup or online.

Play-to-Earn Economy Break Points

Inflationary tokenomics without sinks. Players earn tokens through gameplay. If sinks (burn or consumption mechanisms) are insufficient, supply outpaces demand. Price drops. Player fiat income declines. Players leave. A death spiral.

The right structure is a dual-token model with clear separation: a governance/value token with limited supply and a utility/reward token for in-game economy. The utility token must be actively consumed: item crafting, upgrades, entry fees, breeding. Examples: GODS/FLUX in Gods Unchained, AXS/SLP in Axie (though sinks were insufficient there). Historical data shows that without sinks, token supply inflates by 5–10% monthly, leading to price collapse within 6–9 months.

Effective Sink Mechanisms

  • Breeding/crafting — burning utility token to create a new NFT (e.g., Axie). Typical burn costs range from $5–$15 per action, removing 0.5–2% of total supply annually.
  • Character upgrades — each evolution requires token burning, consuming 0.1–0.3% of circulating supply per upgrade cycle.
  • PvP entry fee — token burn for tournament entry, part goes to prize pool. This can burn up to 0.5% of supply per week in active games.
  • Item durability — item breaks after N battles, token spent on repair. Cost per repair ~$0.50–$2.
  • Financial mechanics — staking with lock-up, removing tokens from circulation for a period. Typical lock-up periods of 30–90 days reduce circulating supply by 15–25%.

On-Chain vs Off-Chain: Boundary and Trade-offs

It’s not necessary to put all game logic on-chain—each transaction costs gas and takes 12 seconds. A game cycle is milliseconds. Balance:

Component On-chain Off-chain Examples
Asset Ownership + NFT items, land
Transfer/Trading + Marketplaces
Finance (staking, rewards) + Staking vaults, DAO
Random generation + (via VRF) Chainlink VRF
Gameplay + Battle system, movement
Game world state + Coordinates, health points
Matchmaking + Server-side logic

Gameplay results are transferred to blockchain via signed messages from server or ZK-proof. Verifiable off-chain with ZK: game server generates ZK-proof of session correctness, contract verifies proof and issues rewards. Implementations: Cartridge (Starknet), zkSync game rollups. Gas savings from batching proofs can reach 90% compared to per-action on-chain validation.

How Does Dual-Token Model Prevent Economic Collapse?

Governance token (limited supply) acts as value store and is used for major decisions. Utility token (minted via gameplay) is consumed by sink mechanisms, ensuring deflationary pressure. The ratio of governance to utility tokens in the initial pool should be 1:10 to 1:20. Simulation shows that a 30% burn rate on utility token keeps supply growth below 3% per year, preserving player income and token price.

Implementation of NFT Game Items

Standard: ERC-1155 for fungible items (resources, consumables) + ERC-721 for unique (characters, land). ERC-1155 provides up to 60% gas savings on batch transfers.

How to Implement Dynamic NFTs Without Overloading the Blockchain?

Item attributes change during gameplay (experience, durability, upgrades). Two approaches:

  • Fully on-chain: attributes stored in contract mapping, tokenURI generated from attributes via SVG/JSON encoding. Expensive in gas with frequent updates (e.g., $0.50 per update). Used for land and key assets.
  • Hybrid: attributes stored off-chain, tokenURI contains state hash. Updates signed by server, verified on-chain during transfer or sale. Cheaper ($0.02 per update) but requires server trust or ZK.

Breeding and crafting. Contract: two parent NFTs → pay utility token (burn) → mint new NFT with attributes dependent on parents + Chainlink VRF for randomness. Without VRF, miners can manipulate randomness via block selection.

// Simplified breeding with Chainlink VRF
function breed(uint256 parent1Id, uint256 parent2Id) external {
    require(ownerOf(parent1Id) == msg.sender);
    require(ownerOf(parent2Id) == msg.sender);
    require(breedingToken.burnFrom(msg.sender, BREEDING_COST));

    uint256 requestId = vrfCoordinator.requestRandomWords(...);
    pendingBreeds[requestId] = BreedRequest(parent1Id, parent2Id, msg.sender);
}

function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
    BreedRequest memory req = pendingBreeds[requestId];
    uint256 childAttributes = deriveAttributes(req.parent1Id, req.parent2Id, randomWords[0]);
    _mintWithAttributes(req.requester, childAttributes);
}

Marketplace and Royalties

An integrated marketplace gives control over fee structure and custom logic (e.g., banning item trading below a certain level). Royalties per EIP-2981 are standard but not enforceable: Blur and other marketplaces ignore on-chain royalties. For enforcement—whitelist-only transfer (only through contracts that pay royalties). Sacrifice composability for rights protection. Typical marketplace fee is 2.5–5% per transaction, generating recurring revenue.

Staking and Rewards Distribution

Staking NFTs is a mechanic for player retention. Problem: distributing rewards with thousands of stakers requires constant transactions (expensive). Solution—reward-per-share pattern (as in MasterChef from SushiSwap): global accRewardPerShare, upon claim or state change, debt is recalculated by formula pendingReward = stakedAmount * (accRewardPerShare - userRewardDebt). O(1) complexity regardless of staker count. Gas savings up to 70% compared to per-element distribution. Over a year with 10,000 stakers, this translates to roughly $40,000 saved in gas.

Why Is Reward-Per-Share Pattern Critical for Scalability?

Direct per-user reward updates cost O(n) per block, consuming more than 200,000 gas for 1,000 stakers. Reward-per-share reduces this to 30,000–50,000 gas per user claim, enabling thousands of stakers. Many early P2E games collapsed under gas costs that exceeded reward value. This pattern scales to tens of thousands without infrastructure overhead.

Process and Timelines

We start with a game economics document: token flows, mint/burn mechanics, projected supply schedule, sink analysis. Before writing code, the economy is modeled (Cadence, Python simulation).

GameFi Building Process: 5 Stages

  1. Economic modeling — 1–2 weeks. Develop dual-token model, calculate sinks, outline incentives for long-term holding.
  2. Token contract development — 2–3 weeks. ERC-20 for governance, ERC-20 for utility, with configurable mint/burn policy.
  3. NFT smart contracts — 3–5 weeks. ERC-721 / ERC-1155 with dynamic metadata, breeding/crafting, Chainlink VRF.
  4. Staking + rewards — 2–3 weeks. Contract based on reward-per-share, interfaces for frontend.
  5. Marketplace (optional) — 2–4 weeks. Custom marketplace with enforced royalty.

Work Deliverables

  • Source code for all smart contracts with tests (Foundry/Hardhat)
  • Architecture and economics documentation
  • Integration with Chainlink, Tenderly for monitoring
  • Code audit and formal verification (Slither, Mythril, Echidna)
  • Team training on contract interaction
  • Post-deployment support (3 months)

Basic GameFi stack (tokens + NFTs + staking + marketplace) — 8 to 16 weeks. Full game with on-chain randomness, breeding, dynamic NFTs — 4–8 months. ZK-based verifiable gameplay — a separate project from 6 months.

Contact us for an audit of your tokenomics—we’ll assess risks and refine sink mechanisms. Order GameFi project development—receive a ready product with proven economy. We guarantee contract stability and code transparency. Our experience includes dozens of implemented Web3 projects, including audits of 15+ P2E games. Get a consultation to start your project.