DeflationChain Yellow Paper

DeflationChain Yellow Paper

0. Abstract

DeflationChain is a new generation Layer-1 blockchain developed with deflationary mechanisms fundamentally integrated into the consensus protocol. Unlike existing blockchain platforms, where deflation is implemented exclusively at the level of smart contracts or tokenomics, DeflationChain introduces the concept of Proof-of-Deflation (PoD) — an innovative consensus mechanism in which the weight of a validator is determined not only by the number of staked tokens, but also by the duration of staking, as well as by the application of deflationary coefficients to the balances of network participants.

DeflationChain's architecture is based on seven key layers: Data Layer, Network Layer, Consensus Layer, Confidential Compute Layer, Trading Core Layer, Execution Layer, and Application Layer . This multi-level architecture ensures the modularity of the system and allows each component to be optimised independently without compromising the integrity of the protocol.

A key feature of DeflationChain is its geopolitical model of validator decentralisation, which limits the number of active validators to one per sovereign jurisdiction. The theoretical maximum is approximately 195 validators, which corresponds to the number of member states of the United Nations. This approach provides unprecedented network resilience to regulatory attacks: no government can force more than one validator to shut down, ensuring network continuity in any geopolitical scenario.

DeflationChain integrates a centralised order book with a throughput of up to 200,000 transactions per second and latency of less than 1 millisecond, while maintaining decentralised asset storage and transparent settlement on the blockchain. The trading core significantly improves on the HyperLiquid concept by eliminating identified vulnerabilities (the JELLY incident) and adding unique deflationary mechanisms: a portion of trading fees is burned, validators are rewarded with existing tokens (not emissions), and the Vault system is integrated with PoD consensus for enhanced security.

The level of confidential computing implemented using Intel TDX (Trust Domain Extensions) and SGX (Software Guard Extensions) technologies enables private AI computing directly on the blockchain infrastructure. DeflationChain, in terms of decentralised AI, has an advantage over the Cocoon architecture, eliminating its main drawback — the centralisation of proxy servers: in our implementation, proxy nodes are network validators with PoD stake, which provides economic motivation for honest behaviour and eliminates a single point of failure.

The blockchain remains fully compatible with the Ethereum Virtual Machine (EVM), allowing developers to use existing tools such as Solidity, Hardhat, and Foundry without having to learn new technologies. At the same time, DeflationChain extends the functionality of the EVM with specialised precompile contracts for working with deflationary logic, staking, and trading operations.

DeflationChain's economic model is based on a daily smart burn mechanism with doubling: after one day, 1% of the balance is burned, after two days — 2% of the balance, then 4%, 8%, 16%, 32%, 64% and 100% on the eighth day. If tokens are not transferred to staking, they are completely devalued in 8 days. The smart commission system distributes transaction fees between burning, the dividend pool, the technical pool, and the marketing fund, creating a sustainable deflationary cycle in which active use of the network amplifies deflation and, as a result, the potential growth in the value of the DEF token.

This document presents the technical specifications of all components of DeflationChain, including mathematical consensus models, cryptographic primitives, network protocols, and security mechanisms. The document is intended for developers, researchers, auditors, and all interested parties seeking a deep understanding of the platform's technical architecture.

1. Introduction

1.1. Motivation for creating DeflationChain

The modern cryptocurrency industry faces a fundamental contradiction between the declared goals of decentralised finance and the actual implementation of most blockchain protocols. Bitcoin, despite its limited supply of 21 million coins, does not have active deflationary mechanisms — its "deflationary nature" is limited to the accidental loss of access to wallets and a gradual slowdown in supply through halvings. Ethereum, Solana, Tron, Avalanche, and the vast majority of other first-tier blockchain platforms use inflationary emission models to pay rewards to validators, which fundamentally contradicts the concept of "digital gold" and value preservation.

DeflationCoin emerged as a response to this problem in the form of a token on Binance Smart Chain (BSC) that implements advanced deflationary mechanisms at the smart contract level. However, operating within someone else's infrastructure imposes significant limitations: the inability to integrate deflationary logic into the consensus mechanism, dependence on the fees and throughput of the underlying blockchain, and lack of control over the platform's development. DeflationChain is a logical development of the project — the creation of its own first-level blockchain with native integration of deflationary principles at all levels of the architecture.

The key motivation for creating DeflationChain is to build the first truly deflationary blockchain in history, where deflation is not an add-on to an inflationary base layer, but a fundamental property of the protocol itself. In traditional Proof-of-Stake systems, validators receive rewards in the form of new tokens, which creates constant inflationary pressure. DeflationChain revolutionises this approach by introducing the concept of Proof-of-Deflation, where validator rewards are generated not from issuance, but from the distribution of existing tokens — the dividend pool, trading commissions, and a portion of gas fees.

The second critical factor is the market's need for a high-performance trading infrastructure that combines the speed of centralised exchanges with the security and transparency of decentralised protocols. The success of HyperLiquid has demonstrated the viability of a hybrid model with a centralised order book and decentralised settlement. DeflationChain significantly improves this approach by adding an integrated deflationary economy and built-in AI services, creating a synergistic effect: active trading generates commissions, part of which are burned, reinforcing deflation and potentially increasing the value of the token, which attracts new users and increases trading activity.

The third motivation is the need for geopolitical stability of the blockchain infrastructure. Events in recent years have demonstrated the vulnerability of centralised and pseudo-decentralised systems to regulatory pressure. When a significant proportion of validators are concentrated in one or more jurisdictions, the governments of those countries have the opportunity to exert a decisive influence on the operation of the network. DeflationChain solves this problem through the "one validator, one country" principle, which ensures that even coordinated actions by several states cannot stop the network from functioning, as this would require the consensus of more than two-thirds of all countries in the world.

Finally, DeflationChain responds to the growing demand for the integration of artificial intelligence into blockchain infrastructure. Unlike projects such as Cocoon, which focus exclusively on AI computing, DeflationChain creates a comprehensive ecosystem where AI services are integrated with a trading platform, deflationary economy, and decentralised governance. The use of AI for market analysis, risk management, and trading strategy automation creates additional demand for the DEF token, as AI services are paid for in the native token with deflationary fees.

1.2. Problems with existing L1 solutions

1.2.1. Ethereum

Despite its status as the second largest cryptocurrency by market capitalisation and the dominant platform for smart contracts, Ethereum suffers from a number of fundamental problems that DeflationChain seeks to solve. The main problem remains scalability: even after switching to Proof-of-Stake and implementing EIP-1559 with a base fee burning mechanism, Ethereum only processes 15-30 transactions per second, which is catastrophically insufficient for a global financial infrastructure. Transaction fees during periods of high load reach tens and hundreds of dollars, making the platform inaccessible to the mass user.

Although the EIP-1559 burning mechanism creates elements of deflation, it is not a full-fledged deflationary model. The issuance of new ETH to reward validators continues, and during periods of low network activity, inflation exceeds burning. Moreover, the deflationary effect of EIP-1559 depends on the demand for blockchain space, creating a paradoxical situation in which the economic attractiveness of the asset increases only in conditions of congestion and high fees.

Block finalisation time in Ethereum is 12-15 minutes, taking into account epochs and checkpoints, which is unacceptable for trading applications that require instant transaction confirmation. Layer-2 solutions such as Optimism, Arbitrum, and zkSync partially solve the scalability problem, but add complexity, fragment liquidity, and introduce additional attack vectors.

1.2.2. Solana

Solana is positioned as a high-performance alternative to Ethereum, claiming a throughput of up to 65,000 transactions per second. However, practice has demonstrated significant reliability issues: the network has repeatedly experienced complete shutdowns lasting from several hours to days. The causes of the failures ranged from attacks on the network to code errors and overload during periods of high activity.

A more fundamental problem with Solana is the centralisation of validators. The hardware requirements for running a full Solana node are extremely high: 256 GB of RAM, a 12-core processor and several terabytes of NVMe storage are recommended. This leads to a concentration of validators in large data centres, mainly in North America and Europe. A significant portion of validators are hosted by a single provider (Hetzner), creating a single point of failure.

Solana's tokenomics are also inflationary: initial inflation was 8% per annum, gradually decreasing to a target level of 1.5%. This means a constant erosion of the shares of existing token holders who do not participate in staking.

1.2.3. HyperLiquid

HyperLiquid is the project closest to DeflationChain in terms of trading infrastructure architecture. The platform has successfully implemented the concept of a centralised order book with decentralised asset storage, achieving impressive performance: up to 200,000 transactions per second with less than 1 millisecond latency. HyperBFT consensus, based on the HotStuff protocol, ensures block finalisation in less than a second.

However, HyperLiquid does not have a deflationary economic model. The HYPE token is distributed through standard staking mechanisms without built-in burning. In addition, the platform does not restrict the geographical distribution of validators, which potentially creates vulnerability to regulatory pressure.

The JELLY token incident in March 2025 exposed vulnerabilities in HyperLiquid's risk management system: a manipulative short squeeze resulted in $10 million in unrealised losses for the HLP protocol vault and required emergency intervention by the team. This case highlighted the need for more sophisticated mechanisms to control open interest and protect against manipulation, which DeflationChain implements at the architecture level.

1.2.4. TON and Cocoon

The Open Network (TON), originally developed by the Telegram team, is a technically advanced platform with a unique sharding architecture. The Cocoon project, launched on TON in November 2025, demonstrates a cutting-edge approach to integrating AI computing into blockchain infrastructure using confidential computing (Intel TDX/SGX).

However, neither TON nor Cocoon has a deflationary economic model. Cocoon focuses exclusively on AI inference, without providing an integrated trading infrastructure. The centralisation of Cocoon's proxy servers (managed by the project team) also creates a potential point of failure and control.

DeflationChain builds upon and surpasses Cocoon's technical solutions in the field of confidential computing (TDX, SGX Seal Server, RA-TLS), integrating them into a comprehensive ecosystem with a deflationary economy, trading platform, and decentralised proxy nodes.

1.3. Evolution from DEF token on BSC

DeflationCoin (DEF) was launched on Binance Smart Chain as an experimental implementation of advanced deflationary tokenomics. The DeflationCoinUpgradeable smart contract implements several innovative mechanisms that form the basis of the DeflationChain economic model.

The BalancePortions mechanism divides each user's balance into separate "portions," each of which is marked with a timestamp of creation. When a balance is requested, the contract calculates the effective amount, taking into account the deflation coefficient, which depends on the age of each portion. The daily burning system applies the principle of doubling: after one day, 1% of the balance is burned, after two days — 2% of the balance, then 4%, 8%, 16%, 32%, 64% and 100% on the eighth day. Cumulative effect: after 8 days of inactivity, the tokens are completely devalued. The difference between the nominal and effective balance at each update is divided in half: 50% is burned forever, 50% goes to the dividend pool.

Smart staking allows users to protect tokens from daily burning by locking them for a period of 1 to 12 years. The longer the staking period, the higher the multiplier for calculating dividends: the array xMultipliers = [1, 2, 3, 4, 5, 6, 7, 10, 12, 14, 16, 20] array defines the coefficients for each year. A 12-year stake receives a 20x multiplier compared to an annual stake, creating a powerful incentive for long-term retention.

The Attention Grabbing mechanism automatically directs 1% of each stake for less than 12 years into a 12-year stake. This creates a constant inflow of funds into long-term storage, reinforcing the deflationary effect and demonstrating users' commitment to the project.

The dividend system distributes tokens accumulated in the dividend pool in proportion to the weighted stake of participants.

D = Samount ×Xmult ×Psnapshot β
where D — participant's dividends, Samount — stake amount, Xmult — multiplier for the year (xMultipliers[year-1]), Psnapshot — dividend pool balance, β — total weighted stake

Smart commissions distribute 5% of the transfer amount for each transaction: 1% is burned, 1% goes to the dividend pool, 1% goes to the technical pool, and 2% goes to the marketing pool. If there is a referral link, the commission is reduced to 4.5%: 2.25% is burned, 2.25% goes to the referrer.

Experience with operating the contract on BSC has demonstrated the viability of the model, but has also revealed limitations: dependence on BSC commissions, inability to integrate with the consensus of the base blockchain, and limited functionality expansion capabilities. DeflationChain transfers all these mechanisms to its own blockchain, adding integration with consensus (Proof-of-Deflation), a trading platform, and AI services.

1.4. Overview of architectural Solutions

DeflationChain implements a multi-level architecture, each layer of which is optimised to perform specific functions while maintaining close integration with other layers.

The Data Layer is responsible for the persistent storage of the blockchain state, including user balances, staking positions, trading positions, and smart contract states. It uses a modified Merkle Patricia Trie with additional roots for deflationary and trading states.

The Network Layer provides peer-to-peer communication between network nodes. It is implemented based on LibP2P with support for the gossip protocol for distributing transactions and blocks, DHT (Kademlia) for peer discovery, and an Ethereum-compatible JSON-RPC interface.

The Consensus Layer implements Proof-of-Deflation, a hybrid mechanism that combines elements of Proof-of-Stake with a deflationary economy. The weight of a validator is determined by a formula that takes into account the stake amount, the duration of staking, and the deflation coefficient. Block finalisation is based on HyperBFT with single-slot finality.

The Confidential Compute Layer provides private AI computing using Intel TDX for virtual machine isolation and SGX for cryptographic key management. The RA-TLS mechanism guarantees cryptographic verification of computing nodes.

The Trading Core Layer implements a high-performance order book with a centralised matching engine and decentralised settlement. The Vault system provides liquidity management, liquidation, and auto-deleveraging with mathematically sound security formulas.

The Execution Layer is an EVM-compatible virtual machine with extensions in the form of precompile contracts for deflationary logic, staking, and trading operations. Solidity 0.8.x and all standard Ethereum development tools are supported.

The Application Layer includes decentralised applications, trading interfaces, AI services, and integrations with external systems.

The interaction between the layers provides a synergistic effect: trading activity generates fees, part of which are burned at the consensus layer; AI services are paid for in DEF tokens with deflationary fees; deflationary mechanisms encourage long-term staking, increasing network security. This architecture creates positive feedback, where increased use of the platform amplifies deflation, potentially increasing the value of the token and attracting new users.

2. Blockchain architecture (multi-level model)

DeflationChain implements a seven-level modular architecture, where each level is responsible for a clearly defined set of functions and interacts with neighbouring levels through standardised interfaces. This approach allows for independent optimisation of each component, simplifies security audits, and enables updates to individual levels without disrupting the entire system.

DeflationChain Architecture
Application Layer
DApps, DEX Interface, AI Services, Wallets
Execution Layer
EVM-compatible Smart Contracts
Trading Core Layer
Centralised Order Book + Vault System
Confidential Compute Layer
TEE/TDX for private computing
Consensus Layer
Proof-of-Deflation + DEFBFT (improved HyperBFT)
Network Layer
P2P, Gossip, RPC Interface
Data Layer
State Storage, Merkle Patricia Trie

2.1. Consensus Layer

The consensus layer is the heart of DeflationChain, ensuring the consistency of the distributed network of nodes. DeflationChain introduces an innovative Proof-of-Deflation (PoD) mechanism that extends traditional Proof-of-Stake by integrating a deflationary economy directly into the validator weighting algorithm and block finalisation process.

2.1.1. Proof-of-Deflation (PoD) — formal Definition

Proof-of-Deflation is a hybrid consensus mechanism that combines the principles of Proof-of-Stake with DeflationChain's unique deflationary economic model. In traditional PoS systems, the weight of a validator is determined solely by the number of staked tokens. PoD extends this model by introducing additional multipliers that reflect the validator's long-term commitment to the network.

Definition 2.1 (Proof-of-Deflation): A consensus mechanism in which the right to create and validate blocks is distributed proportionally to the deflation-weighted stake of participants, defined as the product of the sum of staked tokens, the staking period in years, and the deflation coefficient applied to unstaked tokens.

The key differences between PoD and classic PoS are as follows:

  1. Time multiplier: Validators who have staked tokens for a longer period receive proportionally greater weight in the consensus. This encourages long-term commitment to the network and reduces the volatility of the validator pool.

  2. Deflationary component: Tokens that are not staked are subject to daily burning on a doubling basis: 1% after one day, then 2%, 4%, 8%, 16%, 32%, 64% and 100% on the eighth day (each time from the balance). This creates economic pressure on network participants in favour of staking, increasing the overall security of the network.

  3. Geographical factor: To ensure geopolitical decentralisation, a limit of one validator per jurisdiction is introduced. Validators from "duplicate" jurisdictions receive a zero geo_factor and cannot participate in the consensus.

  4. No inflationary emission: Unlike most PoS systems, where new tokens are created to reward validators, in PoD, rewards are generated from existing sources: the dividend pool, trading commissions, and gas fees.

2.1.2. Mathematical model of validator weight

The weight of a validator V in the Proof-of-Deflation mechanism is calculated using the following formula:

WV =Σi=1n (Si ×Yi × D(ti) ×GV)
where: Si is the sum of tokens in the i-th staking position, Yi — staking period in years (1 ≤ Y ≤ 12), D(ti) is the deflation coefficient, GV — geographical factor, n — number of positions

The relative weight of a validator in the network is determined as:

WVrel = WV Σj=1mWj
where: m is the total number of active validators in the network

For practical calculations, the consensus uses integer arithmetic with scaling. Weights are normalised to the range [0, 10^18], which provides sufficient accuracy for weighted voting.

2.1.3. Deflation coefficient formula

The DeflationChain burning mechanism is based on the principle of doubling: each day, the burning percentage doubles relative to the previous day. Burning is applied to the balance, which creates an exponential effect of depreciation of inactive tokens.

Doubling Burn principle:

Daily burn from the balance
Day 1
1% → 99%
Day 2
2% → 97%
Day 3
4% → 93%
Day 4
8% → 85%
Day 5
16% → 71%
Day 6
32% → 48%
Day 7
64% → 17%
Day 8
100% → 0%
remaining(t) = remaining(t−1) × (1 − dailyBurn[t])
where: t — number of full days since the portion was created, dailyBurn = [0, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.0]

This approach has unique properties: in the first few days, losses are minimal (1-2%), which gives users time to react, but then depreciation accelerates sharply, making long-term inaction economically unfeasible. After 8 days of complete inaction, the tokens are completely devalued.

Summary table of cumulative effect:

Day Daily burn Preserved value
0 0 100
1 1% of the balance 99
2 2% of the balance 97
3 4% of the balance 93
4 8% of the balance 85
5 16% of the balance 71
6 32% of the balance 48
7 64% of the balance 17
8 100 0

The difference between the nominal and effective balances at each update is distributed as follows:

This mechanism creates a powerful economic incentive to participate in staking: tokens in stake are completely protected from daily burning, while unstaked tokens lose 100% of their value in 8 days.

2.1.4. Block voting and finalisation mechanism

DeflationChain uses a modified BFT protocol to achieve consensus with instant finalisation (single-slot finality). The process of creating and finalising a block consists of the following stages:

Stage 1: Propose
The round leader, selected according to the rotation algorithm (see section 3.4), forms a candidate block that includes:

Stage 2: Prevote (Preliminary voting)
Validators receive the candidate block, verify its correctness, and broadcast a signed prevote message:

Stage 3: Precommit
After receiving prevotes from validators with a total weight of more than 2/3 of the total PoD weight, validators broadcast precommit messages:

PREVOTE_THRESHOLD = 2/3 × Σ W_all + 1

Stage 4: Commit
A block is considered finalised after receiving precommits from validators with a total weight of more than 2/3:

COMMIT_THRESHOLD = 2/3 × Σ W_all + 1

After commit, the block is immediately added to the blockchain and is considered irreversible. Unlike Ethereum, where finalisation requires several epochs (12-15 minutes), DeflationChain provides finalisation within a single slot (less than 1 second).

Timeout handling:
If the leader does not provide a valid block within the timeout period, the transition to the next round with a new leader is initiated. Timeouts increase exponentially with successive failures to ensure eventual liveness.

2.1.5. Integration with DEFBFT (improved HyperBFT)

The DeflationChain DEFBFT consensus protocol is based on the HyperBFT architecture, which is an optimised version of the HotStuff protocol. HyperBFT reduces the traditional three-phase BFT process to two rounds of communication, similar to the Jolteon, DiemBFT, and Fast HotStuff protocols.

Key HyperBFT optimisations adapted for DeflationChain:

  1. Pipelining: Multiple blocks are processed in parallel at different stages of consensus, similar to a processor pipeline. While one block is in the precommit stage, the next one can already be proposed.

  2. Optimistic Execution: Transactions begin to execute before the block is fully finalised. If finalisation is successful, the results are saved; if rolled back, they are discarded. This reduces the effective transaction confirmation time.

  3. Optimistic Responsiveness: Consensus adapts to current network conditions. When the network is operating normally, blocks are produced at maximum speed; when network delays occur, the protocol automatically slows down to maintain security.

  4. Linear Message Complexity: The number of messages required to reach consensus is linearly dependent on the number of validators (O(n)), rather than quadratically (O(n²)), as in classic PBFT protocols.

Target performance characteristics:

2.1.6. Byzantine Fault Tolerance in the context of PoD

DeflationChain maintains standard Byzantine Fault Tolerance guarantees: the network remains secure and alive with no more than 1/3 of malicious or faulty validators (measured by PoD weight, not number).

Formal security guarantees:

  1. Safety: If two honest validators have finalised blocks at the same height, these blocks are identical. Guaranteed when f < n/3, where f is the total PoD weight of malicious validators and n is the total PoD weight.

  2. Liveness: With 2/3+ honest validators (by PoD weight) and stable network conditions, the network continues to produce blocks.

Additional PoD protection mechanisms:

The geographical distribution of validators (one per country) provides an additional level of protection: to achieve 1/3 malicious weight, coordination of validators from approximately 65 countries would be required (assuming uniform weight distribution). This significantly increases the cost and complexity of an attack compared to networks where validators are concentrated in a few jurisdictions.

2.2. Execution Layer

The DeflationChain execution layer is an EVM-compatible virtual machine extended with specialised precompile contracts for deflationary logic, staking, and trading operations. Full compatibility with Ethereum allows existing development tools and smart contract porting without modifications.

2.2.1. EVM compatibility

DeflationChain implements full compatibility with the Ethereum Virtual Machine at the Shanghai fork level, including:

Supported opcodes:

Development tools:

Address space:

2.2.2. Gas model and deflationary fees

DeflationChain uses a modified gas model compatible with EIP-1559, but with a unique fee distribution mechanism integrated with a deflationary economy.

Fee calculation:

Ftotal =Gused × (Fbase +Fpriority)
where: Gused — amount of gas consumed by the transaction, Fbase — base commission, Fpriority — tip to the validator

Distribution of base_fee:

Bburn =Fbase × 0.20 (20% burned)
Bdividend =Fbase × 0.30 (30% to the dividend pool)
Bvalidator =Fbase × 0.30 (30% to validator)
Btreasury =Fbase × 0.20 (20% to treasury)

Priority_fee distribution:

Priority_fee is sent entirely to the block validator

This distribution has the following effects:

2.2.3. State and Merkle Patricia Trie

DeflationChain uses a modified Merkle Patricia Trie (MPT) to store the state, extended with additional structures for deflationary and trading logic.

State structure:

🌲 World State
Accounts MPT standard Ethereum state
nonce
balance
storageRoot
codeHash
Deflation State MPT NEW
BalancePortions[]
StakePositions[]
Deflation Metrics
Dividend Pool
Trading State MPT NEW
Positions[]
Orders[]
Vault Balances
Insurance Fund

Storage optimisation:

2.2.4. Transactions and their lifecycle

DeflationChain supports several transaction types that extend the standard Ethereum set:

Type 0: Legacy Transaction
Standard Ethereum transactions for backward compatibility.

Type 2: EIP-1559 Transaction
Transactions with dynamic fees (base_fee + priority_fee).

Type 100: Staking Transaction (NEW)
Specialised transactions for staking operations:

Type 101: Trading Transaction (NEW)
Transactions for trading operations:

Type 102: AI Request Transaction (NEW)
Transactions for AI services:

Transaction lifecycle:

  1. Creation and signing by the client
  2. Sending to mempool via RPC
  3. Validation and distribution via gossip
  4. Inclusion in a block by the leader
  5. Execution on EVM
  6. Finalisation as part of a block
  7. Generation of receipt with results

2.2.5. Precompiles for deflationary logic

DeflationChain extends the standard set of Ethereum precompile contracts with specialised contracts for efficient deflationary logic:

Address 0x0000…0100: DeflationMultiplier

function getDeflationMultiplier(uint256 timestamp) external view returns (uint256)

Returns the deflation multiplier for the specified timestamp with an accuracy of 18 decimal places.

Address 0x0000…0101: PoDWeight

function calculatePoDWeight(address account) external view returns (uint256)

Calculates the current PoD weight of the specified account for use in governance and consensus.

Address 0x0000…0102: StakingPositions

function getStakingPositions(address account) external view returns (StakePosition[] memory)

Returns an array of all staking positions for the account.

Address 0x0000…0103: EffectiveBalance

function getEffectiveBalance(address account) external view returns (uint256)

Calculates the effective balance, taking into account deflation, for the specified account.

Address 0x0000…0104: DividendCalculator

function calculateDividends(address account) external view returns (uint256[] memory)

Returns an array of available dividends for each staking position.

Using precompiles instead of regular smart contracts provides:

2.3. Data Layer

The data layer is responsible for the persistent storage of all blockchain states, ensuring data integrity, availability, and efficient data retrieval.

2.3.1. Block Structure

DeflationChain blocks extend the standard Ethereum structure with additional fields for deflation and trading logic:

Block {
    header: BlockHeader {
        // Standard Ethereum fields
        parentHash: bytes32 // Parent block hash
        ommersHash: bytes32 // Ommer block hash (deprecated, = EMPTY_OMMER_HASH)
        beneficiary:       address    // Validator address
        stateRoot:         bytes32    // MPT root of account states
        transactionsRoot:  bytes32    // MPT root of transactions
        receiptsRoot:      bytes32    // MPT root of receipts
        logsBloom:         bytes256   // Bloom filter of logs
        difficulty:        uint256    // Deprecated (= 0)
        number:            uint64     // Block height
        gasLimit:          uint64     // Block gas limit
        gasUsed:           uint64     // Gas used
        timestamp:         uint64     // Unix timestamp
        extraData:         bytes      // Additional data (max 32 bytes)
        mixHash:           bytes32    // Deprecated
        nonce:             bytes8     // Deprecated (= 0)
        baseFeePerGas:     uint256    // EIP-1559 base fee

        // DeflationChain extensions
        deflationRoot:     bytes32    // MPT root of deflation state
        tradingRoot:       bytes32    // MPT root of trading state
        aiRoot:            bytes32    // MPT root of AI state
        validatorSignatures: bytes[]  // Validator signatures for PoD
        podWeightSnapshot: uint256    // Snapshot of total PoD weight
    }

    body: BlockBody {
        transactions:      Transaction[]     // List of transactions
        withdrawals:       Withdrawal[]      // Withdrawals (EIP-4895)
        tradingEvents:     TradingEvent[]    // Trading events (NEW)
        aiCompletions:     AICompletion[]    // Completed AI requests (NEW)
    }
}

2.3.2. State Storage

DeflationChain uses a two-tier storage system to optimise performance:

Hot Storage:

Cold storage:

Key scheme:

Account State: keccak256(address) → RLP(nonce, balance, storageRoot, codeHash)
Contract Storage: keccak256(address || slot) → value
Deflation State: 0x01 || address || positionIndex → RLP(BalancePortion)
Staking State:    0x02 || address || stakeIndex → RLP(StakePosition)
Trading State:    0x03 || market || positionId → RLP(Position)

2.3.3. Archive Nodes

Archive nodes store the complete state history for each block, which is necessary for:

Requirements for an archive node:

Optimisations for archive nodes:

3. Validator model

The DeflationChain validator model is one of the platform's most innovative features, implementing the principle of geopolitical decentralisation. Unlike existing blockchains, where validators are distributed primarily according to economic criteria (leading to concentration in jurisdictions with cheap electricity and favourable regulation), DeflationChain introduces a fundamental restriction: no more than one active validator from each sovereign jurisdiction. This approach provides unprecedented network resilience to regulatory attacks and creates true global decentralisation.

3.1. Geopolitical Decentralisation

3.1.1. The "1 validator = 1 country" principle

The central element of the DeflationChain validator model is the principle of geographical restriction: no more than one active validator can operate in each sovereign jurisdiction. This restriction is enshrined at the protocol level and cannot be changed without a hard fork with the consent of the overwhelming majority of network participants.

Definition of jurisdiction: For the purposes of DeflationChain, jurisdiction is defined as a sovereign state recognised by the United Nations. This includes 193 UN member states and 2 observer states (the Vatican and Palestine), giving a theoretical maximum of 195 validators. Special administrative regions (e.g., Hong Kong, Macau), dependent territories, and self-proclaimed states are not considered separate jurisdictions for validation purposes.

Reason for the restriction:

  1. Resilience to regulatory pressure: If the government of one country decides to ban cryptocurrency activities or forces a validator to cease operations, this affects no more than 1/195 (≈0.5%) of the maximum number of validators. Disrupting the network (achieving 1/3 malicious weight) would require coordinated action by approximately 65 countries — a scenario that is virtually impossible in the current geopolitical environment.

  2. True global decentralisation: Existing blockchains show a significant concentration of validators. For example, more than 60% of Solana validators are located in the United States and Germany; a significant portion of Ethereum's stake is concentrated in a few jurisdictions. DeflationChain ensures that no single country can control more than 1/195 of the maximum number of validators.

  3. Protection against coordinated attacks: Even if a group of countries (e.g., G7 or G20 members) decides to coordinate an attack on the network, their combined influence will be limited by the number of jurisdictions represented, which is well below the 1/3 threshold required to breach BFT consensus security.

  4. Encouraging global participation: The restriction creates an economic incentive to deploy validators in countries that are traditionally underrepresented in blockchain infrastructure. This promotes technological development and the spread of cryptocurrency technologies in developing regions.

3.1.2. Jurisdiction verification mechanism

To ensure compliance with the "1 validator = 1 country" principle, DeflationChain implements a multi-level jurisdiction verification mechanism that combines cryptographic methods with KYC/KYB procedures.

Verification process:

  1. Application submission: Validator candidates submit their applications through a specialised ValidatorRegistry smart contract, specifying their desired jurisdiction and providing an initial deposit (stake bond).

  2. KYB verification: The candidate undergoes a Know Your Business procedure through an accredited verification partner. The following must be provided:

    • Documents confirming the registration of a legal entity in the specified jurisdiction
    • Proof of physical presence (office, data centre)
    • Identification of beneficial owners
    • Checks for compliance with sanctions lists (OFAC, EU, UN)
  3. Cryptographic attestation: After successfully completing KYB, the verification partner generates a signed attestation containing:

    Attestation {
        validatorAddress: address
        jurisdiction: bytes2 (ISO 3166-1 alpha-2 country code)
        verificationDate: uint256
        expirationDate: uint256
        verifierSignature: bytes
    }
    
  4. On-chain registration: The attestation is published in the ValidatorRegistry smart contract. The contract verifies:

    • The validity of the accredited verifier's signature
    • The absence of an active validator in the specified jurisdiction
    • Sufficiency of the stake bond
    • Compliance of the node's technical parameters with the requirements
  5. Activation: After successful registration, the validator is included in the active set and can participate in the consensus from the next epoch.

Annual re-verification:
To keep the information about the jurisdiction up to date, validators are required to undergo re-verification every 12 months. Failure to pass re-verification results in automatic exclusion from the active set (jailing) until the status is successfully confirmed.

Privacy protection:
KYB verification details are not published on the blockchain. Only the jurisdiction code and attestation hash are stored on-chain. Full verification data is stored by accredited partners in accordance with GDPR and local legislation requirements.

3.1.3. Maximum number of validators

The theoretical maximum number of validators in the DeflationChain network is approximately 195, which corresponds to the number of recognised sovereign states. However, the practical number of active validators will vary depending on:

Network development phases:

Phase Number of validators Characteristics
Genesis 10 Initial launch, mainly regions with developed infrastructure
Growth 50 Expansion into developing regions
Maturity 150-195 Global coverage

Minimum number for security:
To ensure sufficient decentralisation and security of the BFT consensus, a minimum of 21 active validators (7f+1 where f=3) is recommended. The protocol will not activate the mainnet until this threshold is reached.

3.1.4. Justification for the restriction and Advantages

Comparison with traditional models:

Characteristic Ethereum Solana DeflationChain
Max. validators ~1,000,000 ~1,500 ~195
Geographical concentration High (US, EU) Very high (US) Minimal (by design)
Regulatory stability Low Very low Maximum
Attack coordination Requires $ Requires $ Requires geopolitics

Potential criticisms and responses:

Criticism 1: "Limiting to 195 validators is centralisation."
Response: Centralisation is determined not by the number of nodes, but by the concentration of control. 195 validators in 195 countries are more decentralised than 10,000 validators in 5 countries, as the latter are subject to coordinated regulatory pressure.

Criticism 2: "Rich countries will dominate."
Response: PoD weight is determined by stake and time, not by a country's wealth. A validator from a developing country with a long-term stake may have more weight than a validator from the G7 with a short-term position.

Criticism 3: "KYC contradicts decentralisation"
Response: KYC applies only to validators (professional infrastructure operators), not to network users. This is similar to banking licence requirements — users remain anonymous, but infrastructure operators are identified.

3.2. Requirements for validators

3.2.1. Minimum DEF stake

To participate as a DeflationChain validator, a minimum stake is required to ensure an economic incentive for honest behaviour and to cover potential slashing penalties.

Validator staking parameters:

MIN_VALIDATOR_STAKE = 10,000 DEF
MIN_STAKE_PERIOD = 4 years
STAKE_MULTIPLIER = 4x (corresponds to xMultipliers[3])

Rationale for parameters:

Delegated stake:
In addition to their own stake, validators can accept delegated tokens from users. Delegated stake:

3.2.2. Technical Requirements

DeflationChain validators must provide high-performance and reliable infrastructure to maintain network targets.

Hardware requirements (minimum):

CPU:      32 cores / 64 threads, 3.0 GHz+
          Intel Xeon (Sapphire Rapids+) with TDX support — for Confidential Compute
RAM:      128 GB DDR5 ECC
Storage:  2 TB NVMe SSD (DWPD ≥ 1)
          + 10 TB HDD for archive (optional)
Network:  1 Gbps symmetrical, low latency
GPU:      NVIDIA H100/A100 — for AI inference (optional)

Hardware requirements (recommended):

CPU:      64 cores / 128 threads, 3.5 GHz+
          Intel Xeon with TDX + SGX support
RAM:      256 GB DDR5 ECC
Storage:  4 TB NVMe SSD RAID-10
          + 20 TB for archive
Network:  10 Gbps symmetrical
GPU:      2x NVIDIA H100 with CC support

Software requirements:

Availability requirements:

Uptime SLA: 99.9% (maximum 8.76 hours of downtime per year)
Block production: Participation in ≥95% of assigned slots
Latency: <100ms to 90% of other validators

DeflationChain validators must comply with legal requirements that ensure the legitimacy and stability of the network.

Mandatory requirements:

  1. Registration of a legal entity in the declared jurisdiction
  2. Licences/permits for activities with crypto assets (if required by local law)
  3. Absence from sanctions lists (OFAC, EU, UN)
  4. Passing KYB verification through an accredited partner
  5. Agreement to the terms of participation in the network (Terms of Service)

Recommended practices:

3.3. Validator economics

3.3.1. Validator reward formula

DeflationChain validators receive rewards from several sources without creating new tokens (inflationary issuance):

Rvalidator =Rdiv +Rtrading +Rgas +Rai

Remuneration components:

  1. Dividends from staking (R_dividends):
Rdiv = Wvalidator β ×Psnapshot ×Efrac
where: Wvalidator is the weighted stake of the validator, β — global beta indicator, Psnapshot — pool balance, Efrac — epoch share
  1. Share of trading commissions (R_trading):
Rtrading =Ftrading ×Sval ×Wvalidatorrel
where: Ftrading — Trading Core commissions, Sval = 10% — validator share, Wvalidatorrel — relative PoD weight
  1. Share of gas fees (R_gas):
Rgas = (Bproduced ×Favg × 0.30) +Fpriority
where: Bproduced — number of blocks created, Favg — average gas fee, Fpriority — priority fees (100%)
  1. Share from AI services (R_ai):
Rai =Fai ×Sworker
(only for validators with AI infrastructure)

Expected return:
At full network load and uniform distribution of validators, the expected annual return is 15-30% APY per stake, which significantly exceeds typical PoS network rates (4-8% APY) due to the absence of dilution from inflationary issuance.

3.3.2. Slashing conditions

To ensure honest behaviour by validators, DeflationChain implements a penalty (slashing) system, whereby part of the stake is confiscated for protocol violations.

Penalty table:

Violation Penalty Jailing Additional
Double signing 5% stake 30 days Publication of evidence on-chain
Prolonged downtime (>24 hours) 1% stake 7 days Warning at 12 hours
Invalid block proposal 2% stake 14 days Automatic detection
Censorship (proven) 10% stake 90 days Governance vote required
Equivocation 5% stake 30 days Contradictory signatures
Repeat violations 2x base 2x term Cumulative effect

Distribution of slashed tokens:

burned = slashed_amount × 0.50    // 50% burned
treasury = slashed_amount × 0.30  // 30% to treasury
reporter = slashed_amount × 0.20  // 20% to the person who reported the violation

Jailing process:

  1. Detection of violation (automatically or via report)
  2. Immediate exclusion from the active set of validators
  3. Application of slashing to the stake
  4. Jailing period (validator cannot participate in consensus)
  5. Unjailing after the period expires and the correction is confirmed

3.3.3. Delegated Staking

Users who are unwilling or unable to run their own validator can delegate their tokens to existing validators.

Delegation mechanics:

function delegate(address validator, uint256 amount, uint256 years) external {
    require(validators[validator].isActive, "Validator not active");
    require(years >= 1 && years <= 12, "Invalid stake period");

    // Create a delegated position
    DelegationPosition memory position = DelegationPosition({
        delegator: msg.sender,
        validator: validator,
        amount: amount,
        years: years,
        startTime: block.timestamp,
        lastClaimed: 0
    });

    delegations[msg.sender].push(position);
    validators[validator].totalDelegated += amount;

    // Transfer and lock tokens
    DEF.transferFrom(msg.sender, address(this), amount);
}

Validator commission:
Validators set a commission (5-20% of the delegator's rewards), which is withheld when distributing rewards:

Rdelegator =Rgross × (1 −Cval)
Rbonus =Rgross ×Cval
where: Cval — validator commission (5-20%)

Slashing distribution:
When a validator is slashed, a proportional part of the penalty is applied to the delegated stake:

Sdelegator = Damount Stotal ×Aslashed
where: Damount is the delegation amount, Stotal — total stake

This creates an economic incentive for delegators to choose reliable validators and monitor their behaviour.

3.4. Rotation and leader selection

3.4.1. Round leader selection algorithm

The selection of the leader (proposer) for each consensus round is determined based on the PoD weights of the validators, which ensures a fair distribution of the right to create blocks.

Weighted Random Selection Algorithm:

def select_leader(epoch: int, round: int, validators: List[Validator]) -> Validator:
    # Generation of a pseudo-randomseed
    seed = keccak256(
        epoch.to_bytes(8) ||
        round.to_bytes(8) ||
        prev_block_hash
    )

   # Obtaining validator weights
    weights = [v.pod_weight for v in validators if v.is_active]
    total_weight = sum(weights)

    # Selection based on seed
    target = int.from_bytes(seed[:32]) % total_weight
    cumulative = 0

   for validator in validators:
        if not validator.is_active:
            continue
        cumulative += validator.pod_weight
        if cumulative > target:
            return validator

    # Fallback (should not be reached)
    return validators[0]

Algorithm properties:

  1. Determinism: All nodes calculate the same leader for a given (epoch, round)
  2. Proportionality: The probability of selection is proportional to the PoD weight
  3. Unpredictability: It is impossible to predict the leader before the previous block is finalised (dependency on prev_block_hash)
  4. Stability: Failure of the leader leads to a transition to the next round with a new leader

3.4.2. Weighted Random Selection based on PoD

Using PoD weights to select a leader provides several important properties:

Encouraging long-term staking:
Validators with a long staking period (higher Y in the weight formula) have a proportionally higher probability of being selected as leader, which increases their reward and encourages long-term commitment to the network.

Protection against Sybil attacks:
Splitting the stake between multiple validators (if possible) does not increase the total probability of selection, as the weights are additive.

VRF for additional protection:
To prevent grinding attacks (attempts to manipulate the selection of the leader), a Verifiable Random Function (VRF) mechanism can be implemented:

vrf_output = VRF_prove(validator_private_key, epoch || round)
leader = select_based_on_vrf(vrf_output, validators)

VRF ensures that only the validator itself can generate proof for its potential leadership, preventing pre-computation attacks.

4. Proof-of-Deflation: Formal Specification

Proof-of-Deflation (PoD) is the central innovative mechanism of DeflationChain, combining consensus, economic incentives, and deflationary tokenomics into a single coherent system. This section provides a formal specification of all PoD components with mathematical definitions and proofs of key properties.

4.1. Definitions

4.1.1. Staking Position

A staking position is the basic unit of participation in the PoD mechanism. Each position is characterised by a set of parameters that determine its contribution to consensus and its right to receive rewards.

Formal definition:

Definition 4.1 (Staking position)
A staking position S is a tuple (a, A, F, t, Y, L,Cs,Cd), where:
a : address
is the address of the position owner
A : uint256
— the current amount of tokens in the position (amount)
F : uint256
— initial amount for smooth unlocking (finishedAmount)
t : uint256
— timestamp of position creation (startTime)
Y : uint256
— staking period in years, 1 ≤ Y ≤ 12 (year)
L : uint256
— last claim period in YYYYMM format (lastClaimed)
Cs: uint256
— number of claims withdrawn from staking in the current period (claimedStaking)
Cd: uint256
— amount of dividends received in the current period (claimedDividends)

Solidity representation:

struct StakePosition {
    uint256 initialAmount;      // Initial amount upon creation
    uint256 amount;             // Current amount (may decrease upon partial withdrawal)
    uint256 finishedAmount;     // Fixed at the end of the term
    uint256 startTime;          // Block.timestamp of creation
    uint256 year;               // Term: 1-12 years
    uint256 lastClaimed;        // YYYYMM of last claim
    uint256 claimedStaking;     // Withdrawn from principal in the current period
    uint256 claimedDividends;   // Dividends received in the current period
}

Position invariants:

1.
A ≤ initialAmount
// The amount cannot exceed the initial amount
2.
1 ≤ Y ≤ 12
// Term within the acceptable range
3.
t ≤ block.timestamp
// Creation time in the past
4.
F = 0 ∨ (F > 0 ∧ isFinished(S))
// finishedAmount only upon completion

4.1.2. Deflationary Multiplier

The deflationary multiplier determines the proportion of retained value for tokens not in staking, depending on the time since the last movement.

Formal definition:

The burning mechanism uses the doubling principle: every day, the burning percentage of the balance doubles. This creates exponential pressure on inactive tokens, while giving users enough time to react in the early days.

Definition 4.2 (Doubling Principle)
Daily burn d(t) from the balance:
d(1) = 1%, d(2) = 2%, d(3) = 4%, d(4) = 8%
d(5) = 16%, d(6) = 32%, d(7) = 64%, d(8) = 100%
d(t) = min(2t-1, 100)% for t ≥ 1
Cumulative remainder R(t):
R(0) = 100%
R(t) = R(t-1) × (1 - d(t)/100) for t ≥ 1
Result: R = [100, 99, 97, 93, 85, 71, 48, 17, 0]%

The doubling principle ensures a soft start and a hard finish: losses are insignificant in the early days (1-4%), but by the end of the week, the depreciation becomes critical. This gives users the opportunity to rectify the situation (stake or transfer tokens) if they have forgotten about their assets.

Properties of the doubling principle:

1.
d(1) = 1%
// Soft start
2.
d(t) = 2 × d(t-1)
// Doubling every day
3.
d(8) = 100%
// Complete combustion on the 8th day
4.
R(8) = 0%
// Final cumulative result

Economic interpretation:

The doubling function simulates the "cost of inaction" in the DeflationChain system. Token holders who do not participate in staking or active transactions lose value on an exponential scale:

This creates a powerful economic incentive to actively participate in the ecosystem through staking, trading, or using DeFi protocols.

4.1.3. PoD Weight

PoD weight is a key metric that determines a participant's influence in the consensus mechanism and reward distribution.

Formal definition:

Definition 4.3 (PoD weight)
For a set of staking positions P = {S1,S2, ...,Sn} of address a,
PoD weightWa is defined as:
Wa =Σi=1n (Si.amount ×Si.year)
Relative PoD weight:
Warel =Wa /βPoD
whereβPoD =Σall jWj is the global PoD indicator

Properties of PoD weight:

1.
Wa ≥ 0
// Non-negativity
2.
Wa = 0 ⟺ no active positions
// Zero weight = no stake
3.
ΣWarel = 1
// Sum of relative weights = 1
4.
Wa is linearly dependent on amount
// Doubling the steak = doubling the weight
5.
Wa is linearly dependent on year
// Doubling the term = doubling the weight

Calculation example:

Position 1:
10,000 DEF for 4 years
W1 = 10,000 × 4 = 40,000
Position 2:
5,000 DEF for 12 years
W2 = 5,000 × 12 = 60,000
Total: Wa = 40,000 + 60,000 = 100,000
IfβPoD = 2,000,000, thenWarel = 100,000 / 2,000,000 = 5%

4.2. Mathematical Formulas

4.2.1. Beta indicator (for dividends)

The beta indicator β is used to calculate dividends taking into account non-linear multipliers for different staking periods.

Definition:

β =Σall S (Samount ×Xmult[Syear - 1])
xMultipliers = [1, 2, 3, 4, 5, 6, 7, 10, 12, 14, 16, 20]

Difference from β_PoD:
While β_PoD uses a linear dependence on the term (amount × year), β for dividends uses a non-linear scale xMultipliers:

Year PoD multiplier Dividend multiplier Ratio
1 1 1 1.00
4 4 4 1.00
8 8 10 1.25
12 12 20 1.67

This creates an additional incentive for ultra-long-term staking (8-12 years): with equal PoD weight, 12-year positions receive 67% more dividends than 12 × (1-year) positions.

4.2.2. Beta-PoD (for Consensus)

Beta-PoD is used exclusively to calculate weights in the consensus mechanism:

βPoD =Σall S (Samount ×Syear)

β_PoD update:

// When creating a stake
β_PoD += stake.amount × stake.year;

// When extending the term
β_PoD += stake.amount × (newYear - oldYear);

// When partially withdrawing
β_PoD -= withdrawAmount × remainingYears;

4.2.3. Dividend Formula

Dividends for staking position S for the period are calculated as:

D(S) = Samount ×Xmult ×Psnapshot β
where: D(S) — dividends for stake S, Samount — stake amount, Xmult is the multiplier for the year, Psnapshot — dividend pool balance, β is the global beta indicator

Staking time accounting:
Positions created in the current month do not receive dividends for that month:

if getYearMonth(S.startTime) == currentYearMonth:
D(S) = 0

Accounting for dividends already received:

availableDividends = D(S) − S.claimedDividends

4.2.4. Monthly Withdrawal Formula

In addition to dividends, stakers can withdraw part of the principal amount of the stake on a monthly basis:

SM(S) = Samount Y × 12
where: SM(S) — maximum withdrawal amount per month, Samount — current stake amount, Y — stake term in years

Example:

General formula for available withdrawal:

W(S) = SM(S) + D(S) - S.claimedStaking - S.claimedDividends

4.3. Consensus Rounds

4.3.1. Propose → Vote → Commit

DeflationChain consensus follows a simplified two-phase model based on HotStuff:

Phase 1: Propose + Prevote
1
Leader L for round r is selected using the select_leader(epoch, r) algorithm
2
L forms block B and broadcasts PROPOSE(B, r)
3
Validators receive PROPOSE and check:
• The correctness of parent_hash
• The validity of all transactions
• Correctness of state_root after execution
4
If successful, they broadcast PREVOTE(hash(B), r, signature)
Phase 2: Precommit + Commit
5
Upon receiving PREVOTE with a total PoD weight > 2/3:
• QC (Quorum Certificate) = {prevotes} is formed
PRECOMMIT(hash(B), QC, r, signature) is broadcast
6
Upon receiving PRECOMMIT with a total weight > 2/3:
• Block B is considered finalised
COMMIT(hash(B), r) is broadcast
• Status is updated

4.3.2. Quorum

Quorum definition:

Σv∈QWv > 2 3 ×Σv∈VWv
where: Q is a set of validators for the quorum, V — all validators, Wv — PoD weight of the validator

Minimum quorum with equal weights:
With N validators with equal weights, the minimum quorum is ⌈2N/3⌉ + 1 validators.

Example: With 100 validators with equal weights, 67+ votes are required to reach a quorum.

4.3.3. Block finalisation

Finalisation in DeflationChain occurs instantly after the precommit quorum is reached:

Theorem 4.1 (Instant Finalisation)
If block B at height h has received precommits from validators with a total PoD weight > 2/3, then B is the only finalised block at height h, and this property is irreversible.
Proof:

Suppose there is a block B' ≠ B, also finalised at height h. Then:

Σ W(precommit B) > 23 × ΣWall
Σ W(precommit B') > 23 × ΣWall
Σ W(precommit B) + Σ W(precommit B') > 43 × ΣWall

However, validators can only give a precommit to one block at a height (slashing for double signing), so the intersection of the sets:

|precommit B ∩ precommit B'| = 0

This means:

Σ W(precommit B) + Σ W(precommit B') ≤ ΣWall

Contradiction with 43 × ΣWall > ΣWall.

4.4. Protection against Attacks

4.4.1. Long-range Attacks

Long-range attacks occur when an attacker uses old private keys (from validators that have already left staking) to create an alternative block chain, starting from the distant past.

Protection mechanisms in DeflationChain:

  1. Checkpoints: Every 1,000 blocks, a checkpoint is created, the hash of which is included in the next block. Clients reject chains that contradict known checkpoints.

  2. Weak Subjectivity Period: New nodes must synchronise with a state no older than 2 weeks. This ensures that by the time of synchronisation, an attacker will not have had time to create a sufficiently long alternative chain.

  3. Deflationary Protection: Since unstaked tokens lose value after 8 days, validators cannot exit staking and save their tokens for a future attack — they must either remain in staking or lose their funds.

4.4.2. Nothing-at-Stake

The nothing-at-stake problem arises in PoS systems when validators can vote for several conflicting blocks without economic loss.

Solution in DeflationChain:

  1. Slashing for double signing: Signing two different blocks at the same height results in the confiscation of 5% of the stake.

  2. Cryptographic link: Each prevote/precommit contains a unique signature tied to a specific block and round. Attempting to create two signatures for one round is cryptographically provable.

  3. Economic incentive: With a minimum stake of 10,000 DEF, the loss of 5% (500 DEF) for double signing makes the attack economically unprofitable.

4.4.3. Deflationary Penalty

DeflationChain enhances standard slashing mechanisms with a unique deflationary component:

Aslashed = S ×Pslash
Bburned =Aslashed × 0.50 (50% is destroyed)
Ttreasury =Aslashed × 0.30 (30% in treasury)
Rreporter =Aslashed × 0.20 (20% to the reporter)

Deflationary effect:
Burning 50% of slashed tokens creates an additional deflationary effect with each violation. This means that attacks on the network not only punish the attacker, but also bring economic benefits to honest participants by reducing the total supply of tokens.

5. Centralised order book (Trading Core)

Trading Core is the heart of DeflationChain's trading infrastructure, representing a hybrid architecture that combines the speed of centralised exchanges with the security and transparency of decentralised systems. DeflationChain develops and significantly improves the HyperLiquid architecture by eliminating identified vulnerabilities (the JELLY incident with $10 million in losses) and adding unique features: a native deflationary economy, integration with a geopolitically decentralised network of validators, and improved risk control and anti-manipulation mechanisms.

5.1. Trading Core Architecture

5.1.1. Centralised Matching Engine

The Matching Engine (ME) is a high-performance component responsible for matching buyer and seller orders. Unlike traditional DEXs, where matching occurs on-chain with high latency, DeflationChain uses off-chain matching with on-chain settlement.

Matching Engine Architecture:

Matching Engine
Order
Gateway
Order Book
Engine
Trade
Executor
In-Memory State Manager
Balances
Positions
Orders
Markets
Settlement Queue DeflationChain

System components:

  1. Order Gateway: Accepts orders from users via API/WebSocket, performs initial validation (signature, balance, limits), routes to the appropriate Order Book.

  2. Order Book Engine: Maintains sorted lists of bid/ask orders for each market, performs price-time priority matching algorithm, generates trade execution events.

  3. Trade Executor: Processes executed trades, updates positions and balances, calculates PnL, generates settlement transactions.

  4. In-Memory State Manager: Stores the current state of all accounts, positions, and orders in RAM for minimal latency.

Technical specifications:

Parameter Value
Matching Latency < 1 ms (median)
< 5 ms (99th percentile)
Order Throughput 200,000+ orders/sec
Concurrent Markets 1,000+ trading pairs
Memory Footprint < 50 GB for full state
Failover Time < 1 second

5.1.2. Integration with decentralised Settlement

The Settlement Layer provides final confirmation of all trading operations on the DeflationChain blockchain, guaranteeing immutability and transparency.

Transaction processing flow:

User
Order
Order
Gateway
Matching
Engine
Trade
Batch
On-chain
Settlement
<50ms
<1ms
<10ms
<2 seconds
Total: <3 seconds

Settlement stages:

  1. Trade Aggregation (every 100ms): Transactions are grouped into batches to optimise gas costs.

  2. State Transition Proof: For each batch, proof of correct state transition is generated.

  3. On-chain Commit: The batch of transactions is sent to DeflationChain with the signatures of the matching engine operators.

  4. Finalisation: After inclusion in the block and finalisation (instant in DeflationChain), the settlement is considered complete.

Settlement Transaction Format:

struct SettlementBatch {
    uint256 batchId;
    uint256 timestamp;
    bytes32 previousStateRoot;
    bytes32 newStateRoot;
    Trade[] trades;
    bytes operatorSignature;
}

struct Trade {
    address maker;
    address taker;
    bytes32 marketId;
    uint256 price;
    uint256 quantity;
    bool isMakerLong;
    uint256 makerFee;
    uint256 takerFee;
}

5.1.3. Hybrid model: CEX speed + DEX security

DeflationChain Trading Core implements a unique hybrid model that takes the best from centralised and decentralised exchanges:

Comparison table:

Feature CEX DEX DeflationChain
Matching Latency <1 ms >1 sec <1 ms
Custody Centralised Decentralised Decentralised
Settlement Off-chain On-chain On-chain
Transparency Low High High
Counterparty Risk High None None
MEV Resistance N/A Low High
Order Book Depth High Low High

Key principles of the hybrid model:

  1. Self-Custody: Users always control their funds through on-chain smart contracts. The Matching Engine never has direct access to funds.

  2. Deterministic Execution: All matching engine rules are open and deterministic. Anyone can verify the correctness of execution.

  3. Fraud Proofs: If an incorrect settlement is detected, any participant can provide fraud proof and receive a reward from the operator's slashed stake.

  4. Decentralised Operators: The Matching Engine can run on any validator, with automatic failover in case of failures.

5.2. Order Types

DeflationChain Trading Core supports the full range of order types required for professional trading.

5.2.1. Basic Orders

Limit Order:

Definition: An order to buy/sell at a specified price or better.

Parameters:
- side: BUY | SELL
- price: uint256 (in minimum units of quote asset)
- quantity: uint256 (in minimum units of base asset)
- timeInForce: GTC | IOC | FOK | GTT

Example:
{
  "type": "LIMIT",
  "side": "BUY",
  "price": "45000.00",
  "quantity": "1.5",
  "market": "BTC-USDC",
  "timeInForce": "GTC"
}

Market Order:

Definition: An order for immediate execution at the best available price.

Parameters:
- side: BUY | SELL
- quantity: uint256 (can be in base or quote asset)
- slippage: uint256 (maximum deviation from oracle price, in bp)

Slippage protection:
max_execution_price = oracle_price × (1 + slippage / 10000)

Stop-Loss Order:

Definition: The order is activated when the trigger price is reached.

Parameters:
- triggerPrice: uint256
- executionType: MARKET | LIMIT
- limitPrice: uint256 (only for LIMIT)

Activation logic:
IF side == SELL AND mark_price <= triggerPrice: activate()
IF side == BUY AND mark_price >= triggerPrice: activate()

Take-Profit Order:

Definition: An order to lock in profits when the target price is reached.

Parameters: same as Stop-Loss

Activation logic:
IF side == SELL AND mark_price >= triggerPrice: activate()
IF side == BUY AND mark_price <= triggerPrice: activate()

Trailing Stop Order:

Definition: Stop order with a dynamic trigger price.

Parameters:
- trailingDelta: uint256 (in % or absolute units)
- activationPrice: uint256 (optional)

Logic:
trailing_price = max_price - (max_price × trailingDelta / 100)
IF mark_price <= trailing_price: activate()

Post-Only Order (Maker Only):

Definition: The order is guaranteed to be added to the order book.

Behaviour:
IF order would immediately match: REJECT
ELSE: add to order book

Advantage: guaranteed receipt of maker rebate.

Reduce-Only Order:

Definition: The order can only reduce an existing position.

Validation:
IF order.side == position.side: REJECT
IF order.quantity > position.size: order.quantity = position.size

5.2.2. Perpetual Contracts

DeflationChain supports perpetual futures contracts — derivative instruments with no expiry date.

Linear Perpetuals (USDC-settled):

Characteristics:
- Margin and PnL in USDC (stablecoin)
- Contract is quoted in USD
- Position size in base asset

PnL calculation:
PnL = (exit_price - entry_price) × position_size × direction
where direction = 1 for LONG, -1 for SHORT

Example:
- LONG 10 BTC @ $45,000
- Exit @ $47,000
- PnL = (47000 - 45000) × 10 × 1 = +$20,000 USDC

Inverse Perpetuals (DEF-settled):

Characteristics:
- Margin and PnL in DEF (native token)
- Contract is quoted in USD
- Used to hedge DEF exposure

PnL calculation:
PnL = position_value × (1/entry_price - 1/exit_price) × direction

Example:
- SHORT $100,000 contract @ DEF=$10
- DEF falls to $8
- PnL = 100,000 × (1/10 - 1/8) × (-1) = 100,000 × 0.025 = 2,500 DEF

Funding Rate Mechanism:

Funding rate is a periodic payment between holders of long and short positions to peg the perpetual price to the spot price.

Funding rate formula:
F = clamp(
    (mark_price - index_price) / index_price × impact_factor,
    -0.01,  // min -1% per 8h
    +0.01   // max +1% per 8h)


Funding payment:
payment = position_value × F

Direction:
IF F > 0: longs pay shorts
IF F < 0: shorts pay longs

Frequency: every 8 hours (00:00, 08:00, 16:00 UTC)

Mark Price Calculation:

Mark price is used to calculate PnL and liquidations, protecting against spot price manipulation.

mark_price = index_price × (1 + funding_basis)

where:
- index_price = TWAP(oracle_prices) for the last 5 minutes
- funding_basis = cumulative_funding / 8h_intervals

Oracle sources:
- Chainlink
- Pyth Network
- Internal TWAP from spot markets
- Median from 3+ sources

5.2.3. Leverage

DeflationChain allows trading with up to 50x leverage, which increases both potential profits and risks.

Maximum leverage by asset type:

Asset category Max Leverage Initial Margin
Major (BTC, ETH) 50 2
Large Cap 25x 4
Mid Cap 10x 10
Small Cap 5x 20
DEF pairs 20x 5

Margin requirement formulas:

Initial Margin (IM):
IM = position_notional / leverage

Example:
- Position: £100,000
- Leverage: 20x
- IM = £100,000 / 20 = £5,000

Maintenance Margin (MM):
MM = IM × maintenance_ratio
maintenance_ratio = 0.5 (50% of initial)

MM = £5,000 × 0.5 = £2,500

Cross vs Isolated Margin:

Cross Margin:
- All free margin is available for all positions
- Reduces the risk of liquidation of individual positions
- Increases systemic risk

Isolated Margin:
- Margin is allocated separately for each position
- Maximum loss = allocated margin
- Recommended for high-risk trades

5.3. Performance

5.3.1. Target Metrics

DeflationChain Trading Core is designed to compete with top centralised exchanges:

Metric Target Comparison
Order Throughput 200,000+ ops/s Binance: ~100,000 ops/s
Matching Latency (p50) < 1 ms HyperLiquid: ~1 ms
Matching Latency (p99) < 5 ms CEX avg: 5-10 ms
Settlement Latency < 2 sec DEX avg: 12-15 sec
Uptime SLA 99.99 ~52 min downtime/year
Max concurrent users 1,000,000
Order Book Depth 10,000+ levels

Optimisations to achieve target metrics:

  1. Lock-free data structures: Order books are implemented on lock-free data structures to minimise contention.

  2. DPDK networking: Direct kernel bypass for network operations, reducing latency to microseconds.

  3. Memory-mapped persistence: State is synchronised to disk via mmap without blocking the main thread.

  4. Horizontal scaling: Each market is handled by an independent shard.

5.3.2. Superiority over HyperLiquid

DeflationChain outperforms HyperLiquid on most key parameters. Below is a detailed comparison of the architectures:

Feature HyperLiquid DeflationChain
Consensus Protocol HyperBFT PoD + DEFBFT (improved HyperBFT)
Deflationary Tokenomics No Yes
Validator Model Unlimited 1 per country
Native AI Computing No Yes
Order Throughput 200k ops/s 200k+ ops/s
Block Time < 1 sec < 1 sec
EVM Compatibility No Full
Fee Distribution Community Stakers+Burn
Confidential Compute No TDX/SGX

Unique advantages of DeflationChain:

  1. Deflationary economy: Trading fees are partially burned, creating positive pressure on the price of DEF.

  2. EVM compatibility: Developers can use existing tools (Solidity, Hardhat, ethers.js).

  3. Geopolitical stability: The distribution of validators across countries protects against regulatory risks.

  4. Integrated AI: Ability to use AI for trading strategies with guaranteed privacy.

5.4. MEV Protection

MEV (Maximal Extractable Value) is the profit that validators/sequencers can extract by reordering transactions. DeflationChain implements several protection mechanisms.

5.4.1. Fair Ordering Protocol

Fair Ordering Protocol (FOP) is an improvement over traditional blockchains, where the order of transactions is determined solely by the block proposer. In the classic model, the proposer can reorder transactions for personal gain (front-running, sandwich attacks). FOP eliminates this possibility through a cryptographically secured queue.

The key idea is that each order receives a sequence number not from a single validator, but from a threshold group (2/3 of validators). This makes it impossible to manipulate the order without collusion by the majority of the network. The Matching Engine is required to process orders strictly by sequence number, and any violation is automatically detected and punished by slashing.

This approach implements fair ordering in the sense of "first come, first served" — an honest trader who submits an order earlier is guaranteed to be processed earlier, regardless of the size of the commission or connections with validators.

Principle: Orders are processed strictly in the order in which they are received (FIFO).

Implementation:
1. Each order receives a monotonically increasing sequence number.
2. The sequence number is signed with a threshold signature (2/3 of validators).
3. The Matching Engine is required to process orders by sequence number.
4. Violation of the order = slashable offence.

5.4.2. Commit-Reveal for large orders

Commit-Reveal is a classic cryptographic scheme for preventing front-running. Problem: when a large order is visible in the mempool before execution, observers can open a position before it and close it after, profiting from the price movement caused by the large order.

Solution: two-phase execution. In the first phase (Commit), the trader publishes only the cryptographic hash of the order — no one knows the direction, size, or price. In the second phase (Reveal, after 1 block), the trader reveals the parameters, the contract verifies the hash, and executes the order.

It is important to understand the trade-off: commit-reveal adds a delay of 1 block (2 seconds). This is unacceptable for small orders, so the mechanism is only used for orders over $100,000, where the potential damage from front-running outweighs the inconvenience of the delay.

For orders > £100,000:

Phase 1 - Commit (hidden):
- User publishes: hash(order || salt || user_address)
- Order is added to the commit queue

Phase 2 - Reveal (after 1 block):
- User publishes: order, salt
- Hash matching is verified
- Order is executed

Protection: Front-runners cannot see order details before reveal.

5.4.3. Batch Auctions

Batch Auctions is an alternative order execution mechanism activated during periods of high volatility. Unlike continuous trading (where each order is executed immediately), batch auction collects all orders for a specific time window and executes them simultaneously at a single clearing price.

The key advantage is the elimination of time-priority advantage. In continuous trading, HFT traders with faster connections have an advantage — they can react to information before others. In batch auctions, all orders within the window are equal, which levels the playing field between institutional players and retail traders.

DeflationChain automatically switches to batch mode when it detects abnormal volatility or suspicious MEV patterns. The duration of the auction window (100-500 ms) balances protection against MEV with acceptable latency for traders.

Alternative mode for volatile markets:

1. Orders are collected during the auction window (100-500ms)
2. A single clearing price is calculated
3. All orders are executed at the clearing price

Advantage: Eliminates time-priority advantage for HFT.

6. Vault System & Leverage Pool

The Vault System is a critical component of DeflationChain, providing the infrastructure for margin trading, liquidations, and risk management. The system is designed with lessons learned from incidents on other platforms (including the JELLY incident on HyperLiquid) and incorporates multi-layered protection mechanisms.

6.1. Vault Architecture

6.1.1. Deflation Liquidity Provider (DLP)

DLP is a protocol vault that represents an evolution of the HLP concept with the elimination of identified vulnerabilities. Unlike HLP, DLP integrates deflationary mechanisms, improved open interest control, and multi-layered protection against manipulation.

DLP Architecture:

Deflation Liquidity Provider (DLP)
Liquidity Provision
  • Market Making
  • Spread Management
Liquidation Execution
  • Position Takeover
  • Partial/Full
Trading Strategy
  • Delta-neutral
  • Arbitrage
  • Rebalancing
Risk Manager
Greeks Monitor
VaR Engine
Position Limits
Circuit Breakers
Treasury (100% DEF)

Key features of DLP:

Parameter Value
Ownership 100% Community-owned
Base Asset DEF (native token)
Target TVL $100M+ (after maturity)
Primary Function Counterparty for liquidations
Secondary Function Market making (passive)
Revenue Sources Trading fees, liquidation premium
Fee Distribution 70% to LPs, 20% burn, 10% treasury

How DLP works:

  1. Deposit: Users deposit DEF into DLP and receive DLP shares (ERC-20 tokens).

  2. Liquidation as a counterparty: When a trader's position is liquidated, DLP takes the position at the liquidation price with a premium.

  3. Market Making: DLP automatically places limit orders at a specified distance from the mark price.

  4. Rebalancing: DLP positions are periodically rebalanced to maintain delta-neutral exposure.

DLP share value formula:

sharevalue = total vaultequity totalshares
totalvault_equity = Σ(assets × prices) + Σ(unrealisedpnl) − Σ(liabilities)
Calculation example
Total DEF: 500,000
DEF price: $10
Unrealised PnL: +£25,000
Total shares: 450,000
sharevalue = (500,000 × $10 + $25,000) / 450,000 = $11.17

6.1.2. Custom Vaults

In addition to the protocol DLP, any user can create their own vault with a custom trading strategy.

Types of user vaults:

Vault Type Description
Public Vault Open to deposits from any user. The leader receives 10% of the profit.
Private Vault By invitation only. For professional managers with a limited circle of investors.
Strategy Vault Automated strategy (bot). The strategy code is open and verified.
Yield Vault Passive income through lending/staking. Low risk, stable returns.

Vault contract structure:

contract UserVault {
    // Vault metadata
    string public name;
    address public leader;
    VaultType public vaultType;

    // Economics
    uint256 public performanceFee;     // Leader's share (max 20%)
    uint256 public managementFee;      // Annual fee (max 2%)
    uint256 public highWaterMark;      // For performance fee calculation

    // Shares
    mapping(address => uint256) public shares;
    uint256 public totalShares;

    // Risk parameters
    uint256 public maxLeverage;        // Max leverage for vault
    uint256 public maxDrawdown;        // Auto-close if exceeded
    bytes32[] public allowedMarkets;   // Whitelist of tradeable markets

    // Lock-up
    uint256 public lockUpPeriod;       // Minimum hold time
    mapping(address => uint256) public depositTime;
}

Example of creating a vault:

Vault: "DEF Momentum Strategy"
Leader: 0x1234...
Type: Public

Parameters:
- Performance Fee: 15%
- Management Fee: 1%
- Max Leverage: 10x
- Max Drawdown: 30%
- Lock-up: 7 days
- Allowed Markets: [BTC-PERP, ETH-PERP, DEF-PERP]

Initial Deposit: 10,000 DEF (from leader)

6.1.3. Protocol Vaults

Protocol vaults are specialised reserves managed automatically by smart contracts without human intervention.

Insurance Fund Vault:

Insurance Fund Vault
Purpose
Coverage of losses in the event of bankruptcy (when equity < 0)
Use
• Covering negative equity
• Last line of defence before ADL
Replenishment
50% of liquidation penalties 10% trading fees Part of slashing
Minimum amount: max(1% of total_open_interest, $10M)
adequacyratio = insurancefund expectedloss_95th
target: adequacy ratio ≥ 2.0 (200% coverage of expected losses)

Treasury Vault:

Purpose: Financing ecosystem development.

Replenishment:
- 20% of gas fees
- 30% of slashing penalties
- Part of trading fees

Use (through governance):
- Grants to developers
- Marketing
- Security audits
- Listings

Management: Multi-sig (5/9) + Timelock (48h)

Dividend Pool Vault:

Purpose: Distribution of dividends to stakers.

Replenishment:
- 50% of burned balances (progressive burn rate)
- 30% of gas fees
- Part of trading fees

Distribution:
- Monthly
- Proportionally (stake × xMultiplier)
- Snapshot on the 1st day of the month

6.2. Pool security formulas

Security formulas are the mathematical foundation that ensures the stability of the system during volatile market movements.

6.2.1. Margin Requirement

Initial Margin (IM):

The minimum amount required to open a position.

IM = position_notional / leverage

Where:
- position_notional = position_size × mark_price
- leverage = selected leverage (1x-50x)

Example:
A trader wants to open a LONG 10 BTC @ $50,000 with 20x leverage
- position_notional = 10 × $50,000 = $500,000
- leverage = 20x
- IM = $500,000 / 20 = $25,000

IM formula taking into account tiers:

A progressive scale is applied to large positions:

Position Tiers — Progressive Margin
Position Notional Marginal IM Max Leverage
$0 – $100,000 2 50
£100,000 – £500,000 4 25
$500,000 – $2,000,000 5 20x
$2,000,000 – $10,000,000 10 10
> $10,000,000 20 5x
📊 Example for a position of $1,000,000:
IM = £100,000 × 2% + £400,000 × 4% + £500,000 × 5%
   = $2,000 + $16,000 + $25,000 = $43,000
Effective leverage = £1,000,000 / £43,000 ≈ 23.3x

6.2.2. Maintenance Margin (MM)

The minimum equity required to maintain a position.

MM = IM × maintenance_ratio

maintenance_ratio = 0.5 (50% of initial margin)

Example:
- IM = £25,000
- MM = £25,000 × 0.5 = £12,500

If equity falls below £12,500, liquidation begins.

Dynamic maintenance_ratio:

For volatile assets, an increased coefficient is applied:

maintenance_ratio = base_ratio × volatility_multiplier

volatility_multiplier = max(1.0, realised_vol_30d / 50%)

Example for a volatile asset:
- base_ratio = 0.5
- realised_vol_30d = 100%
- volatility_multiplier = 100% / 50% = 2.0
- maintenance_ratio = 0.5 × 2.0 = 1.0 (100% IM = MM)

6.2.3. Liquidation Price

The price at which the position will be liquidated.

For LONG positions:

Liq_Price_Long = Entry_Price × (1 - (1/leverage) × (1 - MM_ratio) + fees)

Where:
- leverage = position_notional / initial_margin
- MM_ratio = maintenance_margin / initial_margin
- fees = estimated closing fees (0.1%)

Example:
- Entry_Price = £50,000
- Leverage = 20x
- MM_ratio = 0.5
- fees = 0.001

Liq_Price = £50,000 × (1 - 0.05 × 0.5 + 0.001)
          = £50,000 × 0.976
          = £48,800

For SHORT positions:

Liq_Price_Short = Entry_Price × (1 + (1/leverage) × (1 - MM_ratio) + fees)

Example:
Liq_Price = £50,000 × (1 + 0.05 × 0.5 + 0.001)
          = £50,000 × 1.026
          = £51,300

6.2.4. Available

Margin

Free margin available for opening new positions or withdrawal.

Available_Margin = Account_Equity - Total_Initial_Margin_Used

Account_Equity = Balance + Unrealised_PnL

Unrealised_PnL = Σ(position_size × (mark_price - entry_price) × direction)

Example:
- Balance: £50,000
- LONG 5 BTC @ £48,000, mark_price = £50,000
- Unrealised_PnL = 5 × (£50,000 - £48,000) × 1 = +£10,000
- Account_Equity = £50,000 + £10,000 = £60,000
- Position Notional = 5 × $50,000 = $250,000
- IM_used = $250,000 / 10 = $25,000 (at 10x)
- Available_Margin = $60,000 - $25,000 = $35,000

6.2.5. Margin

Ratio

A key indicator of account health.

Margin_Ratio = Account_Equity / Total_Maintenance_Margin

Account status:
- Margin_Ratio > 2.0: Healthy (green)
- 1.5 < Margin_Ratio ≤ 2.0: Warning (yellow)
- 1.0 < Margin_Ratio ≤ 1.5: Danger (orange)
- Margin_Ratio ≤ 1.0: Liquidation (red)

6.3. Liquidation Mechanism

Liquidation is the forced closure of a position due to insufficient margin. DeflationChain uses a multi-stage mechanism to minimise market impact.

6.3.1. Liquidation Trigger

Liquidation condition:
Account_Equity ≤ Total_Maintenance_Margin

Equivalent to:
Margin_Ratio ≤ 1.0

Monitoring:
- Mark price is updated every second
- Margin check is performed with every update
- Positions are sorted by margin_ratio

Initiation process:

1. The system detects margin_ratio ≤ 1.0
2. The account is marked as "liquidatable"
3. A LiquidationTriggered event is generated
4. The Liquidation Engine begins processing

6.3.2. Partial Liquidation

To minimise trader losses and market impact, partial liquidation is applied.

Partial liquidation algorithm:

WHILE margin_ratio < target_margin_ratio:
    # Step 1: Cancel open orders
    cancel_open_orders()
    recalculate_margin_ratio()

    IF margin_ratio >= target_margin_ratio:
        BREAK

    # Step 2: Partial closure (20% of position)
    close_ratio = 0.20
    for position in sorted_positions_by_loss:
        close_amount = position.size × close_ratio
        execute_market_close(position, close_amount)
        recalculate_margin_ratio()

        IF margin_ratio >= target_margin_ratio:
            BREAK

target_margin_ratio = 1.5 (150% of maintenance)

Example of partial liquidation:

Initial state:
- Equity: £10,000
- Position: LONG 10 BTC @ £50,000
- MM: £12,500
- Margin_Ratio: 0.8 (liquidation!)

Step 1: Close 20% (2 BTC)
- Realised loss: -$1,000
- New Equity: $9,000
- New position: 8 BTC
- New MM: $10,000
- New Margin_Ratio: 0.9

Step 2: Close another 20% (1.6 BTC)
- Realised loss: -$600
- New Equity: $8,400
- New position: 6.4 BTC
- New MM: $8,000
- New Margin_Ratio: 1.05

Step 3: Close another 20% (1.28 BTC)
- After closing Margin_Ratio > 1.5
- Liquidation complete

6.3.3. Full Liquidation

Applies when partial liquidation is not possible or equity becomes negative.

Conditions for full liquidation:
1. Margin_Ratio < 0.5 after partial liquidation
2. Position is too small for partial closing
3. Insufficient liquidity for partial closing

Process:
1. All positions are closed with market orders
2. If final_equity > 0: the balance is returned to the trader
3. If final_equity < 0: the loss is covered by the Insurance Fund

6.3.4. Insurance Fund

The Insurance Fund is the last line of defence against loss socialisation.

Insurance Fund structure:

struct InsuranceFund {
    uint256 balance;                // Current balance
    uint256 targetBalance;          // Target balance
    uint256 utilisationRate;        // Current utilisation
    uint256 replenishmentRate;      // Replenishment rate

    mapping(bytes32 => uint256) marketReserves; // Reserve by markets
}

Insurance Fund formulas:

Target balance:
target_balance = max(
    total_open_interest × 0.01,     // 1% of OI
    $10,000,000                      // Minimum $10M)


Replenishment:
- 50% of liquidation_fees
- 10% of trading_fees
- 30% of slashing_penalties

Usage:
deficit = abs(negative_equity_from_liquidation)
IF insurance_fund.balance >= deficit:
    insurance_fund.balance -= deficit
ELSE:
    trigger_adl()  // Auto-Deleveraging

Transparency:

Public metrics (updated every block):
- insurance_fund_balance
- insurance_fund_utilization_24h
- insurance_fund_replenishment_rate
- largest_single_usage
- adl_trigger_distance

6.3.5. Liquidation Fee Structure

⚠️ Liquidation Fee Structure
Component Amount
Liquidation Penalty 1.0
Insurance Fund Fee 0.5
Keeper Reward 0.1
📊 Liquidation Penalty Distribution:
50% → Insurance Fund 30% → DLP (liquidator) 20% → Protocol Treasury

6.4. Vault Withdrawal Formula

6.4.1. Margin Adequacy Check

Before withdrawing funds, the system checks whether the withdrawal will violate margin requirements.

def can_withdraw(vault: Vault, amount: uint256) -> bool:
    """
    Checks the possibility of withdrawal without violating margin requirements.
    """
   # Currentequity
    current_equity = vault.get_equity()

    # Equity after withdrawal
    equity_after = current_equity - amount

    # Required margin for openpositions
    required_margin = 0
    for position in vault.positions:
        required_margin += position.maintenance_margin

   # Minimum buffer (120% of maintenance)
    min_equity = required_margin * 1.2

    return equity_after >= min_equity


def max_withdrawable(vault: Vault) -> uint256:
    """
    Calculates the maximum possible withdrawal amount.
    """
    current_equity = vault.get_equity()
    required_margin = sum(p.maintenance_margin * 1.2 for p in vault.positions)

    return max(0, current_equity - required_margin)

6.4.2. Margin release algorithm

If the user wants to withdraw more than available_margin, the system automatically releases the margin.

Margin release order:

1. Cancellation of open orders (from lowest to highest margin)
   freed_margin += cancelled_order.locked_margin

2. If insufficient:
   Partial closing of positions (20% increments)
   - Priority: positions with the lowest unrealised_pnl

3. If still insufficient:
   Complete closing of the smallest positions

4. Repeat until freed_margin >= requested_withdrawal

Example:

Request: withdraw $50,000

Current status:
- Equity: £100,000
- Open orders locked: £20,000
- Positions MM: £40,000
- Available: £100,000 - £40,000 × 1.2 = £52,000

Step 1: $50,000 can be withdrawn without changes ✓

Alternative scenario (Available = £30,000):

Step 1: Cancel orders for £15,000 margin
       Available now = £45,000 (insufficient)

Step 2: Close 20% of the least profitable position
       Freed: £8,000 margin
       Available now = £53,000 ✓

Withdrawal of £50,000 is permitted

6.4.3. Lock-up Period

To protect DLP from sudden liquidity outflows, a lock-up period is applied.

Lock-up parameters:

DLP:
- Lock-up period: 4 days
- Early withdrawal penalty: 0.5%

User Vaults (set by the leader):
- Min lock-up: 0 days
- Max lock-up: 90 days
- Early withdrawal penalty: 0-5% (at the leader's discretion)

Withdrawable_at formula:
withdrawable_at = deposit_timestamp + lock_up_period

Exceptions:
- Emergency withdrawal (in case of critical vault state) — penalty 2%
- Governance-approved withdrawal — no penalty

6.5. Auto-Deleveraging (ADL)

ADL is a mechanism of last resort that is activated when the Insurance Fund is insufficient to cover losses.

6.5.1. Activation conditions

ADL is activated when:

1. The liquidated position has negative_equity
2. The Insurance Fund is insufficient to cover:
   insurance_fund.balance < abs(negative_equity)

Formula:
deficit = abs(liquidated_position.equity)
IF deficit > insurance_fund.balance:
    trigger_adl(deficit - insurance_fund.balance)

6.5.2. Ranking by PnL and Leverage

Opposite positions (counterparties) are selected for ADL based on rank.

ADL Rank calculation:

adl_rank = pnl_percentile × leverage_percentile

pnl_percentile:
- Sorting all positions by unrealised_pnl
- Assigning percentile (0-100%)
- Positions with high PnL = high percentile

leverage_percentile:
- Sorting by effective_leverage
- High leverage = high percentile

Example:
Position A: PnL = +$50,000 (top 10%, percentile = 90)
          Leverage = 15x (top 20%, percentile = 80)
          adl_rank = 0.90 × 0.80 = 0.72

Position B: PnL = +$10,000 (top 40%, percentile = 60)
          Leverage = 5x (top 60%, percentile = 40)
          adl_rank = 0.60 × 0.40 = 0.24

Position A will be ADL'd first

6.5.3. ADL formula

ADL Amount Calculation:

remaining_deficit = deficit - insurance_fund.balance

FOR counterparty IN sorted_by_adl_rank(counterparties):
    adl_amount = min(
        counterparty.position_size,
        remaining_deficit / mark_price
    )

    # Closing part of the counterparty's position
    close_position(counterparty, adl_amount, liquidation_price)

    remaining_deficit -= adl_amount × mark_price

    IF remaining_deficit <= 0:
        BREAK

Compensation to ADL counterparties:

ADL Premium (partial compensation):
- ADL positions are closed at mark_price
- Additionally: 0.1% premium from the closed size
- Premium source: future trading fees

Notification:
- ADL risk is displayed in the UI (light indicator)
- Traders with a high ADL rank receive a warning

6.6. Risk Management

6.6.1. Dynamic Open Interest Limits

Lessons from the JELLY incident: limiting the concentration of positions in individual assets.

Max Open Interest calculation:

max_oi(asset) = min(
    market_cap × oi_ratio,
    daily_volume × volume_ratio,
    liquidity_depth × depth_ratio)


Parameters:
- oi_ratio = 0.05 (5% of market cap)
- volume_ratio = 0.5 (50% of daily volume)
- depth_ratio = 10x (10x order book depth ±2%)

Example for a low-cap token:
- Market Cap: $50M
- Daily Volume: $5M
- Liquidity Depth (±2%): $500K

max_oi = min($50M × 0.05, $5M × 0.5, $500K × 10)
       = min($2.5M, $2.5M, $5M)
       = $2.5M

Any position > $2.5M will be rejected.

6.6.2. Caps on allocation to the Liquidation Vault

Limits for DLP:

max_single_position = dlp_tvl × 0.05  // 5% max per position
max_asset_exposure = dlp_tvl × 0.15  // 15% max per asset
max_net_exposure = dlp_tvl × 0.30    // 30% max net long/short

Example for DLP with TVL = $100M:
- max_single_position = $5M
- max_asset_exposure = $15M (all BTC positions)
- max_net_exposure = $30M (delta)

6.6.3. Protection against manipulation

Oracle Manipulation Detection:

Anomaly detection:

price_deviation = abs(new_price - twap_5min) / twap_5min

IF price_deviation > 0.10:  // >10% deviation
    flag_suspicious()
    use_fallback_oracle()

IF price_deviation > 0.20:  // >20% deviation
    halt_new_positions()
    notify_risk_committee()

Circuit Breakers:

Automatic trading halt:

Level 1 (5 min halt):
- Price move > 15% in 5 minutes
- Action: 5-minute pause

Level 2 (1 hour halt):
- Price move > 25% in 15 minutes
- Action: 1-hour pause, increase margins

Level 3 (Manual intervention):
- Price move > 40% in 1 hour
- Action: manual review, possibly settle at TWAP

Unusual Activity Monitoring:

Monitoring of suspicious activity:

1. Large position concentration
   - Alert if single account > 10% of market OI

2. Wash trading detection
   - Matching trades from same entity

3. Spoofing detection
   - Large orders cancelled within 100ms

4. Cross-market manipulation
   - Coordinated moves in spot + perp

7. Confidential Compute Layer

Confidential Compute Layer (CCL) is an innovative component of DeflationChain that provides private computations with verifiable integrity. DeflationChain significantly outperforms the Cocoon (TON) project architecture by eliminating its main drawback — centralised proxy servers. In our implementation, proxy nodes are validators with PoD stake, which provides economic motivation for honest behaviour and true decentralisation. CCL uses Intel TDX and SGX technologies for hardware protection of user data and AI models.

7.1. Overview

7.1.1. Purpose of the Confidential Compute Layer

CCL solves a fundamental problem of decentralised computing: how to perform complex computations (including AI inference) with the guarantee that:

  1. Data privacy: User input data is not visible to the computing node operator
  2. Computational integrity: The result is actually obtained from the specified model/algorithm
  3. Model protection: AI model weights are protected from copying
  4. Verifiability: Anyone can verify that the computations have been performed correctly

Main use cases:

Confidential Compute Use Cases
AI Inference
  • LLM chat
  • Image generation
  • Data analysis
  • Predictions
Private Trading
  • Hidden order flow
  • Strategy execution
Confidential contracts
  • Private voting
  • Sealed-bid auctions
  • Private state transitions
  • ZK proof generation

7.1.2. Integration with DeflationChain

CCL is integrated into DeflationChain as an optional layer available to applications requiring privacy:

DeflationChain L1
Application Layer
Public DApps
Confidential DApps
Hybrid DApps
Public + Confidential
Confidential Compute Layer
CCL Gateway
• Request routing • Result verification • Load balancing • Payment handling
TDX VM
Worker 1
(Country A)
TDX VM
Worker 2
(Country B)
TDX VM
Worker N
(Country C)
SGX Seal Server
(Key Management)
Consensus Layer (PoD)

Confidential computation execution flow:

1. User → CCL Gateway: Encrypted request + payment in DEF
2. CCL Gateway → Worker Selection: Selection of TDX VM based on availability/location
3. Gateway → Worker: Forwarding encrypted request
4. Worker: Attestation + Decryption + Computation
5. Worker → Gateway: Encrypted result + Attestation proof
6. Gateway: Verification + Settlement
7. Gateway → User: Encrypted result
8. On-chain: Payment distribution + Usage logging

7.1.3. Comparison with Cocoon

DeflationChain CCL uses a more flexible and powerful architecture than Cocoon:

Feature Cocoon (TON) DeflationChain CCL
Blockchain TON DeflationChain
Primary Use Case AI Inference AI + Trading
TEE Technology Intel TDX + SGX Intel TDX + SGX
Worker Distribution Centralised Geopolitical (1/country)
Payment Token TON DEF
GPU Support Limited Full (NVIDIA H100+)
Open Source Partial Full
Trading Integration None Native

7.2. Technical Components

7.2.1. Intel TDX Integration

Intel Trust Domain Extensions (TDX) is a hardware isolation technology that protects virtual machines from host system compromise.

Hardware requirements:

Hardware Requirements:

CPU:
- Intel Xeon Scalable (4th Gen "Sapphire Rapids" or newer)
- TDX support (check via CPUID)
- Minimum: 32 cores, 64+ cores recommended

Memory:
- DDR5 with encryption support (TME-MK)
- Minimum: 256 GB RAM
- ECC required

BIOS/Firmware:
- TDX enabled in BIOS
- Latest microcode updates
- Secure Boot enabled

Software:
- Linux Kernel 6.16+ with TDX patches
- QEMU/KVM with TDX support
- Custom TDX Guest Image (DeflationChain-certified)

TDX Guest VM architecture:

TDX Guest VM
Application Layer
LLM Inference
Image Models
Custom Models
Runtime Layer
vLLM/TensorRT
PyTorch Runtime
ONNX Runtime
Security Layer
RA-TLS Handler
Key Manager
Audit Logger
TDX-Aware OS (Linux)
Memory encryption + Attestation support
TDX Module
(Intel Hardware)

TDX security guarantees:

TDX Security Properties:

1. Memory Encryption (TME-MK):
   - All VM memory is encrypted with a unique key.
   - The key is generated by the TDX Module and is not accessible to the host.
   - AES-128-XTS encryption

2. Execution Isolation:
   - VM is isolated from the hypervisor
   - Hypervisor cannot read/write VM memory
   - Interrupt injection is restricted

3. Remote Attestation:
   - Cryptographic proof of VM configuration
   - Includes: measurements, RTMR registers, TD Quote
   - Verified against Intel attestation service

4. Integrity Protection:
   - Detection of code/data tampering
   - Replay protection for attestation

7.2.2. SGX Seal Server

SGX Seal Server is a specialised service for managing cryptographic keys using Intel SGX enclaves.

Purpose:

SGX Seal Server Functions:

1. Key Generation:
   - Key generation within the SGX enclave
   - Keys never leave the enclave in plain text

2. Key Sealing:
   - Encryption of keys tied to hardware identity
   - Persistence between reboots
   - Key rotation support

3. Key Derivation:
   - Deterministic key generation from master secret
   - Hierarchical key structure (master → domain → session)

4. Attestation Service:
   - Issuing attestation quotes for TDX VMs
   - Worker identity verification

Seal Server Architecture:

🔐 SGX Seal Server Architecture
⚠️ Untrusted Host
Network Interface
(TLS termination outside enclave)
✓ SGX Enclave (Trusted)
Request Handler
Authentication Rate limiting Request parsing Logging
🔑
Key generation
📜
Quote generation
🔒
Seal/Unseal
🔀
Derive Key
💾 Sealed Storage
master_key (sealed to MRENCLAVE)
domain_keys[] (sealed to MRSIGNER)
session_keys[] (ephemeral)

API Seal Server:

service SealServer {
    // Generate new key pair insideenclave
    rpc GenerateKeyPair(GenerateRequest) returns (GenerateResponse);

    // Seal key for persistentstorage
    rpc SealKey(SealRequest) returns (SealResponse);

   // Unseal previously sealedkey
    rpc UnsealKey(UnsealRequest) returns (UnsealResponse);

    // Derive child key frommaster
    rpc DeriveKey(DeriveRequest) returns (DeriveResponse);

    // Get attestation quote forverification
    rpc GetQuote(QuoteRequest) returns (QuoteResponse);

   // Verify attestation of another enclave/TDXVM
    rpc VerifyAttestation(VerifyRequest) returns (VerifyResponse);
}

message GenerateRequest {
    KeyType key_type = 1;  // ECDSA, Ed25519, AES256, etc.
   string purpose = 2;     // "signing", "encryption", "session"
}

message QuoteResponse {
    bytes quote = 1;        // SGX/TDX quote (attestation proof)
    bytes public_key = 2;   // Enclave's publickey
    bytes signature = 3;    // Signature over quote
}

7.2.3. RA-TLS (Remote Attestation over TLS)

RA-TLS is a protocol that integrates remote attestation into the standard TLS handshake, allowing clients to verify that they are communicating with a genuine TEE.

How it works:

RA-TLS Handshake Flow:

Client                                          TDX Worker
   │                                                 │
   │  ─────────── ClientHello ──────────────────▶   │
   │                                                 │
   │  ◀─────────── ServerHello ──────────────────   │
   │               + Certificate(RA-TLS)            │
   │               + ServerKeyExchange              │
   │               + CertificateRequest             │
   │                                                 │
   │  [Verify RA-TLS Certificate]                   │
   │    1. Extract TDX Quote from cert extension    │
   │    2. Verify Quote signature (Intel)           │
   │    3. Check RTMR values against allowlist      │
   │    4. Verify Quote freshness (timestamp)       │
   │                                                 │
   │  ─────────── Certificate ──────────────────▶   │
   │              ClientKeyExchange                 │
   │              ChangeCipherSpec                  │
   │              Finished                          │
   │                                                 │
   │  ◀─────────── ChangeCipherSpec ─────────────   │
   │               Finished                         │
   │                                                 │
   │  ═══════════ Encrypted Channel ═══════════   │
   │                                                 │

RA-TLS certificate structure:

X.509 Certificate with RA-TLS Extensions:

Certificate:
    Version: 3
    Serial Number: <random>
    Signature Algorithm: ECDSA-SHA256
    Issuer: CN=TDX Worker, O=DeflationChain
    Validity:
        Not Before: <now>
        Not After: <now + 1 hour>
    Subject: CN=TDX Worker <worker_id>
    Subject Public Key Info:
        Algorithm: ECDSA P-256
        Public Key: <ephemeral_public_key>

    X509v3 Extensions:
        1.2.3.4.1 (TDX Quote): <base64_encoded_quote>
            - RTMR[0]: <hash of firmware>
            - RTMR[1]: <hash of kernel>
            - RTMR[2]: <hash of application>
            - RTMR[3]: <hash of user data>
            - Report Data: <public_key_hash>

        1.2.3.4.2 (Worker Info):
            - Worker ID: <uuid>
            - Country: <iso_country_code>
            - Capabilities: [LLM, ImageGen, ...]

        1.2.3.4.3 (Timestamp):
- Quote Generation Time: <unix_timestamp>
- Valid Until: <unix_timestamp + validity_period>

Verification on the client:

def verify_ra_tls_cert(cert: X509Certificate, trusted_measurements: List[bytes]) -> bool:
    """
    Verify RA-TLS certificate authenticity.
    """
   # 1. Extract TDX Quote from certificateextension
    quote = extract_quote_extension(cert, OID_TDX_QUOTE)

    # 2. Verify Quote signature (Intel's attestation key)
    if not verify_intel_signature(quote):
        return False

   # 3. Check measurements againstallowlist
    rtmr_values = extract_rtmr(quote)
    for i, rtmr in enumerate(rtmr_values):
        if rtmr not in trusted_measurements[i]:
            return False

    # 4. Verify public keybinding
    report_data = extract_report_data(quote)
    cert_pubkey_hash = sha256(cert.public_key)
    if report_data[:32] != cert_pubkey_hash:
        return False

    # 5. Checkfreshness
    quote_time = extract_timestamp(quote)
    if time.now() - quote_time > MAX_QUOTE_AGE:
        return False

    return True

7.2.4. GPU Attestation

AI inference requires GPU support. DeflationChain CCL supports NVIDIA Confidential Computing.

GPU requirements:

Supported GPUs:

NVIDIA Hopper Architecture:
- H100 SXM5 (80GB HBM3)
- H100 PCIe (80GB HBM3)

Requirements:
- NVIDIA Confidential Computing mode enabled
- GPU Driver 535+ with CC support
- CUDA 12.2+

Attestation:
- GPU attestation via NVIDIA Attestation Service
- Verification of GPU firmware integrity
- Secure channel between CPU TEE and GPU

GPU Attestation Flow:

🎮 GPU Attestation Process
1 TDX VM → GPU: Request attestation
2 GPU → TDX VM: GPU Attestation Report
📋 GPU Report Contents:
GPU Model Hash Firmware Version Driver Version CC Mode Status ECC Memory Status Secure Boot Status
🔐 Signature (NVIDIA key)
3 TDX VM: Combine CPU + GPU attestation
🔗 Combined Attestation:
TDX Quote (CPU attestation) GPU Report (embedded in TD Report Data) Binding: hash(TDX Quote || GPU Report)
4 Client: Verify both CPU and GPU attestation ✓

7.3. Root Contract for Confidential Compute

7.3.1. Root Contract Overview

The Root Contract is an on-chain registry that stores information about authorised configurations, models, and workers for CCL.

Contract structure:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract ConfidentialComputeRegistry {
    // ============ Structures ============

    struct TDXImage {
        bytes32 imageHash;          // Hash of TDX VM image
        string version;             // Semantic version
        bool isActive;              // Can be used for new deployments
        uint256 registeredAt;       // Registration timestamp
        address registeredBy;       // Who registered (governance)
    }

    struct AIModel {
        bytes32 modelHash;          // Hash of model weights
        string name;                // Human-readable name
        string modelType;           // "llm", "image", "audio", etc.
        uint256 inputPricePerToken; // Price per input token (DEF wei)
        uint256 outputPricePerToken;// Price per output token
        bool isActive;
        address owner;              // Model owner (receives royalties)
    }

    struct Worker {
        address workerAddress;      // On-chain identity
        bytes32 countryCode;        // ISO 3166-1 alpha-2
        bytes publicKey;            // Worker's public key (for encryption)
        bytes32 currentQuoteHash;   // Latest attestation quote hash
        uint256 lastAttestationTime;
        WorkerStatus status;
        uint256 totalComputeUnits;  // Lifetime compute delivered
        uint256 stakeAmount;        // Staked DEF
    }

    struct Proxy {
        address proxyAddress;
        string endpoint;            // URL for client connections
        bytes32[] supportedCountries;
        bool isActive;
    }

    enum WorkerStatus {
        Inactive,
        Pending,
        Active,
        Suspended,
        Slashed
    }

    // ============ State Variables ============

    // Allowed TDX images (hash => TDXImage)
    mapping(bytes32 => TDXImage) public allowedImages;
    bytes32[] public imageHashes;

    // Registered AI models (hash => AIModel)
    mapping(bytes32 => AIModel) public registeredModels;
    bytes32[] public modelHashes;

    // Registered workers (address => Worker)
    mapping(address => Worker) public workers;
    address[] public workerAddresses;

    // Workers by country (countryCode => worker addresses)
    mapping(bytes32 => address[]) public workersByCountry;

    // Proxy endpoints
    mapping(address => Proxy) public proxies;
    address[] public proxyAddresses;

    // Governance parameters
    uint256 public minWorkerStake = 10000 * 10**18; // 10,000 DEF
    uint256 public attestationValidityPeriod = 24 hours;
    uint256 public slashingPenalty = 1000 * 10**18; // 1,000 DEF

    // ============ Events ============

    event ImageRegistered(bytes32 indexed imageHash, string version);
    event ImageDeactivated(bytes32 indexed imageHash);
    event ModelRegistered(bytes32 indexed modelHash, string name, address owner);
    event WorkerRegistered(address indexed worker, bytes32 countryCode);
    event WorkerAttestationUpdated(address indexed worker, bytes32 quoteHash);
    event WorkerSlashed(address indexed worker, uint256 amount, string reason);
    event ComputeCompleted(
        address indexed worker,
        bytes32 indexed modelHash,
        uint256 inputTokens,
        uint256 outputTokens,
        uint256 payment
    );

    // ============ Functions ============

    function registerImage(
        bytes32 imageHash,
        string calldata version
    ) external onlyGovernance {
        require(allowedImages[imageHash].registeredAt == 0, "Already registered");

        allowedImages[imageHash] = TDXImage({
            imageHash: imageHash,
            version: version,
            isActive: true,
            registeredAt: block.timestamp,
            registeredBy: msg.sender
        });

        imageHashes.push(imageHash);
        emit ImageRegistered(imageHash, version);
    }

    function registerWorker(
        bytes32 countryCode,
        bytes calldata publicKey,
        bytes calldata initialQuote
    ) external payable {
        require(msg.value >= minWorkerStake, "Insufficient stake");
        require(workers[msg.sender].workerAddress == address(0), "Already registered");
        require(
            workersByCountry[countryCode].length == 0,
            "Country slot occupied"
        );

        // Verify initial attestation quote
        bytes32 quoteHash = keccak256(initialQuote);
        require(verifyQuote(initialQuote), "Invalid attestation");

        workers[msg.sender] = Worker({
            workerAddress: msg.sender,
            countryCode: countryCode,
            publicKey: publicKey,
            currentQuoteHash: quoteHash,
            lastAttestationTime: block.timestamp,
            status: WorkerStatus.Active,
            totalComputeUnits: 0,
            stakeAmount: msg.value
        });

        workerAddresses.push(msg.sender);
        workersByCountry[countryCode].push(msg.sender);

        emit WorkerRegistered(msg.sender, countryCode);
    }

    function updateAttestation(bytes calldata quote) external {
        Worker storage worker = workers[msg.sender];
        require(worker.status == WorkerStatus.Active, "Worker not active");
        require(verifyQuote(quote), "Invalid attestation");

        worker.currentQuoteHash = keccak256(quote);
        worker.lastAttestationTime = block.timestamp;

        emit WorkerAttestationUpdated(msg.sender, worker.currentQuoteHash);
    }

    function recordCompute(
        address workerAddr,
        bytes32 modelHash,
        uint256 inputTokens,
        uint256 outputTokens
    ) external onlyProxy {
        Worker storage worker = workers[workerAddr];
        AIModel storage model = registeredModels[modelHash];

        require(worker.status == WorkerStatus.Active, "Worker not active");
        require(model.isActive, "Model not active");
        require(
            block.timestamp - worker.lastAttestationTime <= attestationValidityPeriod,
            "Attestation expired"
        );

        uint256 payment = inputTokens * model.inputPricePerToken +
                          outputTokens * model.outputPricePerToken;

        // Update worker stats
        worker.totalComputeUnits += inputTokens + outputTokens;

        // Distribute payment
        uint256 workerShare = payment * 70 / 100;  // 70% to worker
        uint256 modelOwnerShare = payment * 20 / 100; // 20% to model owner
        uint256 protocolShare = payment * 10 / 100;   // 10% to protocol

        // Transfer payments...

        emit ComputeCompleted(workerAddr, modelHash, inputTokens, outputTokens, payment);
    }

    function slashWorker(
        address workerAddr,
        string calldata reason
    ) external onlyGovernance {
        Worker storage worker = workers[workerAddr];
        require(worker.status == WorkerStatus.Active, "Worker not active");

        uint256 slashAmount = min(worker.stakeAmount, slashingPenalty);
        worker.stakeAmount -= slashAmount;
        worker.status = WorkerStatus.Slashed;

        // 50% burned, 50% to treasury
        // ...

        emit WorkerSlashed(workerAddr, slashAmount, reason);
    }

    function verifyQuote(bytes calldata quote) internal view returns (bool) {
        // 1. Parse quote structure
        // 2. Verify Intel signature
        // 3. Check RTMR values against allowed images
        // 4. Verify timestamp freshness
        // Implementation depends on attestation library
        return true; // Simplified
    }
}

7.3.2. Worker Registration Process

👷 Worker Registration Flow
1 Prerequisites
🖥️ Hardware: Intel Xeon 4th Gen+ with TDX 💿 Software: Certified TDX image 🌐 Network: Static IP, domain name 💰 Stake: Minimum 10,000 DEF
2 KYB Verification
📄 Submit legal entity documents 🏛️ Proof of jurisdiction (country) ✓ Verify no existing worker in country 👥 Approval by governance committee
3 Technical Setup
⚙️ Deploy TDX VM with certified image 🔑 Generate worker keypair inside TDX 📜 Obtain initial attestation quote 🔐 Configure networking (RA-TLS)
4 On-Chain Registration
Call registerWorker() with:
countryCode (ISO 3166-1) publicKey (from TDX) initialQuote (attestation) msg.value ≥ 10,000 DEF
✓ Status = Active upon success
5 Ongoing Requirements
🔄 Update attestation every 24 hours 📊 Maintain 99.9% uptime ⚡ Process requests promptly 🆕 Keep software up to date

7.3.3. Model Registration

Model Registration Flow:

1. Model Owner prepares model:
   - Train/fine-tune model
   - Export to supported format (ONNX, SafeTensors, etc.)
   - Calculate model hash: sha256(weights || config)

2. Encrypt model for distribution:
   - Generate content encryption key (CEK)
   - Encrypt model: AES-256-GCM(model, CEK)
   - Encrypt CEK for each worker: ECIES(CEK, worker_pubkey)

3. Upload to decentralised storage:
   - IPFS / Arweave / Filecoin
   - Distribute encrypted CEKs to workers

4. Register on-chain:
   registerModel(
       modelHash,
       name,
       modelType,
       inputPrice,
       outputPrice,
       contentURI
   )

5. Workers download and verify:
   - Fetch encrypted model from storage
   - Decrypt CEK using worker private key (inside TDX)
   - Decrypt model
   - Verify hash matches registered modelHash
   - Load model into inference runtime

7.4. Pricing Model

7.4.1. Compute Pricing

💰 Compute Pricing Structure
Model Type Input Price Output Price
LLM (7B params) 0.001 DEF/1K tok 0.002 DEF/1K tok
LLM (70B params) 0.005 DEF/1K tok 0.010 DEF/1K tokens
LLM (400B+ params) 0.020 DEF/1K tokens 0.040 DEF/1K tok
Image Gen (SD) 0.01 DEF/image
Image Gen (FLUX) 0.05 DEF/image
Audio (Whisper) 0.001 DEF/min
Embeddings 0.0001 DEF/1K tok
📊 Revenue Distribution:
70% → Worker 20% → Model Owner 10% → Protocol (5% burn, 5% treasury)

7.4.2. Staking Requirements

Worker Staking:

Minimum Stake: 10,000 DEF

Stake Functions:
1. Slashing collateral (for misbehaviour)
2. Quality of service guarantee
3. Economic alignment with network

Slashing Conditions:
- Invalid attestation: 10% of stake
- Prolonged downtime (>24h): 5% of stake
- Incorrect computation (proven): 20% of stake
- Data leak (proven): 100% of stake

Unstaking:
- Unbonding period: 30 days
- Can exit during unbonding (forfeit pending rewards)

8. Deflationary Economic Model

The deflationary economic model is the foundation of DeflationChain, inherited and expanded from the original DeflationCoin on BSC. The model provides a continuous reduction in the circulating supply of tokens, creating long-term deflationary pressure on supply and, theoretically, a positive impact on value.

8.1. Daily Smart Burning

8.1.1. BalancePortions Mechanism

A key innovation of DeflationCoin is the BalancePortions system, which tracks the time each portion of tokens is received and applies progressive burning.

BalancePortion structure:

struct BalancePortion {
    uint256 amount;     // Number of tokens in a portion
    uint256 timestamp;  // Time of portion receipt
}

// Each address stores an array of portions
mapping(address => BalancePortion[]) private _balancePortions;

How it works:

When tokens are received:
1. A new BalancePortion is created with the current timestamp
2. The portion is added to the address array

When tokens are sent:
1. refresh_balance() is called to update the balance
2. Effective balance = Σ(portion.amount × getMultiplier(portion.timestamp))
3. The difference between the nominal and effective balances is the "burned" portion.
4. 50% of the difference is permanently destroyed.
5. 50% of the difference is sent to the dividend pool.

Portion expenditure logic (FIFO):
1. The oldest portions are spent first
2. Older portions have a lower effective_amount
3. The user loses less when using "fresh" tokens

Example:

Day 0: The user receives 1,000 DEF
        BalancePortions = [{amount: 1000, timestamp: Day0}]
        Effective balance = 1000 × 100% = 1,000 DEF

Day 3: The user receives another 500 DEF
        BalancePortions = [
          {amount: 1000, timestamp: Day0},
          {amount: 500, timestamp: Day3}
        ]
        Effective balance = 1000 × 93% + 500 × 100% = 930 + 500 = 1,430 DEF
        Nominal balance = 1,500 DEF
        "Burned" = 70 DEF

Day 5: User wants to send 1,200 DEF
        First, refresh_balance():
        - Portion 1: 1000 × 71% = 710 DEF effective
        - Portion 2: 500 × 97% = 485 DEF effective
- Total effective = 1,195 DEF

ERROR: Not enough funds to send 1,200 DEF!
Maximum amount that can be sent is 1,195 DEF

8.1.2. Doubling Burn Principle

The Daily Smart Burn system uses the doubling principle: every day, the burn percentage of the current balance doubles. This creates exponential pressure on inactive holders, while giving them enough time to react in the early days.

Key features of the doubling principle:

This approach encourages one of two actions: staking tokens (full protection + dividends) or using them regularly (resetting the burn timer with each transaction).

Doubling principle — daily burning from the balance
Day 1
1
→ 99%
Day 2
2
→ 97%
Day 3
4
→ 93%
Day 4
8
→ 85%
Day 5
16
→ 71%
Day 6
32
→ 48%
Day 7
64
→ 17%
Day 8
100
→ 0%
dailyBurn[t] = min(2(t−1), 100) %
remaining[t] = remaining[t−1] × (100 − dailyBurn[t]) 100
where: t — day from the moment of receiving tokens (0–8)

Full table:

Day Daily burn from balance Cumulative balance Comment
0 0 100 No burning
1 1 99 Soft start
2 2 97 Doubling
3 4 93 Doubling
4 8 85 Start of acceleration
5 16 71 Noticeable losses
6 32 48 More than half
7 64 17 Critical losses
8 100 0 Complete depreciation

The doubling principle creates a characteristic S-shaped loss curve: a gentle slope at the beginning (days 1-3, ~7% lost), a steep decline in the middle (days 4-6, the bulk is lost) and a final reset to zero (days 7-8). This curve shape is optimal for balancing the protection of forgetful users and the effective burning of "dead" tokens.

getBurnRate function:

This function implements on-chain logic for determining the burn rate based on the age of the balance portion. The function is optimised for minimal gas consumption and uses a pre-calculated array of values.

function getBurnRate(uint256 timestamp) public view returns (uint256) {
    uint256 daysElapsed = (block.timestamp - timestamp) / 86400;

    if (daysElapsed == 0) return 0;    // 0% burn
    if (daysElapsed >= 8) return 100;  // 100% burn

    // burnRate is indexed from day 1
    // burnRate = [1, 3, 7, 15, 29, 52, 83]
    // burnRate[0] = 1 (day 1 → 1% burn)
    return burnRate[daysElapsed - 1];
}

function getPreservedRate(uint256 timestamp) public view returns (uint256) {
    return 100 - getBurnRate(timestamp);  // Preserved portion
}

The implementation uses integer arithmetic with percentage accuracy. For more accurate calculations in financial transactions, scaling with a coefficient of 10^18 can be applied.

Mathematical model of burning:

The mathematical model formalises the progressive burning mechanism and allows predicting the effective balance for any wallet state.

Let N(t) be the user's nominal balance at time t
Let P_i be the i-th portion with timestamp t_i and amount a_i

Preservation coefficient:
S(d) = (100 - burnRate[min(d, 8)]) / 100

Effective balance:
E(t) = Σ_i (a_i × S(t - t_i))

where burnRate = [0, 1, 3, 7, 15, 29, 52, 83, 100]

Burning amount:
Burned(t) = N(t) - E(t) = Σ_i (a_i × burnRate[min(t - t_i, 8)] / 100)

Since S(d) is a step function, burning occurs discretely when crossing day boundaries. This means that balance updates can be postponed without loss of accuracy — the final result will be identical to a daily update.

8.1.3. Distribution of Burned

With each refresh_balance(), the difference between the nominal and effective balances is distributed:

refresh_balance() logic:

previous_nominal = sum(portions[].amount)
effective = sum(portions[].amount × getMultiplier(portions[].timestamp))

diff = previous_nominal - effective

if (diff > 0):
    burned = diff / 2          // 50% is destroyed forever
    to_dividend = diff / 2     // 50% goes to the dividend pool

    totalSupply -= burned
    dividendPool += to_dividend

    emit Burned(burned)
    emit DividendPoolIncreased(to_dividend)

Annual burn statistics (forecast):

The annual burn volume depends on the average holding time of tokens between transactions. The longer the tokens remain inactive, the more of them are burned. Below are calculations for different user behaviour scenarios.

Scenario 1: Active traders (average holding period of 3 days)
─────────────────────────────────────────────────────────
- Average burn rate = (0 + 1 + 3 + 7) / 4 = 2.75%
- With 120 trading cycles per year:
  Preserved share = (1 - 0.0275)^120 ≈ 3.5% lost

Scenario 2: Moderately active (average holding period of 5 days)
─────────────────────────────────────────────────────────
- Average burn rate = (0 + 1 + 3 + 7 + 15 + 29) / 6 = 9.2%
- With 72 cycles per year: significant losses

Scenario 3: Passive holders (8+ days retention)
─────────────────────────────────────────────────────────
- Full burn after 8 days
- Incentive: MUST stake or transfer

Burn protection strategies:
1. Staking — full protection + dividends
2. Active trading — reset the timer with each transaction
3. Regular transfers — periodic reset

This model creates unique economic pressure: passive holding ("hodl" without staking) is economically disadvantageous, while active participation in the ecosystem through staking or trading is rewarded with capital protection.

8.2. Smart Commissions

8.2.1. Standard commission (5%)

Each DEF transfer is subject to a 5% commission, which is distributed as follows:

Standard transfer (without referral):

total_commission = amount × 5%

Distribution:
Recipient Share Purpose
Burn 1% (20%) Destruction of tokens
Dividend Pool 1% (20%) Dividends to stakers
Technical Pool 1% (20%) Protocol development
Marketing Pool 2% (40%) Marketing and promotion

Example: - Transfer: 10,000 DEF - Commission: 500 DEF - Burn: 100 DEF - Dividend Pool: 100 DEF - Technical Pool: 100 DEF - Marketing Pool: 200 DEF - Recipient receives: 9,500 DEF

8.2.2. Referral commission (4.5%)

If there is a referral, the commission is reduced to 4.5%, and half goes to the referrer:

🎁 Referral Commission (4.5%)
total_commission = amount × 4.5%
Recipient Share Purpose
🔥 Burn 2.25% (50%) Token destruction
💰 Referral Wallet 2.25% (50%) Referral reward
✨ Advantages of the referral system:
Sender: 4.5% instead of 5% Referrer: passive income Burn: 2.25% vs 1%

8.2.3. Exceptions to commissions

Addresses exempt from commissions:
- Staking contract (when staking/unstaking)
- Dividend Pool (when distributing)
- Trading Core (for effective trading)
- Bridge contracts (when migrating)
- Validator rewards distribution

Check in _transfer():
if (excludedFromFee[sender] || excludedFromFee[recipient]) {
    fee = 0;
}

8.3. Smart Staking

8.3.1. xMultipliers

xMultipliers determine the dividend bonus depending on the staking period:

xMultipliers = [1, 2, 3, 4, 5, 6, 7, 10, 12, 14, 16, 20]
Full table of xMultipliers
Term (years) Multiplier Comment
1 1x Base level
2 2x
3 3x
4 4x Minimum for validators
5 5x
6 6x
7 7x
8 10x ⚡ Jump — reward for long-term
9 12x
10 14x
11 16x
12 20x 🏆 Maximum bonus
ROI comparison:
With the same number of staked tokens:
  • A 12-year staker receives 20 times more dividends than a 1-year staker
  • This is a strong incentive for long-term loyalty

8.3.2. Attention Grabbing Mechanism

When creating a stake for less than 12 years, 1% of the amount is automatically staked for 12 years:

Attention Grabbing Logic:

function stake(uint256 amount, uint256 years) {
    require(years >= 1 && years <= 12, "Invalid staking period");

    if (years < 12) {
        // 1% automatically for 12 years
        uint256 attentionGrab = amount / 100;
        uint256 mainStake = amount - attentionGrab;

        _createStake(msg.sender, mainStake, years);
        _createStake(msg.sender, attentionGrab, 12);
    } else {
        _createStake(msg.sender, amount, 12);
    }
}

Example:
A user stakes 10,000 DEF for 4 years:
- Main stake: 9,900 DEF for 4 years (4x multiplier)
- Attention grab: 100 DEF for 12 years (20x multiplier)

Effect:
- The user is "tied" to the project for 12 years through a mini-stake
- Even after the 4-year stake ends, the 12-year stake remains
- Creates a psychological connection to the project

8.3.3. StakePosition Structure

Each staking position is represented by a StakePosition structure that stores all the information necessary for calculating dividends, tracking withdrawals, and managing lock-up periods. The structure is optimised for gas efficiency: all time parameters are stored as uint256 for compatibility with block.timestamp, and financial indicators use full Wei precision (10^18).

A key feature is the separation of amount and finishedAmount: the former tracks the current locked amount (decreasing with monthly withdrawals), while the latter tracks the amount available for smooth unlocking after the staking period ends. This allows users to obtain partial liquidity during the stake term while retaining their right to dividends.

struct StakePosition {
    uint256 initialAmount;      // Initial stake amount (unchanging)
    uint256 amount;             // Current amount (may decrease with withdrawals)
    uint256 finishedAmount;     // Amount for smooth unlocking after the end
    uint256 startTime;          // Unix timestamp of stake creation
    uint256 year;               // Staking term (1-12 years)
    uint256 lastClaimed;        // Last dividend claim (YYYYMM format)
    uint256 claimedStaking;     // Withdrawn from the principal amount in the current month
    uint256 claimedDividends;   // Dividends withdrawn in the current month
}

// Each user can have multiple stake positions
mapping(address => StakePosition[]) private _stakes;

The lastClaimed field uses the YYYYMM format (e.g., 202501 for January 2025), which allows you to effectively check whether dividends for the current month have already been received. The claimedStaking and claimedDividends fields are reset to zero at the start of a new month, providing fresh withdrawal limits.

8.3.4. Monthly withdrawal from stake

A unique feature of DeflationChain is the ability to make partial withdrawals from active staking without losing status and accumulated privileges. Unlike most PoS systems, which require full unstaking to obtain liquidity, DeflationChain allows stakers to withdraw up to 1/N of the amount each month, where N is the total number of months of staking.

This mechanism solves a critical liquidity problem for long-term stakers: a user with a 12-year stake can receive a portion of their funds when needed without losing the 20x dividend multiplier on the remaining amount. This makes long-term commitments less risky and increases the attractiveness of maximum staking periods.

Monthly withdrawal formula:
SM = Samount Y × 12
where: SM is the maximum withdrawal amount per month, Samount — current stake amount, Y — stake term in years
Withdrawal examples
Stake SM Note
12,000 DEF / 1 year 1,000 DEF/month Full withdrawal in 12 months
12,000 DEF / 4 years 250 DEF/month Full withdrawal over 48 months
12,000 DEF / 12 years 83.33 DEF/month Full withdrawal in 144 months
Upon withdrawal:
  • stake.amount decreases
  • stake.claimedStaking increases
  • When a new month is reached, claimedStaking is reset

8.3.5. Gradual unlock after completion

The gradual unlock mechanism is a key element in protecting the token price from sharp fluctuations. After the staking period ends, tokens are not returned to the user instantly, but are unlocked gradually over a period proportional to the staking period.

This approach solves the problem of "cliff unlock" — a situation where a large number of tokens become available for sale at the same time, putting pressure on the price. Instead, DeflationChain distributes the unlock over time, creating a predictable and manageable flow of liquidity.

Smooth unlock formula:

unlock_period = stake.year × 30 days
daily_unlock = stake.finishedAmount / unlock_period

Time frames:
- 1-year stake: unlock in 30 days  (3.33% per day)
- 4-year stake: unlock in 120 days (0.83% per day)
- 12-year stake: unlock in 360 days (0.28% per day)

Important: during the gradual unlock period, the user continues to receive dividends on the portion that has not yet been unlocked (albeit with a reduced multiplier). This encourages users not to rush to withdraw and to view unlocking as a continuation of staking. Users can also re-stake unlocked tokens for a new term at any time.

8.4. Dividend System

8.4.1. Beta Indicator

Beta (β) is a global indicator used to calculate each staker's share in the dividend pool:

β = Σ(stake.amount × xMultipliers[stake.year - 1])

For all active stakes in the system.

Example of β calculation:
Stake 1: 10,000 DEF × 4x (4 years) = 40,000
Stake 2: 5,000 DEF × 12x (9 years) = 60,000
Stake 3: 20,000 DEF × 1x (1 year) = 20,000...

β = 40,000 + 60,000 + 20,000 + ... = total weighted stake

8.4.2. Dividend Formula

D(S) = Amount ×Xmult ×Psnapshot β
where D(S) — dividends for stake S, Samount — stake amount, Xmult is the multiplier for the term, Psnapshot — snapshot of the dividend pool, β — total weighted stake

Calculation example:

- poolSnapshot = dividend pool balance at the beginning of the period - β = total beta of all stakes Example: - Stake: 10,000 DEF for 8 years (10x multiplier) - poolSnapshot = 100,000 DEF (monthly dividend pool) - β = 5,000,000 (total weighted stake of the network) D = (10,000 × 10 × 100,000) / 5,000,000 D = 10,000,000,000 / 5,000,000 D = 2,000 DEF The staker will receive 2,000 DEF in dividends for the period.

8.4.3. Frequency and snapshot

Dividend cycle:

1. Snapshot (1st day of each month, 00:00 UTC):
   - poolSnapshot = dividend_pool.balance is fixed
   - β = sum of all weighted stakes is fixed
   - Recorded in the contract as snapshot[month]

2. Claim period (entire month):
   - Stakers can claim dividends
   - Dividends are calculated using the formula above
   - Upon claiming: stake.claimedDividends increases

3. Next month:
   - New snapshot
   - claimedDividends is reset for everyone
   - Unclaimed dividends remain in the pool

Auto-compound option:
- The user can enable auto-stake for dividends
- Dividends are automatically added to the existing stake
- Increases S.amount without creating a new position

8.5. Tokenomics Overview

8.5.1. Sources of Burning

Token burning occurs from a variety of sources:

🔥 Token burn sources
Source Mechanism
Daily Smart Burn 50% of progressive burning
Transfer Commission 1% of each transfer
Referral Commission 2.25% of referral transfers
Trading Fees 20% of Trading Core commissions
Gas Fees 20% of gas fees
Slashing 50% of slashed stakes
DLP Fees 20% of vault fees
CCL Protocol Fees 5% of compute payments

8.5.2. Supply Model

Supply Model:

Initial Supply (when migrating from BSC): S_0

Annual change in supply:
S(t+1) = S(t) - B(t) + R(t)

Where:
- B(t) = total burn for the year
- R(t) = rewards to validators (inflationary component)

Target: B(t) > R(t) → net deflation

Estimated annual burn:
- Daily burn (avg 5% circulation × 10% loss × 50%): ~2.5% per annum
- Commission burn: ~0.5% per annum
- Trading/Gas burn: ~1% per annum
- Total burn: ~4% per annum

Inflation from validator rewards: ~2% per annum

Net deflation: ~2% per annum (with normal activity)

8.5.3. Long-term Equilibrium

Long-term equilibrium:

As supply decreases:
1. The price per token increases (with constant demand)
2. Absolute burn decreases (same %)
3. The rate of deflation slows down

Asymptotic behaviour:
- Supply tends towards a certain S_min
- S_min is determined by the balance:
  burned_from_circulation = validator_rewards + network_growth

Protection against hyper-deflation:
- Governance can regulate burning parameters (burnRate)
- Emergency mechanism to reduce burn rate
- Supply is not expected to reach 0

9. Network Level

The DeflationChain network level provides reliable, fast and secure communication between all network participants: validators, full nodes, light clients and external applications.

9.1. P2P Protocol

9.1.1. Basic Architecture

DeflationChain uses libp2p as the foundation for P2P communications, ensuring modularity and compatibility with existing infrastructure.

Protocol stack:

libp2p Protocol Stack
Application Protocols
Block Sync
Tx Gossip
State Sync
Pub/Sub Layer
(GossipSub Protocol)
Multiplexing Layer
(Yamux / Mplex Stream Multiplexer)
Security Layer
(Noise Protocol / TLS 1.3)
Transport Layer
(TCP / QUIC / WebSocket / WebRTC)
Discovery Layer
(Kademlia DHT / mDNS / DNS)

Supported transports:

Transport Usage
TCP Primary transport for validators and full nodes
QUIC Low-latency communication, NAT traversal
WebSocket Browser clients, WebSocket RPC
WebRTC P2P communications in browsers

9.1.2. GossipSub Protocol

GossipSub is a message distribution protocol for P2P networks developed by Protocol Labs for libp2p. DeflationChain uses GossipSub v1.1 with additional optimisations for low-latency trading data.

GossipSub works on a mesh topology: each node maintains a small number of direct connections (mesh peers, usually 8) for each topic. Messages are distributed through the mesh with flood publishing for priority data. Additionally, nodes "gossip" about recent messages with peers outside the mesh, ensuring resilience to mesh connection failures.

A critical advantage of GossipSub is sub-second propagation even in global networks. For DeflationChain, this means that consensus messages reach all validators in 200ms, blocks propagate across the network in a second, and trade updates are delivered in 50-100ms.

Channels:

DeflationChain organises messages into topics (channels), each with its own semantics and propagation policy. Block and consensus topics use flood publishing for maximum reliability, while trading topics are optimised for low latency.

DeflationChain GossipSub Topics:

/deflationchain/1.0.0/blocks
  - New blocks
  - Publishers: block proposers
  - Subscribers: all nodes

/deflationchain/1.0.0/transactions
  - Pending transactions
  - Publishers: any participant
  - Subscribers: validators, full nodes

/deflationchain/1.0.0/consensus
  - Consensus messages (prevote, precommit)
  - Publishers: validators
  - Subscribers: validators

/deflationchain/1.0.0/attestations
  - Attestations for finality
  - Publishers: validators
  - Subscribers: all nodes

/deflationchain/1.0.0/trading/orderbook
  - Order book updates
  - Publishers: Trading Core
  - Subscribers: trading clients

/deflationchain/1.0.0/trading/trades
  - Executed trades
  - Publishers: Trading Core
  - Subscribers: trading clients

GossipSub parameters:

The GossipSub configuration in DeflationChain is optimised to balance delivery reliability and bandwidth efficiency. The parameter D=8 means that each node supports 8 mesh peers per topic — enough to withstand the loss of several peers, but without creating excessive load.

Heartbeat every second allows you to quickly detect unavailable peers and rebuild the mesh. History length=5 heartbeats means that the node remembers the messages of the last 5 seconds to detect duplicates and respond to gossip requests.

GossipSub Configuration:

D = 8            // Target degree (number of mesh peers)
D_lo = 6         // Minimum degree
D_hi = 12        // Maximum degree
D_lazy = 6       // Lazy push gossip degree

heartbeat_interval = 1s
history_length = 5       // Messages are stored for 5 heartbeats
history_gossip = 3       // Gossip about the last 3 heartbeats

fanout_ttl = 60s         // TTL for fanout peers
gossip_factor = 0.25     // Proportion of peers for gossip

Flood publishing: enabled for high-priority messages (blocks, consensus)

Latency targets:

Latency targets are critical for different types of messages. For consensus, fast delivery between validators (200ms) is important — exceeding this leads to increased block time. For trading, minimum latency (50ms) is critical — otherwise users will trade on CEX. For regular transactions, a longer latency (500ms) is acceptable.

The table below shows 95th percentile targets — 95% of messages must fit within the specified time. This is a stricter criterion than average latency, as tail latency is critical to the user experience.

Message Propagation Latency
Message Type Target Latency Notes
Transaction < 500ms 95th percentile globally
Block < 1s To 99% of validators
Consensus Message < 200ms Between validators
Trading Order < 50ms To Trading Core
Order Book Update < 100ms To all trading clients

9.1.3. Peer Discovery

Peer discovery is a fundamental task for a P2P network: how does a new node find other participants? DeflationChain uses a multi-level approach, combining several mechanisms to ensure reliable discovery in various network conditions.

The first level is hardcoded bootstrap nodes. These are stable, highly available nodes managed by the DeflationChain Foundation, whose addresses are hardcoded into the client. They serve as an entry point for new nodes.

The second level is Kademlia DHT (Distributed Hash Table). After connecting to bootstrap nodes, the node joins the DHT and can find other participants by their peer ID. DHT scales to millions of nodes with logarithmic search complexity.

The third level is DNS-based discovery. DNS TXT records contain the current addresses of active nodes. This allows you to update the list of endpoints without changing the client code.

Kademlia DHT:

Kademlia is a decentralised key-value storage system used for peer discovery. Each node has a 256-bit ID, and the distance between nodes is calculated as the XOR of their IDs. This creates a structure where each node knows more about its "close" (by XOR metric) peers and can efficiently route requests to any ID in O(log N) steps.

Kademlia Configuration:

K = 20              // Bucket size
α = 3               // Parallelism factor
β = 3               // Disjoint paths for lookup

Key space: 256-bit (SHA-256 of peer ID)
Distance metric: XOR

Bootstrap nodes:
- Hardcoded list of 10+ geographically distributed nodes
- DNS-based discovery: _dht.deflationchain.io

Refresh interval: 1 hour
Record TTL: 24 hours

DNS-based Discovery:

DNS-based discovery uses standard DNS infrastructure to distribute node information. Advantage: DNS is updated centrally but distributed through a global network of caching DNS servers. This allows the node list to be updated quickly when changes occur in the network.

DNS Records:

_dnsaddr.deflationchain.io TXT
  → "dnsaddr=/ip4/1.2.3.4/tcp/30333/p2p/12D3KooW..."
  → "dnsaddr=/ip4/5.6.7.8/tcp/30333/p2p/12D3KooW..."

Advantages:
- Updatable endpoints without changing the client
- Geographic load balancing via DNS
- Fallback when DHT is unavailable

mDNS (Local Discovery):

mDNS enabled for:
- Development environments
- Private networks
- LAN-based validators

Service name: _deflationchain._tcp.local

9.1.4. Peer Scoring

Peer Scoring is a reputation mechanism in GossipSub that allows reliable nodes to be distinguished from problematic or malicious ones. Each peer is assigned a numerical score that affects connection priority, mesh peer selection, and disconnection decisions.

The score is accumulated from several components. The topic score reflects behaviour in specific topics: delivering valid messages increases the score, while sending invalid messages decreases it. The application score takes into account the specifics of DeflationChain: validators with high uptime receive a bonus. The IP score allows Sybil attacks to be detected: multiple peers from the same IP/subnet receive a lower score.

Important: the score is not used for censorship. Even a peer with a low score can send transactions and receive blocks — it just won't be selected in the mesh and its messages will have a lower priority. This protects against DoS without violating the permissionless nature of the network.

Peer Score Components:

P = w1×P_topic + w2×P_app + w3×P_ip + w4×P_behaviour

where:
- P_topic: behaviour in GossipSub topics
- P_app: application-specific metrics
- P_ip: reputation by IP/subnet
- P_behaviour: general behaviour (latency, uptime)

Topic Score (P_topic):
- Mesh delivery: +points for delivering valid messages
- First message deliveries: +bonus for the first delivery
- Invalid messages: -penalty for invalid messages
- Mesh time: +bonus for stable presence in the mesh

Score Thresholds:
- GossipThreshold = -500   // Below — no gossip to this peer
- PublishThreshold = -1000 // Below — no publish to peer
- GraylistThreshold = -3000 // Temporary ban
- BlacklistThreshold = -10000 // Permanent ban

9.2. Block Synchronisation

Block synchronisation is the process through which a new or lagging node obtains the current state of the blockchain. DeflationChain supports three synchronisation modes optimised for different use cases.

9.2.1. Full Sync

Full Sync is the most reliable but slowest method of synchronisation. The node downloads all blocks from genesis, executes all transactions, and independently restores the current state. Advantage: complete independence from trust assumptions — the node cryptographically verifies each block. Disadvantage: synchronisation time increases linearly with the age of the chain.

Full sync is recommended for archive nodes (which store the complete history), for validators during initial setup, and in cases where maximum verification without trust in third parties is important.

Full Sync Protocol:

1. Peer Discovery:
   - Find peers with higher block height
   - Prioritise peers with good scores

2. Header Download:
   - Request headers in batches of 1000
   - Verify header chain (hashes, signatures)
   - Parallel download from multiple peers

3. Body Download:
   - Request block bodies for received headers
   - Parallel download with priority by age

4. State Reconstruction:
   - Execute all transactions sequentially
   - Build state trie
   - Verify state root against header

5. Catch-up:
   - After sync, switch to gossip for new blocks

Performance Targets:
- Header sync: 10,000 headers/sec
- Block sync: 100 blocks/sec (depending on block size)
- Total time for 1M blocks: ~3 hours

9.2.2. Fast Sync (Snap Sync)

Snap Sync is an optimised mode for quickly starting a new node. Instead of executing all historical transactions, the node downloads a snapshot of the current state (state trie) directly and then synchronises only the latest blocks.

The key idea: the state trie is cryptographically linked to the block header (via the state root). If the downloaded state matches the state root in the block header signed by 2/3+ validators, the state is guaranteed to be correct — no need to re-execute history.

Snap sync is significantly faster than full sync: downloading 100GB of state takes about an hour, compared to days for full sync on a mature chain. This is the recommended mode for regular full nodes and RPC providers.

Snap Sync Protocol:

1. Find Pivot Block:
   - Get block height from several peers
   - Select pivot = max_height - 128 (safety margin)

2. Download State Snapshot:
   - Request state trie starting from root
   - Parallel download by account ranges
   - Streaming state download

3. Verify Snapshot:
   - Compute state root
   - Compare with pivot block header

4. Sync Recent Blocks:
   - Download blocks from pivot to current
   - Execute transactions to update state

5. Switch to Full Node:
   - After sync, the node can serve requests

Performance:
- State download: ~1 hour for 100GB state
- Significantly faster than full sync for mature chains

9.2.3. Light Client Sync

Light Clients — minimalistic mode for devices with limited resources (mobile phones, browsers, IoT). Instead of storing the full state, a light client only synchronises block headers and requests specific data (balances, transactions) as needed via Merkle proofs.

A Merkle proof is cryptographic proof that a specific value is included in the state trie. The proof has a size of O(log N) of the state size and can be verified against the state root in the header. This allows the light client to verify the correctness of the data without trusting the full node from which it received it.

Light clients are ideal for wallets: the user only needs their balance and the ability to send a transaction. Storing ~50 bytes per block allows a million blocks to be synchronised in 50MB — acceptable even for a mobile application.

Light Client Protocol:

1. Header Sync:
   - Download block headers only
   - Verify validator signatures
   - Track finalised head

2. State Proofs:
   - When requesting balance/storage:
   - Request Merkle proof from full node
   - Verify proof against header state root

3. Transaction Submission:
   - Broadcast via full nodes
   - Monitor inclusion via light sync

Storage Requirements:
- Headers only: ~50 bytes per block
- 1M blocks ≈ 50 MB
- Suitable for mobile/browser clients

9.3. RPC Interface

RPC (Remote Procedure Call) is an interface for applications to interact with the blockchain. DeflationChain provides a fully Ethereum-compatible API that allows you to use existing tools (MetaMask, ethers.js, web3.py) without modification, as well as extensions for specific functions (deflation, staking, trading).

9.3.1. JSON-RPC (Ethereum-compatible)

JSON-RPC is a standard protocol for Ethereum RPC. Each request contains the method name and parameters in JSON format, and the response contains the result or error. It is a synchronous request-response protocol, usually running on top of HTTP or WebSocket.

DeflationChain implements a complete set of standard eth_, net_, web3_* methods, ensuring compatibility with the existing Ethereum tooling ecosystem. This is critical for adoption: developers can port dApps without changing the code.

Standard Ethereum methods:

Below is a list of supported standard methods. Each works identically to Ethereum, ensuring drop-in compatibility.

eth_blockNumber
eth_getBlockByNumber
eth_getBlockByHash
eth_getTransactionByHash
eth_getTransactionReceipt
eth_sendRawTransaction
eth_call
eth_estimateGas
eth_getBalance
eth_getCode
eth_getStorageAt
eth_getLogs
eth_chainId
eth_gasPrice
eth_feeHistory
net_version
net_listening
web3_clientVersion

DeflationChain-specific methods:

In addition to the standard Ethereum API, DeflationChain provides def_* methods to access unique functionality: effective balances taking deflation into account, staking positions, validator information, PoD metrics. These methods are necessary for correctly displaying the status in wallets and dApps.

Important: eth_getBalance returns the nominal balance (number of tokens received), while def_getEffectiveBalance returns the actual balance taking into account progressive burning. To display the balance to the user, always use def_getEffectiveBalance.

def_getEffectiveBalance(address)
  → Returns effective balance after applying burnRate

def_getBalancePortions(address)
  → Returns array of BalancePortions with timestamps

def_getStakingPositions(address)
  → Returns array of StakePositions

def_getDividendInfo(address, month)
  → Returns dividend amount for staking position

def_getValidatorInfo(address)
  → Returns validator status, weight, country

def_getPoDWeight(address)
  → Returns Proof-of-Deflation weight

def_getBeta()
  → Returns current global beta indicator

def_getDividendPoolBalance()
  → Returns current dividend pool balance

9.3.2. Trading Core RPC

Trading Core RPC is a specialised API for interacting with DeflationChain's centralised order book and matching engine. These methods are optimised for minimal latency, which is critical for trading.

An important difference from standard blockchain RPCs is that trading operations are processed by an off-chain matching engine and enter the blockchain already executed. This provides CEX speed while maintaining on-chain settlement and custody.

The trade_* methods are available through a separate endpoint (trade.deflationchain.io), optimised for low latency, with geographically distributed entry points to minimise network delays.

trade_placeOrder(params)
  → Place new order

trade_cancelOrder(orderId)
  → Cancel existing order

trade_getOpenOrders(address)
  → Get all open orders for address

trade_getOrderHistory(address, limit)
  → Get order history

trade_getPositions(address)
  → Get all open positions

trade_getAccountInfo(address)
  → Get margin, equity, available balance

trade_getOrderbook(market, depth)
  → Get current order book

trade_getTrades(market, limit)
  → Get recent trades

trade_getFundingRate(market)
  → Get current/predicted funding rate

trade_getMarkPrice(market)
  → Get current mark price

9.3.3. WebSocket Subscriptions

WebSocket is a protocol for bidirectional real-time communication. Unlike HTTP (request-response), WebSocket allows the server to push data to the client without a request. This is critical for trading interfaces where updates must come instantly.

DeflationChain supports standard Ethereum subscriptions (newHeads, logs, pendingTransactions) plus specific trading subscriptions for order books and trades. The client subscribes once and receives all subsequent updates without polling.

Advantages of WebSocket over HTTP polling: minimal latency (data arrives immediately after the event), efficiency (no overhead from constant HTTP requests), and bandwidth savings (only useful data, no HTTP headers).

WebSocket Endpoint: wss://rpc.deflationchain.io/ws

Subscription Types:

1. New Blocks:
   {"method": "eth_subscribe", "params": ["newHeads"]}
   → Emits block header on each new block

2. Pending Transactions:
   {"method": "eth_subscribe", "params": ["newPendingTransactions"]}
   → Emits tx hash for each new pending tx

3. Logs:
   {"method": "eth_subscribe", "params": ["logs", {"address": "0x..."}]}
   → Emits matching log events

4. Orderbook Updates:
   {"method": "trade_subscribe", "params": ["orderbook", "BTC-PERP"]}
   → Emits orderbook deltas

5. Trade Feed:
   {"method": "trade_subscribe", "params": ["trades", "BTC-PERP"]}
   → Emits each executed trade

6. Position Updates:
   {"method": "trade_subscribe", "params": ["positions", "0x..."]}
   → Emits position changes for address

7. Account Updates:
   {"method": "trade_subscribe", "params": ["account", "0x..."]}
   → Emits balance/margin changes

9.3.4. AI/CCL RPC

CCL RPC is an API for interacting with the Confidential Compute Layer, allowing you to request AI inference with guaranteed privacy. These methods differ from standard RPCs: requests are encrypted with the TEE worker's public key, and responses are decrypted only by the client.

Interaction process: the client selects a model and worker (or allows the protocol to select automatically), encrypts the input with the worker's public key, and sends the request. The worker performs inference inside the TEE and returns the encrypted result. No one, including the worker operator, sees either the request or the response.

For common use cases (ChatGPT-like interface), there are SDKs that abstract cryptography. Developers only need to call ccl_chat() — encryption and decryption happen automatically.

ccl_getModels()
  → List available AI models

ccl_getWorkers()
  → List registered workers

ccl_getWorkersByCountry(countryCode)
  → Get workers in specific country

ccl_submitRequest(params)
  → Submit confidential compute request
  params: {
    model: "model_hash",
    input: "encrypted_input",
    worker: "preferred_worker" (optional)
  }

ccl_getRequestStatus(requestId)
  → Get status of submitted request

ccl_getRequestResult(requestId)
  → Get encrypted result (when ready)

ccl_estimateCost(params)
  → Estimate cost for request

10. Cryptographic Primitives

DeflationChain uses proven cryptographic primitives that ensure security, compatibility, and performance.

10.1. Signatures

10.1.1. ECDSA (secp256k1)

The Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve is DeflationChain's primary cryptographic primitive for creating digital signatures. This choice is driven by the need for full compatibility with the Ethereum ecosystem, allowing users to utilise existing wallets such as MetaMask without any modifications.

The secp256k1 curve was chosen by Satoshi Nakamoto for Bitcoin and subsequently adopted by Ethereum. Its key advantage is computational efficiency thanks to specially selected parameters. Unlike NIST curves, secp256k1 has transparent parameter origins, which eliminates the possibility of hidden vulnerabilities (backdoors).

DeflationChain uses ECDSA for three main purposes: transaction signing (each transaction must be signed with the sender's private key), message signing according to EIP-191 and EIP-712 standards (for off-chain action authorisation), and address derivation (the wallet address is calculated as the last 20 bytes of the Keccak-256 hash of the public key).

secp256k1 parameters:

Curve: y² = x³ + 7 (mod p)
p = 2²⁵⁶ - 2³² - 2⁹ - 2⁸ - 2⁷ - 2⁶ - 2⁴ - 1
n = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
G = (Generator point)

Security level: ~128 bits

Use in DeflationChain:
- Transaction signatures
- Message signing (EIP-191, EIP-712)
- Account derivation (compatible with MetaMask, etc.)

Transaction signing process:

Signing a transaction in DeflationChain follows the standard Ethereum process, which consists of four sequential steps. First, the transaction is serialised using Recursive Length Prefix (RLP) encoding, which is a deterministic way of converting structured data into a byte sequence. Next, the Keccak-256 hash of the serialised data is calculated, which serves as a unique identifier for the transaction. After that, the sender's private key is used to create an ECDSA signature of the hash, resulting in three components: r, s (coordinates of the point on the curve) and v (recovery parameter). Finally, the signature is added to the transaction, forming a signed transaction ready to be sent to the network.

1. Serialise transaction (RLP encoding):
   tx_bytes = RLP([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0])

2. Hash transaction:
   tx_hash = keccak256(tx_bytes)

3. Sign hash:
   (r, s, v) = ECDSA_sign(private_key, tx_hash)

4. Create signed transaction:
   signed_tx = RLP([nonce, gasPrice, gasLimit, to, value, data, v, r, s])

Recovery (obtaining the public key from the signature):

One of the unique features of ECDSA is the ability to recover the signer's public key from the signature itself. This feature is critical for blockchain: instead of including a 64-byte public key in every transaction, it is sufficient to store only the signature, and the public key (and therefore the sender's address) can be calculated mathematically. The parameter v in the signature (recovery id) indicates which of the two possible points on the elliptic curve to use for recovery. In Ethereum, after EIP-155, the parameter v also encodes the chainId to protect against replay attacks between different networks.

def recover_public_key(tx_hash, v, r, s):
    # v encodes recovery id (27/28 for legacy, EIP-155 adds chainId)
    recovery_id = v - 27 if v < 35 else (v - 35) % 2

    # Recover public key from signature
    R = point_from_x(r, recovery_id % 2)
    e = int(tx_hash, 16)
    public_key = (s * R - e * G) * modinv(r, n)

    return public_key

10.1.2. Ed25519 (for validators)

Ed25519 is a digital signature scheme based on the Edwards25519 curve, developed by Daniel Bernstein. In DeflationChain, Ed25519 is used optionally for internal validator operations where performance is critical and compatibility with Ethereum is not required.

The main advantage of Ed25519 is the determinism of signatures: unlike ECDSA, it does not require the generation of a random nonce for each signature. This eliminates a whole class of vulnerabilities associated with weak random number generators. In addition, Ed25519 is significantly faster than ECDSA: signature creation is approximately 10 times faster, and verification is 3 times faster.

In the context of DeflationChain, validators use Ed25519 to sign consensus messages (prevote, precommit), mutual authentication between validators, and signatures for internal administrative operations. This allows thousands of signatures to be processed per second without significant CPU load.

Ed25519 parameters:

Curve: Edwards curve -x² + y² = 1 + d*x²*y² (Curve25519)
d = -121665/121666 (mod p)
p = 2²⁵⁵ - 19
Security level: ~128 bits

Advantages:
- Deterministic signatures (no random nonce)
- Faster than ECDSA: ~10x for signing, ~3x for verification
- Resistant to side-channel attacks

Usage:
- Consensus signatures (prevote, precommit)
- Validator identity
- Inter-validator communication

Performance comparison:

Below is a comparative table of ECDSA and Ed25519 performance for typical cryptographic operations. Measurements were taken on modern server hardware (Intel Xeon, single core). Ed25519's advantage is particularly important in the Batch Verify operation, which is not available for ECDSA but is critical for validators processing hundreds of signatures in each consensus round.

ECDSA vs Ed25519 Performance Comparison
Operation ECDSA Ed25519 Improvement
Key Generation ~50 μs ~20 μs 2.5x
Sign ~200 μs ~20 μs 10x
Verify ~300 μs ~100 μs 3x
Batch Verify N/A ~50 μs/sig 6x vs single

10.1.3. BLS12-381 (aggregated signatures)

BLS (Boneh-Lynn-Shacham) is a digital signature scheme with a unique aggregation property: multiple signatures from different signatories can be mathematically combined into a single compact signature. This property is revolutionary for blockchain systems, where confirmation from multiple validators is required.

DeflationChain uses the BLS12-381 curve, which is also used in Ethereum 2.0. This curve provides 128-bit security when working with bilinear pairings — mathematical operations necessary for aggregating and verifying signatures.

The practical significance of aggregation is enormous: instead of storing 100 separate signatures (48 bytes each = 4800 bytes), it is sufficient to store one aggregated signature (48 bytes). This 99% reduction is critical for blocks containing Quorum Certificates — proof that more than 2/3 of validators have confirmed the block.

BLS12-381 parameters:

Pairing-friendly elliptic curve
Embedding degree: 12
Field size: 381 bits
Security level: ~128 bits

Groups:
- G1: 48 bytes (compressed)
- G2: 96 bytes (compressed)
- Signature: in G1 or G2 (depending on the scheme)

Advantages:
- Signature aggregation: N signatures → 1 signature
- Verification: 1 pairing instead of N verifications
- Ideal for consensus with a large number of validators

Signature aggregation:

The process of aggregating BLS signatures is elegantly simple from a mathematical point of view, but has deep cryptographic foundations. When each validator signs the same message (e.g., the hash of the proposed block), their signatures can simply be added together as points on an elliptic curve. The resulting signature is verified with a single pairing operation, which is much more efficient than verifying each signature separately.

It is important to note that aggregation is particularly effective when all signatories sign the same message — this is the typical scenario for consensus. With different messages, verification requires n pairing operations, which is less efficient.

BLS Aggregation:

1. Each validator i signs message m:
   σ_i = Sign(sk_i, m)

2. Aggregate signatures:
   σ_agg = σ_1 + σ_2 + ... + σ_n

3. Aggregate public keys (for identical messages):
   pk_agg = pk_1 + pk_2 + ... + pk_n

4. Verify aggregated signature:
   Verify(pk_agg, m, σ_agg) = e(σ_agg, g2) == e(H(m), pk_agg)

Storage savings:
- 100 validators: 100 × 48 bytes = 4800 bytes → 48 bytes
- 99% reduction in signature storage

Use in DeflationChain:

In DeflationChain, BLS signatures are used in three key areas. First, Quorum Certificates (QC) — each finalised block contains an aggregated signature of all validators who confirmed it. This allows any node to quickly verify consensus without checking hundreds of individual signatures.

Second, State Sync Proofs — light clients and new nodes can provably synchronise with the network by obtaining a compact proof of finality: one aggregated signature plus a bitfield (bit mask) indicating which validators' signatures were aggregated.

Third, Cross-shard Communication (planned) — with a potential transition to sharding, aggregated signatures will allow evidence to be efficiently transferred between shards without exponential overhead growth.

BLS Use Cases:

1. Quorum Certificates (QC):
   - Prevote signatures aggregated
   - Precommit signatures aggregated
   - Block header includes only 1 aggregated signature

2. State Sync Proofs:
   - Proof of finality for light clients
   - Compact proof: 1 signature + bitfield of signers

3. Cross-shard Communication (future):
   - Aggregated proofs between shards

10.2. Hashing

10.2.1. Keccak-256

Keccak-256 is the main hash function of DeflationChain, inherited from Ethereum for full compatibility. It is important to understand that Keccak-256 is not NIST SHA-3, although both are based on the same algorithm. Ethereum chose the original Keccak before NIST standardisation, which made minor changes to the padding.

The Keccak hash function uses a sponge construction, which is fundamentally different from the Merkle-Damgård construction used in SHA-1 and SHA-256. This makes Keccak resistant to length extension attacks, to which classic hash functions are vulnerable.

In DeflationChain, Keccak-256 is used everywhere: for deriving addresses from public keys, hashing transactions and blocks, calculating Merkle Patricia Trie roots, calculating storage slots for smart contracts, and generating function selectors (the first 4 bytes of the function signature hash).

Keccak-256 (SHA-3 finalist, but NOT NIST SHA-3):

Output: 256 bits (32 bytes)
Block size: 1088 bits
Capacity: 512 bits
Security: 128-bit collision resistance

Usage:
- Address derivation: address = keccak256(public_key)[12:32]
- Transaction hashing
- State trie node hashing
- Merkle Patricia Trie
- Storage slot calculation
- Event/function selector: bytes4(keccak256("transfer(address,uint256)"))

Examples of use:

Below are typical patterns of using Keccak-256 in DeflationChain smart contracts. Address derivation demonstrates how a 64-byte public key is converted to a 20-byte address. The calculation of the storage slot according to the EIP-1967 standard shows a technique for preventing collisions when working with proxy contracts. Function selectors allow the EVM to identify the called methods by the first 4 bytes of calldata.

// Address derivation
address = bytes20(keccak256(abi.encodePacked(publicKeyX, publicKeyY)));

// Storage slot calculation (EIP-1967)
bytes32 IMPLEMENTATION_SLOT = bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1);

// Function selector
bytes4 selector = bytes4(keccak256("transfer(address,uint256)"));
// selector = 0xa9059cbb

// Mapping storage location
bytes32 slot = keccak256(abi.encodePacked(key, mappingSlot));

10.2.2. SHA-256

SHA-256 is a classic hash function from the SHA-2 family, standardised by NIST. In DeflationChain, SHA-256 is not the main hash function (this role is performed by Keccak-256), but is used in specific contexts where compatibility with external systems is required.

The first important context is Intel TDX attestation. The TEE remote attestation process uses SHA-256 to hash reports and certificate chains. This is an Intel requirement, and DeflationChain follows it for integration with CCL (Confidential Compute Layer).

The second context is compatibility with Bitcoin for potential cross-chain operations and Bitcoin signature verification. SHA-256(SHA-256(x)) is the standard hashing pattern in the Bitcoin protocol.

The third context is HMAC-SHA256 for key derivation, where compatibility with standards such as HKDF (RFC 5869) is required.

SHA-256:

Output: 256 bits
Block size: 512 bits
Security: 128-bit collision resistance

Use in DeflationChain:
- TDX attestation quotes (Intel requirement)
- Bitcoin-compatible operations
- HMAC-SHA256 for key derivation
- Random number generation seed

10.2.3.

Blake3 Blake3 is a modern, high-performance hash function developed in 2020 by the team that created Blake2. It combines the speed of Blake2 with the advantages of parallel processing and Merkle tree mode, making it ideal for hashing large amounts of data.

In DeflationChain, Blake3 is used for internal operations that do not require compatibility with Ethereum. Its key advantage is speed: Blake3 is 3-5 times faster than Keccak-256 and SHA-256 on modern processors thanks to the efficient use of SIMD instructions (AVX-512 on servers).

A distinctive feature of Blake3 is its built-in support for incremental hashing and parallel processing. When hashing gigabyte-sized files, Blake3 automatically distributes the work between CPU cores, linearly scaling performance. This is especially valuable for nodes processing large amounts of state data.

Blake3:

Output: Variable (default 256 bits)
Security: 128-bit
Performance: 3-5x faster than SHA-256

Features:
- SIMD optimised
- Parallel hashing
- Streaming support
- Keyed hashing mode

Usage:
- Internal node hashing (not consensus-critical)
- Content-addressable storage
- File hashing
- Merkle tree construction (internal)

Performance comparison:

The performance of hash functions is critical for blockchain, as hashing is performed millions of times per second: when verifying transactions, updating the state trie, and checking Merkle proofs. The table below shows the comparative performance on a single CPU core when processing typical 64-byte input data. Blake3 leads the way thanks to its modern architecture, optimised for modern processors.

Hash Function Performance (single core, 64-byte input)
Algorithm Speed (MB/s) Relative
Blake3 1,500 1x (baseline)
Blake2b 1,000 1.5x slower
Keccak-256 500 3x slower
SHA-256 300 5x slower

10.3. Encryption

10.3.1. AES-256-GCM

AES-256-GCM (Advanced Encryption Standard in Galois/Counter Mode) is the main symmetric encryption algorithm in DeflationChain. This choice is based on three factors: broad hardware support (AES-NI instructions in modern CPUs), authenticated encryption mode (encryption + integrity verification in a single operation), and standardisation in TLS 1.3.

GCM mode is particularly important for blockchain applications because it provides AEAD (Authenticated Encryption with Associated Data). This means that in addition to encrypting confidential data, it is possible to authenticate (protect from modification) additional metadata without encrypting it — for example, the message type or sender ID.

In the context of DeflationChain, AES-256-GCM is used to encrypt payloads in TLS connections between nodes, protect data in the CCL (Confidential Compute Layer), and securely store validators' private keys.

AES-256-GCM:

Key size: 256 bits
Block size: 128 bits
Nonce size: 96 bits (recommended)
Tag size: 128 bits
Mode: Galois/Counter Mode (authenticated encryption)

Security:
- Confidentiality: AES-CTR
- Integrity: GHASH (GCM)
- AEAD: Authenticated Encryption with Associated Data

Usage:
- TLS 1.3 cipher suite
- CCL encrypted payloads
- Key wrapping
- Secure storage

Encrypted message format:

The structure of an encrypted message in DeflationChain follows cryptography best practices. A nonce (12 bytes) is generated uniquely for each message — reusing a nonce with the same key completely compromises GCM security. The nonce is followed by variable-length encrypted text, and the structure is completed by a 16-byte authentication tag that allows any data modification to be detected.

Associated Data (AAD) is data that is authenticated but not encrypted. This is useful for metadata that must be visible (for routing, logging) but protected from tampering. For example, the message type and sender ID can be in the AAD, allowing intermediate nodes to route the message without decrypting the content.

🔐 Encrypted Payload Structure
Nonce
12 bytes
Ciphertext
variable
Auth Tag
16 bytes
📋 Associated Data (not encrypted, but authenticated):
Message type Sender ID Timestamp Version
💡 Example:
plaintext = "sensitive data"
aad = "msg_type=compute,sender=0x1234"
(nonce, ciphertext, tag) = AES_GCM_encrypt(key, plaintext, aad)

10.3.2. ChaCha20-Poly1305

ChaCha20-Poly1305 is a modern AEAD cipher developed by Daniel Bernstein as an alternative to AES-GCM. Its key advantage is that it does not depend on specialised hardware instructions: ChaCha20 runs quickly on any processor, using only basic operations (XOR, addition, bit shifts).

This is important for blockchain for two reasons. First, not all nodes run on servers with AES-NI — mobile devices, older processors, and some ARM platforms may not have hardware AES. Second, ChaCha20 was originally designed with protection against timing attacks — execution time does not depend on the value of the key or data, which is critical for cryptographic operations.

In DeflationChain, ChaCha20-Poly1305 is used as a fallback for clients without AES-NI, for mobile wallets and lightweight clients, and in protocols such as WireGuard for VPN node connections.

ChaCha20-Poly1305:

Key size: 256 bits
Nonce size: 96 bits
Tag size: 128 bits

Advantages:
- Does not require AES-NI (software-friendly)
- Constant-time on all platforms
- No timing side-channels

Usage:
- Mobile clients
- Fallback for devices without AES-NI
- Wireguard-style protocols

10.3.3. ECIES (Hybrid Encryption)

ECIES (Elliptic Curve Integrated Encryption Scheme) solves a fundamental problem: how to encrypt a message for the recipient knowing only their public key? Asymmetric algorithms directly (such as RSA) are inefficient for large data, so a hybrid approach is used.

The essence of ECIES is that the sender generates a one-time (ephemeral) key pair, calculates a common secret with the recipient's public key via ECDH (Elliptic Curve Diffie-Hellman), and uses this secret for symmetric encryption (AES-GCM). The recipient uses their private key and the sender's ephemeral public key to recreate the same secret and decrypt.

In DeflationChain, ECIES is critical for CCL: the user encrypts the request to the AI model with the TEE worker's public key, ensuring that only the TEE with the corresponding private key (protected by hardware) can decrypt the data.

ECIES Process:

Encryption (for the recipient with public key P):
1. Generate ephemeral key pair: (e, E = e*G)
2. Compute shared secret: S = e * P
3. Derive encryption key: k = KDF(S)
4. Encrypt message: c = AES_GCM(k, m)
5. Output: (E, c, tag)

Decryption (with private key p):
1. Compute shared secret: S = p * E
2. Derive key: k = KDF(S)
3. Decrypt: m = AES_GCM_decrypt(k, c)

Use in DeflationChain:
- CCL request encryption (user → worker)
- Encrypted model key distribution
- Secure inter-validator communication

10.4. Key Derivation

10.4.1. HKDF (HMAC-based Key Derivation Function)

HKDF is a standardised mechanism (RFC 5869) for generating cryptographic keys from input keying material (IKM). Unlike simple hashing, HKDF provides formally proven security and domain separation support — the ability to generate multiple independent keys from a single secret.

The two-phase Extract-then-Expand architecture is particularly important for blockchain. The Extract phase takes potentially weak IKM (e.g., the result of ECDH) and creates a cryptographically strong pseudo-random key (PRK). The Expand phase allows an arbitrary number of keys to be generated from a single PRK, each for its own purpose (encryption, MAC, IV, etc.).

In DeflationChain, HKDF is used to derive session keys after the TLS handshake, generate separate keys for encryption and authentication from a single shared secret, and domain separation between different protocols.

HKDF (RFC 5869):

Extract-then-Expand paradigm:
1. Extract: PRK = HMAC(salt, IKM)
2. Expand: OKM = HMAC(PRK, info || counter)

Usage:
- Deriving session keys
- Key stretching
- Domain separation

10.4.2. BIP-32/39/44 (HD Wallets)

Hierarchical deterministic wallets (HD Wallets) are the industry standard for cryptographic key management, fully supported by DeflationChain. Three interrelated BIP (Bitcoin Improvement Proposal) standards ensure compatibility with the existing wallet ecosystem.

BIP-39 defines the conversion of a seed phrase (12-24 words from a standard 2048-word dictionary) into a cryptographic seed via PBKDF2. This allows users to memorise or securely record the seed phrase to recover all wallet keys.

BIP-32 describes hierarchical derivation: an unlimited number of child keys can be mathematically derived from a single master seed. Hardened derivation (with an apostrophe in the path) provides additional security — compromising a child key does not reveal the parent key.

BIP-44 standardises derivation paths for different cryptocurrencies: m/44'/60'/0'/0/0 for the first Ethereum address. DeflationChain uses its own coin_type for native operations, while maintaining compatibility with coin_type 60 (Ethereum) for EVM transactions.

Hierarchical Deterministic Wallet:

BIP-39: Mnemonic → Seed
- 12-24 words from a 2048-word list
- PBKDF2 with 2048 iterations

BIP-32: Seed → Master Key → Child Keys
- Extended keys: (key, chain_code)
- Hardened derivation for security

BIP-44: Derivation Paths
- m/44'/60'/0'/0/0 (first Ethereum address)
- m/44'/[CHAIN_ID]'/0'/0/x for DeflationChain

10.5. Merkle Structures

10.5.1. Merkle Patricia Trie

Merkle Patricia Trie (MPT) is a fundamental Ethereum data structure inherited by DeflationChain for storing global state. MPT combines the properties of three structures: Merkle tree (cryptographic proofs), Patricia trie (efficient key search), and radix tree (common prefix compression).

Each MPT node is hashed, and changing any value cascades changes the hashes of all parent nodes up to the root (state root). This allows anyone to verify the presence or absence of data with only a 32-byte root hash and a Merkle proof — a fixed-size proof regardless of the total amount of data.

DeflationChain uses three separate trie: State Trie (balances, nonce, contract code hashes), Storage Trie (storage data for each contract), and Transactions Trie (transactions in a block). The roots of these trie are included in the block header, providing a cryptographic link between the entire state and the blockchain.

Modified Merkle Patricia Trie:

Node Types:
1. NULL: empty node
2. Branch: 17 elements (16 nibbles + value)
3. Extension: (shared_nibbles, child)
4. Leaf: (remaining_path, value)

RLP Encoding:
- Nodes are encoded with RLP
- If RLP(node) < 32 bytes: inline
- If RLP(node) >= 32 bytes: store, reference by hash

State Trie:
- Key: keccak256(address)
- Value: RLP([nonce, balance, storageRoot, codeHash])

Storage Trie:
- Key: keccak256(slot)
- Value: RLP(value)

Transactions Trie:
- Key: RLP(index)
- Value: RLP(transaction)

10.5.2. Verkle Trees (Future)

Verkle Trees are the next generation of data structures for blockchain, planned for implementation in DeflationChain after the mainnet stabilises. The name comes from "Vector commitment" + "Merkle", reflecting the key innovation: replacing hash functions with polynomial commitments (KZG).

The main advantage of Verkle Trees is a dramatic reduction in proof size. In MPT, the proof grows logarithmically with the size of the data and can reach kilobytes. In Verkle Tree, the proof remains almost constant regardless of the depth of the tree due to the mathematical properties of KZG commitments.

For DeflationChain, this means more efficient light clients (less data to synchronise), faster state sync for new nodes, and preparation for stateless clients — nodes that do not store the full state but receive proofs for each transaction. The migration from MPT to Verkle is planned as a backward-compatible upgrade without a hard fork.

Verkle Trees (Planned Upgrade):

Advantages over MPT:
- Witness size: O(log n) → O(log n / log k) where k = branching factor
- For k=1024: ~10x smaller proof size
- Vector commitments instead of hash-based

Polynomial Commitments:
- KZG (Kate-Zaverucha-Goldberg)
- Constant-size proofs
- Batched verification

Planned integration:
- After mainnet stabilisation
- Backward compatible upgrade
- Gradual migration from MPT

11. Security

DeflationChain's security is ensured by a multi-level protection system covering all components: from cryptographic primitives to economic mechanisms. This section describes the threat model, formal verification methods, audit procedures, and the bug bounty programme.

11.1. Threat Model

11.1.1. Threat Model Definition

DeflationChain is developed under the assumption of a Byzantine adversarial model, where a certain proportion of participants may act maliciously at will. This is the most conservative security model: an attacker can violate the protocol in any way, including sending conflicting messages to different participants, arbitrary delays, and complete shutdown.

The DeflationChain threat model is based on four categories of assumptions. Cryptographic assumptions rely on the computational complexity of mathematical problems — if the discrete logarithm on elliptic curves is broken, the cryptocurrency industry as a whole will be threatened. Network assumptions use a partial synchrony model — the network may be asynchronous (messages are delayed arbitrarily), but after a certain point (GST — Global Stabilisation Time), messages are delivered within a limited time.

Economic assumptions are based on the rationality of participants: attacks must be economically disadvantageous. Byzantine tolerance requires honest validators to control more than 2/3 of the PoD weight — this is the standard threshold for BFT consensus, ensuring security in the presence of up to 1/3 malicious participants.

Basic assumptions:

Security Assumptions
Cryptographic
  • ECDLP hard
  • Keccak-256 collision-resistant
  • AES-256 semantically secure
  • BLS12-381 bilinear groups secure
Network
  • Partial synchrony model
  • Eventually reliable broadcast
  • Messages delivered within Δ after GST
Economic
  • Rational actors maximise profit
  • Cost of attack > expected profit
  • Validators have reputation at stake
Byzantine Tolerance
  • f < n/3 Byzantine validators (by PoD)
  • Honest majority controls > 2/3 PoD weight

11.1.2. 51% Attack

A 51% attack is a fundamental threat to any decentralised system: an attacker who controls the majority of resources (computing power in PoW, stake in PoS, or PoD weight in DeflationChain) can theoretically rewrite transaction history, perform double-spending, and censor transactions.

However, DeflationChain has unique defence mechanisms that make this attack virtually impossible. Firstly, accumulating 51% PoD weight requires not only purchasing tokens, but also many years of staking — existing long-term stakers already have an xMultiplier advantage of up to 20x. An attacker starting from scratch would need to either accumulate significantly more tokens or wait for years.

Second, the geopolitical distribution of validators (one per country) creates an additional barrier: coordinating an attack across dozens of jurisdictions with their own laws, regulators, and law enforcement agencies is extremely difficult. Third, the very nature of the attack is self-destructive — a successful attack will crash the price of DEF, destroying the value of the attacker's stake.

Analysis for DeflationChain:

Scenario: The attacker wants to obtain 51%+ PoD weight

Calculation of the cost of the attack:
─────────────────────────────────────────────
Assumptions:
- Total DEF staked: 5,000,000 DEF (~24% of 21M issuance)
- DEF price: $10
- Average stake duration: 4 years
- Target: 51% PoD weight

Required Stake:
- For 51% with equal stake duration: 2,550,000 DEF
- Market value: $25.5M

Additional factors:
- Slippage when purchasing such a volume: +30-50%
- Price impact from announcement of intentions: +100-500%
- Real cost of attack: $50-150M+

Time to accumulate:
- When purchasing 1% of supply/day: 12+ days
- During this time: community response, governance action
─────────────────────────────────────────────

Mechanisms of protection against a 51% attack:

51% Attack Mitigation
1. Geopolitical distribution
  • 1 validator per country
  • Coordination between countries is difficult
  • Different jurisdictions = different risks
2. Long-term staking incentives
  • 12-year stake gives 20x multiplier
  • Honest stakers have an advantage
  • New attackers start with 1x
3. Economic deterrents
  • Successful attack → DEF price crash
  • Attacker loses stake value
  • Nash equilibrium for honesty
4. Social layer defences
  • Community monitoring
  • Emergency governance proposals
  • Hard fork capability (last resort)

11.1.3. Validator collusion

Validator collusion poses a more subtle threat than a direct 51% attack. Even without majority control, a group of validators can coordinate their actions to benefit themselves or harm the network. The threshold of 1/3 PoD weight is critical: with it, finality can be blocked (though history cannot be changed), and with 2/3, the network can be completely controlled.

In the context of DeflationChain, collusion is complicated by several factors. The geographical diversity of validators means different time zones, languages, and cultural barriers to coordination. The public nature of validators' reputations creates accountability — strange behaviour will quickly attract the attention of the community. Economic incentives are aligned: long-term stakes mean long-term interest in the success of the network.

Nevertheless, DeflationChain implements systems for detecting anomalous behaviour: analysis of voting patterns for suspiciously high correlation between validators, monitoring of transactions for censorship, and whistleblower reward mechanisms to encourage the disclosure of collusion.

Types of collusion attacks:

Attack type                | Requirements           | Consequences
─────────────────────────┼─────────────────────┼────────────────────────
Censorship              | 1/3+ PoD weight      | Transaction blocking
Double spending         | 2/3+ PoD weight      | Financial losses
Liveness attack         | 1/3+ PoD weight      | Network shutdown
State corruption        | 2/3+ PoD weight      | Arbitrary changes

Detection mechanisms:

Automatic collusion detection is a non-trivial task, as it is necessary to distinguish legitimate consensus (validators voting for the correct block) from coordinated malicious actions. DeflationChain uses statistical analysis to detect anomalies.

Voting time analysis detects suspiciously synchronised actions — if validators from different parts of the world vote with a difference of less than 50 milliseconds, this may indicate coordination via a private communication channel. Selection pattern analysis tracks whether certain validators always vote the same way even when there are alternative valid options. Absence analysis detects coordinated voting omissions that could be used to attack liveness.

class CollusionDetector:
    """
    Validator collusion detection system
    """

    def detect_voting_patterns(self, votes: List[Vote]) -> Alert:
        """
        Analyses voting patterns for signs of collusion
        """
       # Suspicious signs:
        # 1. Identical voting times (< 50ms difference)
        # 2. Identical blocks with alternativeoptions
        # 3. Coordinated voting abstentions

        timing_correlation = self.analyze_timing(votes)
        choice_correlation = self.analyze_choices(votes)
        absence_correlation = self.analyze_absences(votes)

        if timing_correlation > THRESHOLD:
            return Alert.SUSPECTED_TIMING_COLLUSION
       if choice_correlation > THRESHOLD:
            return Alert.SUSPECTED_CHOICE_COLLUSION

        return Alert.NONE

    def detect_censorship(self, mempool: Mempool, blocks: List[Block]) -> Alert:
        """
        Detection of coordinated transaction censorship
        """
       for tx in mempool.pending:
            if tx.age > MAX_PENDING_TIME:
                if tx.fee >= MINIMUM_FEE:
                    # Transaction with sufficient fee isignored
                    excluding_validators = self.find_excluding_validators(tx)
                   if len(excluding_validators) > COLLUSION_THRESHOLD:
                        return Alert.SUSPECTED_CENSORSHIP

        return Alert.NONE

Protective mechanisms:

DeflationChain implements several levels of protection against collusion. Proposer-Builder Separation (PBS) is an architectural solution borrowed from Ethereum, where validators do not directly form the contents of blocks. Instead, specialised builders compete for the right to include transactions, and the validator only selects the block with the highest bid. This makes censorship difficult: a builder that excludes transactions loses out to a builder that includes them.

Mandatory Transaction Inclusion requires that transactions that have been in the mempool for longer than a certain amount of time (usually N blocks) must be included. A validator who systematically ignores such transactions is subject to slashing. This makes long-term censorship impossible even if a significant proportion of validators collude.

The Reputation System keeps on-chain statistics on the behaviour of each validator: percentage of missed blocks, voting patterns, correlations with other validators. This information is public and influences the trust of delegators. Whistleblower Rewards create an economic incentive to expose collusion from within — a participant in collusion can gain more by turning in their accomplices.

1. Proposer-Builder Separation (PBS):
   - Validators do not select block content.
   - Builders compete for the right to form blocks.
   - Reduces opportunities for coordinated censorship.

2. Mandatory Transaction Inclusion:
   - Transactions older than N blocks must be included
   - Refusal = slashing offence
   - Crlist mechanism (Ethereum-inspired)

3. Validator Reputation System:
   - On-chain tracking of validator behaviour
   - Correlation score between validator pairs
   - Public dashboard for monitoring

4. Whistleblower Rewards:
   - Reward for proving collusion
   - 10% of slashed amount → whistleblower
   - Anonymous reporting channel

11.1.4. Smart Contract Vulnerabilities

Smart contracts represent a unique attack vector: the code is public, irreversible (after deployment), and controls real assets. The history of DeFi is full of examples of vulnerabilities being exploited with multimillion-dollar losses — from The DAO (2016, $60M) to various flash loan attacks of today.

DeflationChain inherits EVM and, accordingly, the classic vulnerabilities of Solidity contracts. Reentrancy is an attack where a contract calls an external contract before updating its state, allowing recursive calls. Integer overflow/underflow is historically critical but is automatically checked in Solidity 0.8+. Access control bypass is the circumvention of authorisation checks due to logical errors.

Flash loans are particularly dangerous for DeFi-specific attacks, as they allow huge amounts to be borrowed without collateral in a single transaction. This allows for price manipulation on DEXs, exploitation of unreliable oracles, and complex attacks requiring large amounts of capital. DeflationChain mitigates these risks through TWAP oracles, transaction limits, and mandatory core contract audits.

Vulnerability classification:

Smart Contract Vulnerability Taxonomy
CRITICAL (P0)
Reentrancy attacks → CEI pattern, ReentrancyGuard, pull payments
Integer overflow/underflow → Solidity 0.8+ built-in checks
Access control bypass → OpenZeppelin AccessControl, multi-sig
Logic errors in calculations → Formal verification, fuzzing, invariant testing
HIGH (P1)
Flash loan attacks → TWAP oracles, borrowing limits
Oracle manipulation → Multiple oracles, outlier detection
Front-running vulnerabilities → Commit-reveal, batch auctions
Signature malleability → EIP-712, signature normalisation
MEDIUM (P2)
Denial of Service (DoS) → Gas limits, pull patterns
Griefing attacks → Minimum deposits, cooldown periods
Unexpected token behaviours → Token whitelisting, safeTransfer

DeflationCoin-specific risks:

DeflationCoin has unique mechanics that create specific risks not found in standard ERC-20 tokens. The BalancePortions system with progressive burning requires special attention to race conditions and timestamp manipulation.

The first risk is an attempt to send multiple transactions in a single block to bypass the burning mechanism. If a user can update their balance multiple times in a single block.timestamp, they can potentially "reset" the inactivity counter. Protection is implemented by verifying that each address can only be updated once per block.

The second risk is the manipulation of block time by the validator to gain an advantage in xMultipliers. Although validators have some freedom in setting the timestamp, DeflationChain limits the allowable deviation from the previous block, making significant manipulation impossible.

The third risk is a flash stake attack on the dividend pool: borrowing a large amount, staking, receiving dividends, unstaking, returning the loan — all in a single transaction. Protection requires a minimum staking period (30 days) before dividends can be claimed.

// Risk 1: Race condition in BalancePortion
// Attack: Multiple transactions in one block to bypass progressive burning

// Protection:
function refreshBalance(address user) internal {
    require(block.timestamp > lastRefresh[user], "Already refreshed this block");
    lastRefresh[user] = block.timestamp;
    // ... usual logic
}

// Risk 2: Manipulation of staking time
// Attack: Validator manipulates block.timestamp for profit in xMultipliers

// Defence:
modifier timestampSafe() {
    require(
        block.timestamp >= previousBlockTimestamp,
        "Timestamp regression"
    );
    require(
        block.timestamp <= previousBlockTimestamp + MAX_BLOCK_DRIFT,
        "Timestamp too far in future"
    );
    _;
}

// Risk 3: Dividend pool drainage
// Attack: Flash stake to receive dividends

// Defence:
function claimDividends(uint256 stakeId) external {
    StakePosition storage stake = stakes[msg.sender][stakeId];
    require(
        block.timestamp >= stake.startTime + MINIMUM_STAKE_FOR_DIVIDENDS,
        "Stake too young"
    );
    // MINIMUM_STAKE_FOR_DIVIDENDS = 30 days
}

11.1.5. Oracle Manipulation

Oracles are a bridge between the blockchain and the outside world, providing data on asset prices. For DeflationChain with an integrated Trading Core, the reliability of oracles is critical: incorrect prices lead to wrongful liquidations, unfair settlement perpetuals, and the possibility of arbitrage at the expense of the protocol.

A classic attack scenario: an attacker with a flash loan manipulates the price on a low-liquidity DEX used by the oracle. The oracle records the distorted price, allowing the attacker to execute a profitable transaction (open/close a position, trigger a false liquidation) before the price returns to its normal level. All this happens in a single atomic transaction.

DeflationChain counteracts this with a multi-level system: using TWAP (Time-Weighted Average Price) instead of spot price smooths out short-term manipulations by requiring the distorted price to be maintained for minutes, which is unrealistic for a flash loan attack. The multi-oracle architecture aggregates data from Chainlink, Pyth, Band, and RedStone — manipulation requires control of most sources. Outlier rejection discards values that deviate more than 2 standard deviations from the median.

Attack vectors:

Oracle Manipulation Attacks
1. Spot Price Manipulation
Attack: Flash loan → pump/dump → profit
Impact: False liquidations
Defence: TWAP 5-15 min, outlier rejection
2. Oracle Delay Exploitation
Attack: Trade ahead of delayed update
Impact: Risk-free arbitrage
Defence: Frequent updates, staleness checks
3. Oracle Node Compromise
Attack: Compromise majority of nodes
Impact: Arbitrary price reports
Defence: Multi-oracle, stake requirements
4. Source Manipulation
Attack: Manipulate low-liquidity sources
Impact: Feed false data to oracles
Defence: Liquidity-weighted, cross-validation

DeflationChain Oracle Architecture:

The architecture of DeflationChain oracles is based on the principle of defence in depth — multiple levels of protection, each of which reduces the risk of a successful attack. The first level consists of Primary Oracles — verified data providers (Chainlink, Pyth, Band, RedStone), each with its own infrastructure and price collection methodology.

The Oracle Aggregator Contract — the second level — collects data from all providers and applies statistical processing: it calculates the median (resistant to outliers), discards values that deviate by more than 2σ, and checks the relevance of the data (staleness check — maximum 60 seconds). The emergency circuit breaker automatically suspends operations when anomalies are detected.

TWAP Engine — the third level — smooths out the remaining fluctuations through time-weighted averaging. Mark Price (used to calculate PnL and liquidations) is averaged over 5 minutes, which makes flash loan manipulations ineffective. Index Price (reference price from CEX) is averaged over 1 minute. The difference between them (premium) is used for the funding rate.

DeflationChain Oracle System
Primary Oracles
Chainlink
(ETH)
Pyth
(Solana)
Band
(Cosmos)
RedStone
(L2)
Oracle Aggregator Contract
• Median price calculation
• Outlier rejection (> 2σ)
• Staleness check (60s max)
• Confidence interval
• Emergency circuit breaker
TWAP Engine
Mark Price = TWAP(Aggregated Price, 5 minutes)
Index Price = TWAP(CEX prices, 1 minute)
Premium = Mark Price - Index Price

11.1.6. MEV Extraction

MEV (Maximal Extractable Value) is the profit that validators and specialised bots can extract by reordering, inserting, or censoring transactions. MEV is discussed in detail in section 5.4; here, we provide a systematic analysis of threats at the network level.

MEV creates a negative externality: users pay a "hidden tax" in the form of degraded transaction execution. Front-running makes limit orders predictable for attackers. Sandwich attacks extract value from AMM swaps. Time-bandit attacks threaten finality: if MEV from reorganisation exceeds the reward for honest behaviour, a rational validator may attempt to rewrite history.

DeflationChain takes a comprehensive approach to MEV. At the protocol level: commit-reveal schemes for critical operations, batch auctions instead of FIFO execution, MEV-aware transaction ordering through Flashbots-like mechanisms. At the Trading Core level: priority execution of liquidations via DLP (protection against MEV hunters), partial execution instead of order rejection. At the monitoring level: real-time tracking of MEV activity to adapt protective measures.

Extended MEV Threat Analysis:

MEV type Impact on users Impact on protocol Mitigation Status
Front running Worst execution of trades Decreased trust ✅ Commit-reveal
Sandwich attacks Hidden costs Reputational risks ✅ Bundled auctions
Time-bandit attacks Reorganisation risk Finality issues ✅ Fast finalisation
MEV liquidations Unfair pricing LP losses ✅ DLP priority
JIT liquidity Unfair competition Market distortion ⚠️ Partially
Block stuffing Transaction delays Deterioration of UX ✅ Gas limits

Cross-domain MEV (Future Risk):

Scenario: cross-network arbitrage using bridge delays

Attack vector:

  1. Monitoring a large DEF transaction on the Ethereum network

  2. Front-running on the DeflationChain network via a faster bridge

  3. Profiting from price discrepancies

Protective measures:

11.2. Formal verification

Formal verification is the application of mathematical methods to prove the correctness of software. Unlike testing (which can detect bugs but cannot prove their absence), formal verification guarantees that certain properties hold for all possible inputs and states.

Formal verification is particularly important for blockchain: the code is public (attackers can see all the details), irreversible (errors cannot be "rolled back"), and controls real assets. The cost of an exploit can be measured in billions of dollars, which justifies significant investment in verification.

DeflationChain applies formal verification at three levels: consensus protocol (TLA+ for distributed systems modelling), smart contracts (Certora, Dafny for invariants and pre/post-conditions), and cryptographic primitives (verified implementations from trusted libraries).

11.2.1. Consensus protocol

For the consensus protocol, safety properties (must always be satisfied) and liveness properties (must eventually be satisfied) are formally verified. Safety guarantees that nothing bad will happen: all honest nodes make the same decisions, and the accepted values were proposed by someone. Liveness guarantees progress: the system will not get stuck, decisions will eventually be made.

PoD-specific properties include the correctness of weight calculation (the formula weight = stake × years is observed), deflationary invariant (total supply decreases monotonically), and fairness (the probability of being a leader is proportional to the PoD weight).

Properties for verification:

📐 Consensus Protocol Formal Properties
🛡️ SAFETY MUST hold always
1 Agreement
∀ honest nodes i, j: decide(i, r) = v ∧ decide(j, r) = v' → v = v'
"All honest nodes make the same decision"
2 Validity
decide(i, r) = v → v was proposed by some node
"The accepted value was proposed by someone"
3 Integrity
∀ honest node i: |{r : decide(i, r) ≠ ⊥}| ≤ 1
"Each node makes a decision no more than once"
⏱️ LIVENESS MUST hold eventually
4 Termination
∀ honest node i, ∃ r: decide(i, r) ≠ ⊥
"All honest nodes eventually make a decision"
5 Fairness
P(leader(r) = v) ∝ pod_weight(v)
"The probability of leadership is proportional to the PoD weight"
🔥 PoD-SPECIFIC Deflation Protocol Properties
6 Weight Consistency
pod_weight(v, t) = Σ(stake × year × β⁻¹)
"PoD weight is calculated correctly"
7 Deflationary Invariant
total_supply(t+1) ≤ total_supply(t)
"Total supply decreases monotonically"

Verification tools:

Tool Purpose Components to be verified
TLA+ Modelling of distributed systems Consensus rounds, leader selection
Coq Proof of theorems Cryptographic properties
Dafny Program verification Smart contract logic
Certora Specialised verification DeFi Financial invariants
Echidna Property-based fuzzing Boundary cases, invariants

11.2.2. Core Smart Contracts

DeflationChain smart contracts undergo formal verification using specialised tools for DeFi. The key concept is invariants: properties that must be satisfied in any state of the contract, after any sequence of transactions.

For DeflationCoin, critical invariants include: conservation of value (totalSupply is always equal to the sum of all balances and stakes — tokens do not appear out of nowhere), deflation (totalSupply can only decrease, never increase), parameter constraints (staking years are always in the range of 1-12, burnRate is always within acceptable limits).

Verification is performed using Certora Prover — an industrial tool for formal verification of Solidity. Specifications are written in CVL (Certora Verification Language), a declarative language for describing rules and invariants. Each contract change undergoes automatic verification: if the new code violates any invariant, the deployment is blocked.

Verifiable contracts:

// Invariants for DeflationCoinUpgradeable

/// @notice Verified Invariants:
/// INV-1: totalSupply == Σ(balances[addr]) + Σ(stakes[addr].amount)
/// INV-2: dividendPool + technicalPool + marketingPool ≤ totalFees
/// INV-3: ∀ stake: stake.year ∈ [1, 12]
/// INV-4: ∀ portion: portion.timestamp ≤ block.timestamp
/// INV-5: refreshedBalance(addr) ≤ rawBalance(addr)

contract DeflationCoinVerified {

    /// @custom:invariant totalSupply equals sum of all balances and stakes
    function invariant_supplyConsistency() public view returns (bool) {
        uint256 computed = 0;
        // Note: In reality, this is verified off-chain or through Merkle proofs.
        for (address a in allAddresses) {
            computed += balanceOf(a);
            for (uint i = 0; i < stakeCount(a); i++) {
                computed += stakes[a][i].amount;
            }
        }
        return computed == totalSupply;
    }

    /// @custom:invariant staking years are bounded
    function invariant_stakingBounds() public view returns (bool) {
        for (address a in allAddresses) {
            for (uint i = 0; i < stakeCount(a); i++) {
                if (stakes[a][i].year < 1 || stakes[a][i].year > 12) {
                    return false;
                }
            }
        }
        return true;
    }
}

Certora specifications:

// DeflationCoin.spec

methods {
    balanceOf(address) returns uint256 envfree
    totalSupply() returns uint256 envfree
    transfer(address, uint256) returns bool
    stake(uint256, uint8) returns uint256
}

// Rule: Transfer preserves total supply (minus burns)
rule transferPreservesTotalSupply(address from, address to, uint256 amount) {
    uint256 supplyBefore = totalSupply();
    uint256 fromBalanceBefore = balanceOf(from);
    uint256 toBalanceBefore = balanceOf(to);

    transfer(to, amount);

    uint256 supplyAfter = totalSupply();
    uint256 burned = supplyBefore - supplyAfter;

    // Supply can only decrease (deflationary)
    assert supplyAfter <= supplyBefore;

    // Conservation (accounting for burns and fees)
    assert fromBalanceBefore + toBalanceBefore - burned >=
           balanceOf(from) + balanceOf(to);
}

// Rule: Staking doesn't create tokens
rule stakingNoInflation(uint256 amount, uint8 year) {
    uint256 supplyBefore = totalSupply();

    stake(amount, year);

    uint256 supplyAfter = totalSupply();

    assert supplyAfter <= supplyBefore;
}

// Invariant: Daily reductions are monotonically decreasing
// Invariant: burnRate increases monotonically (more is burned every day)
invariant burnRateIncreasing()
    forall uint8 i. i < 8 => burnRate(i) < burnRate(i + 1);

11.2.3. Cryptographic Primitives

Cryptographic primitives are the foundation of any blockchain system's security. An error in the implementation of ECDSA or AES could potentially compromise the entire network. That's why DeflationChain uses only verified, battle-tested implementations from recognised projects.

For ECDSA (secp256k1), libsecp256k1 is used — a library developed by Bitcoin Core that has undergone many years of production use with hundreds of billions of dollars at stake. For BLS12-381, blst from Protocol Labs is used — a high-performance implementation with formal verification of correctness through proof assistants.

An important principle: DeflationChain does not implement cryptography from scratch. Each cryptographic primitive is imported from a proven library. This eliminates a whole class of vulnerabilities associated with the incorrect implementation of complex algorithms. All libraries used undergo regular audits and are actively maintained.

Formal verification of cryptography:

🔐 Cryptographic Primitive Verification
ECDSA (secp256k1)
Implementation: libsecp256k1
Security proof: Based on ECDLP hardness
Known attacks: None practical (2¹²⁸ security)
Usage: TX signatures, address derivation
BLS12-381
Implementation: blst library
Security proof: RFC draft + academic papers
Properties verified:
• Signature aggregation correctness
• Rogue key attack prevention
• Subgroup checks
Keccak-256
Implementation: Reference (NIST)
Security proof: SHA-3 competition analysis
Properties: Collision resistance, preimage resistance
AES-256-GCM
Implementation: OpenSSL / libsodium
Security proof: IND-CCA2 under AES-as-PRP
Properties: Authenticated encryption, nonce misuse detection

11.3. Audits

Auditing is a critical component of security, an independent expert assessment of code by professional security researchers. DeflationChain uses a multiple audit strategy: different auditors specialise in different aspects (consensus, DeFi, infrastructure), and the overlap of their areas of expertise maximises coverage.

11.3.1. Pre-launch audits

Before the mainnet launch, all critical components are audited by leading security firms in the industry. Auditors are selected based on their track record, specialisation, and reputation. Each audit includes manual code review, automatic static analysis, and fuzzing testing.

Trail of Bits — known for their in-depth technical analysis and work with major blockchain projects. OpenZeppelin — creators of standard libraries for Solidity, experts in smart contract security. Consensys Diligence — specialising in DeFi protocols. Certora — leaders in formal verification. NCC Group — expertise in system programming and infrastructure.

The total budget for pre-launch audits is $2,000,000. This is an investment in reputation and security: the cost of a successful exploit will exceed this amount many times over.

Planned audits:

Pre-Launch Audit Schedule
Phase 1: Core Protocol Q3 2026
Auditor: Trail of Bits
Scope: Consensus, P2P, Block production
Duration: 8 weeks | Budget: £500,000
Phase 2: Smart Contracts Q4 2026
OpenZeppelin
DeflationCoin, Staking, Governance
6 weeks
£350,000
Consensys Diligence
Trading Core, Vault System
6 weeks
$400,000
Certora
Critical invariants, economic properties
4 weeks
$200,000
Phase 3: Infrastructure Q1 2027
Auditor: NCC Group
Scope: Node software, RPC, Bridge
Duration: 4 weeks | Budget: £250,000
Phase 4: CCL / AI Components Q2 2027
Auditor: Cure53 + Intel (TDX-specific)
Scope: TEE integration, attestation, key management
Duration: 6 weeks | Budget: £250,000
Total Pre-launch Audit Budget: £1,500,000

11.3.2. Ongoin Audits

Security is not a one-time event, but a continuous process. After the launch of the mainnet, DeflationChain continues to invest in security through the Continuous Security Programme with an annual budget of $500,000.

Automated monitoring runs continuously: Slither and Mythril perform static analysis on every commit, Echidna and Foundry fuzz run property-based tests to find edge cases, and Certora checks invariants on any contract changes. This is the first line of defence, catching obvious errors before deployment.

Periodic reviews provide expert control: quarterly external security reviews to evaluate new features, monthly internal code reviews to maintain quality, weekly vulnerability scans using up-to-date CVE databases.

Upgrade Audits — any change to core contracts requires a mandatory audit before deployment. For critical hotfixes, there is a fast-track procedure with a 48-hour emergency review, but even that does not allow unverified code into production.

Continuous Security Programme:

Continuous Security Programme
Automated Monitoring
Static Analysis (daily)
Slither, Mythril, Securify2
Fuzzing (continuous)
Echidna, Foundry fuzz
Invariant Testing (per-commit)
Certora, Halmos
Periodic Reviews
Quarterly External security review
Monthly Internal code review
Weekly Vulnerability scanning
Upgrade audits
Core contract changes → mandatory audit
Critical fixes → 48-hour fast-track
Governance-approved auditor pool
Annual Budget: £500,000

11.4. Bug Bounty Programme

Bug Bounty — security crowdsourcing: a community of security researchers searches for vulnerabilities in exchange for a reward. This is a cost-effective mechanism: the protocol only pays for bugs that are actually found, and the global pool of researchers far exceeds the capabilities of any auditing firm.

DeflationChain implements Bug Bounty through Immunefi — a leading platform for blockchain bug bounties with a proven track record. Immunefi provides the infrastructure (secure submission, triage, payment) as well as access to a community of experienced white hats.

11.4.1. Programme Structure

The DeflationChain Bug Bounty reward structure is calibrated based on the actual damage caused by exploiting the vulnerability. CRITICAL vulnerabilities (direct theft of funds, infinite mint, network shutdown) are rewarded with up to $1,000,000 — this is expensive, but the potential damage is measured in hundreds of millions. HIGH vulnerabilities (requiring user action, temporary issues) — up to $100,000. MEDIUM (griefing, information disclosure) — up to $10,000. LOW (minor leaks, best practice violations) — up to $1,000.

The total reserve of £5,000,000 provides funding for the programme for years to come. The scope includes all on-chain code, node software, bridges, CCL — virtually anything that could affect the security of user funds.

DeflationChain Bug Bounty Programme
Severity Levels & Rewards
CRITICAL
Direct theft of funds • Consensus breakdown • Permanent DoS • Infinite minting
£1,000,000
HIGH
Theft requiring user action • Temporary halt • Incorrect liquidation • Oracle manipulation
$100,000
MEDIUM
Griefing attacks • Information disclosure • High-cost DoS • Governance manipulation
$10,000
LOW
Minor information leaks • Best practice violations • UI/UX security issues
$1,000
Scope
In-Scope:
• DeflationChain node software
• All deployed smart contracts
• Bridge contracts and relayers
• CCL infrastructure
• Official frontends and APIs
Out-of-Scope:
• Third-party integrations
• Social engineering
• Physical attacks
Rules
• Responsible disclosure required
• 90-day disclosure embargo
• No exploitation of live mainnet
• First reporter wins (for duplicates)
Platform: Immunefi
Total Reserve: $5,000,000

11.4.2. Disclosure Process

Responsible Disclosure is an ethical standard for handling discovered vulnerabilities. The researcher privately informs the team, the team fixes the bug, and only after the fix is published is information about the vulnerability disclosed. This protects users from exploitation in the window between discovery and fix.

DeflationChain follows the industry standard 90-day embargo: after receiving a report, the team has up to 90 days to fix the issue before public disclosure. For CRITICAL vulnerabilities, an emergency response is activated with the deployment of a fix within 1-3 days. After each incident, a post-mortem is published with technical details and lessons learned.

Researchers receive not only monetary rewards, but also public recognition (if they wish): their name/handle is listed in the security advisory, which is important for building a reputation in the security community.

Responsible Disclosure Timeline
Day 0
Researcher submits report via Immunefi
Day 1-2
Triage team acknowledges receipt
Day 3-7
Technical assessment and severity classification
Day 7-14
Fix development and internal testing
Day 14-21
Fix deployed to testnet
Day 21
Fix deployed to mainnet (if critical)
Day 30
Embargo period
Day 90
Public disclosure (with researcher credit)
Fast-Track for Critical
Day 0
Report received
Day 0-1
Emergency response team activated
Day 1-3
Fix developed and deployed
Day 3
Post-mortem published

11.4.3. Historical Incidents

Transparency is a key principle of DeflationChain security. All security incidents, regardless of severity, will be published in a structured format. This serves several purposes: it allows the community to assess the actual security status of the protocol, helps other projects learn from others' mistakes, and creates accountability — the team cannot "sweep incidents under the rug."

Each incident log includes a unique ID, date of discovery, severity, current status, technical description of the vulnerability, root cause analysis (why the bug appeared), resolution (how it was fixed), amount of bounty paid, and credit to the researcher. The public incident log is available on the project website and is updated in real time.

At the time of writing (pre-mainnet), no incidents have been recorded. After launch, this section will be updated as security issues arise and are resolved.

Incident Log Format
Incident ID: DEF-YYYY-NNN
Date Discovered: YYYY-MM-DD
Severity:
CRITICAL HIGH MEDIUM LOW
Status:
RESOLVED MITIGATED ACKNOWLEDGED
Description: [Brief description]
Root cause: [Technical explanation]
Resolution: [Fix applied]
Bounty Paid: $X,XXX
Researcher: [Handle or Anonymous]
Pre-mainnet: No incidents to report

12. Migration from BSC

DeflationCoin currently operates on Binance Smart Chain (BSC). Migration to its own DeflationChain network requires careful planning to preserve user positions and ensure smooth operation.

12.1. Bridge Mechanism

12.1.1. Bridge Architecture

The bridge between BSC and DeflationChain is built on the proven Lock-and-Mint architecture used by most cross-chain bridges. The principle is simple: when transferring to DeflationChain, tokens on BSC are locked in a storage contract, and an equivalent amount of native DEF is minted on DeflationChain. When transferring back, DEF is burned on DeflationChain, and the locked tokens are unlocked on BSC.

The security of the bridge is ensured by a network of relays — independent operators who monitor events on both chains and sign attestations. Threshold signatures are required to perform the operation (3 out of 5 relayers must confirm). Each relayer is required to stake 10,000 DEF, which can be confiscated (slashed) if fraud is detected.

Relayers are geographically distributed (USA, EU, Asia, LATAM, Africa) to ensure resilience to regional failures and regulatory actions. The rotation and addition of new relayers is controlled by governance, ensuring the long-term decentralisation of the bridge.

Lock-and-Mint Bridge:

BSC ↔ DeflationChain Bridge
BSC (Source Chain)
DeflationCoin
(BEP-20)
Bridge Lock Contract
• Locks tokens
• Emits LockEvent
• Stores Merkle
Relayers
DeflationChain (Target)
Native DEF
(Genesis Token)
Bridge Mint Contract
• Mints native DEF
• Verifies proofs
• Enforces limits
Relayer Network
R1
USA
R2
EU
R3
Asia
R4
LATAM
R5
Africa
Threshold: 3/5 signatures
Stake: 10,000 DEF
Slashing: 50% for fraud

12.1.2. Bridge Flow

The process of transferring tokens between chains is optimised to balance speed and security. Deposit (BSC → DeflationChain) takes 1-2 minutes and involves minimal risk, as the tokens on BSC were already in circulation. Withdrawal (DeflationChain → BSC) takes 1-1.5 hours due to the challenge period — a temporary window for fraud proofs.

The bridge commission is 0.1% of the transfer amount and is distributed equally: 0.05% is burned (in accordance with the DEF deflationary model), 0.05% goes to relays as a reward for their work. The minimum transfer is 10 DEF (to prevent spam), the maximum is 100,000 DEF per transaction (risk management).

It is important to understand the asymmetry: deposits are relatively safe (worst case scenario — tokens are stuck on BSC but not lost), withdrawals require more caution (a malicious relay may attempt to unlock tokens without actually burning them on DC). Therefore, withdrawals have a challenge period.

BSC → DeflationChain (Deposit):

BSC → DeflationChain (Deposit)
1 User approves DEF (BSC) to Bridge Lock Contract
2 User calls deposit(amount, destinationAddress)
3 Contract locks tokens, emits DepositEvent
4 Relayers observe event, sign attestation
5 Aggregator collects 3/5 signatures
6 User/Relayer calls mint() on DeflationChain
7 Bridge Mint verifies signatures, mints native DEF
Timing
BSC confirmation: ~15s
Relayer attestation: ~30s
DeflationChain mint: ~2s
Total: ~1-2 minutes
Fees
Bridge fee: 0.1%
(0.05% burn, 0.05% relayers)
Min: 10 DEF | Max: 100K DEF

12.1.3. Multi-sig Security

Multi-signature security is the cornerstone of bridge security. Instead of trusting a single operator, each transaction requires the consent of a threshold number of independent signatories. In the current configuration, this is 3 out of 5 — a compromise between security (an attacker needs to compromise 3 keys) and liveness (the bridge works even if 2 relayers are offline).

The BridgeLockVault contract on BSC is a critical security point that stores all locked DEF. The contract implements standard protections: replay protection via a nonce counter, signature uniqueness verification (one relay = one vote), and rate limiting via daily limits. These measures limit damage even in the event of partial compromise.

It is noteworthy that the contract does not store private keys — only the addresses of authorised signatories. The keys are stored by the relays in HSMs (Hardware Security Modules) or cold wallets, physically distributed across different locations.

contract BridgeLockVault {
    // Multi-sig configuration
    address[] public signers;           // Relayer addresses
    uint256 public threshold;           // Required signatures (3/5)
    uint256 public nonceCounter;        // Replay protection

    // Deposit tracking
    mapping(bytes32 => DepositInfo) public deposits;
    mapping(bytes32 => bool) public processedWithdrawals;

    struct DepositInfo {
        address user;
        uint256 amount;
        uint256 timestamp;
        bool processed;
    }

    /// @notice Lock DEF for bridging to DeflationChain
    function deposit(uint256 amount, address dcDestination) external {
        require(amount >= MIN_DEPOSIT, "Below minimum");
        require(amount <= MAX_DEPOSIT, "Above maximum");
        require(dailyVolume + amount <= DAILY_LIMIT, "Daily limit exceeded");

        bytes32 depositId = keccak256(abi.encodePacked(
            msg.sender,
            amount,
            dcDestination,
            block.timestamp,
            nonceCounter++
        ));

        defToken.transferFrom(msg.sender, address(this), amount);

        deposits[depositId] = DepositInfo({
            user: msg.sender,
            amount: amount,
            timestamp: block.timestamp,
            processed: false
        });

        dailyVolume += amount;

        emit Deposit(depositId, msg.sender, amount, dcDestination);
    }

    /// @notice Process withdrawal from DeflationChain
    function withdraw(
        bytes32 withdrawalId,
        address recipient,
        uint256 amount,
        bytes[] calldata signatures
    ) external {
require(!processedWithdrawals[withdrawalId], "Already processed");
require(signatures.length >= threshold, "Insufficient signatures");

        bytes32 message = keccak256(abi.encodePacked(
            withdrawalId,
            recipient,
            amount,
            block.chainid
        ));

        uint256 validSignatures = 0;
        address[] memory usedSigners = new address[](signatures.length);

        for (uint i = 0; i < signatures.length; i++) {
            address signer = recoverSigner(message, signatures[i]);
            require(isValidSigner(signer), "Invalid signer");
            require(!contains(usedSigners, signer), "Duplicate signer");
            usedSigners[validSignatures++] = signer;
        }

        require(validSignatures >= threshold, "Threshold not met");

        processedWithdrawals[withdrawalId] = true;
        defToken.transfer(recipient, amount);

        emit Withdrawal(withdrawalId, recipient, amount);
    }
}

12.1.4. Fraud Proof System

The Fraud Proof System is the bridge's last line of defence. Even if the threshold of relays is compromised and a malicious withdrawal is initiated, honest network participants have the opportunity to challenge the transaction during the challenge period (1 hour).

The concept of optimistic verification: the bridge assumes that all transactions are honest and executes them after a short delay. But if anyone provides cryptographic proof of fraud, the transaction is cancelled and the attackers are punished. This is more efficient than pessimistic verification (checking every transaction on-chain), but requires active monitoring.

Fraud proof structurally consists of a DeflationChain block header, Merkle proof of transaction inclusion/exclusion, state proof (if necessary), and signatures of 2/3+ validators confirming the header. Anyone can become a challenger by staking a bond (1000 DEF). If the fraud proof is successful, the challenger receives 10% of the disputed amount plus a refund of the bond. If the fraud proof is false, the bond is confiscated.

Fraud Proof System
1. Optimistic Verification
• Withdrawals: 1-hour challenge period
• Anyone can submit a fraud proof
• If valid → withdrawal is cancelled
2. Fraud Proof Types
Type A: Non-existent withdrawal
Type B: Invalid amount
Type C: Reverted transaction
3. Proof Structure
• Block header (DC)
• Merkle proof (inclusion/exclusion)
• State proof (if necessary)
• Validator signatures (2/3+)
4. Incentives
Success reward: 10% of amount
Malicious relayer: slashed 50%
False proof: lose bond (1000 DEF)

12.2. Transferring Staking Positions

Migrating staking positions is a critical operation that requires special attention. Unlike simple balances, stakes contain time parameters (startTime, year, lastClaimed) that determine xMultiplier and dividend rights. Loss or distortion of these parameters can lead to unfair redistribution of rewards among stakers.

12.2.1. Snapshot mechanism

A snapshot is an atomic snapshot of the state of all stakes at a certain BSC block height. The process is divided into five phases, starting 60 days before the migration date (T=0).

The pre-registration phase allows users to link their BSC address to the new DeflationChain address in advance. This is not mandatory, but it is recommended: users without pre-registration will be able to claim later, but the process will take longer and require proof of ownership of the BSC address.

At the moment of the snapshot (T=0), the exact state is recorded: all StakePositions with their parameters, the Merkle root of the state is calculated and published. After that, the BSC contract goes into read-only mode — no new operations, only viewing.

The DeflationChain Genesis block includes all migrated positions with saved parameters. The claim period (90 days) gives time to those who did not pre-register. After 90 days, unclaimed tokens are transferred to the treasury by governance decision.

The stake migration process:

Staking Position Migration
Phase 1: Announcement T-30 days
Publication of snapshot date • Instructions for users • Start of pre-registration
Phase 2: Pre-registration T-30 to T-7
BSC ↔ DC address connection • Signing with BSC key • On-chain proof verification
Phase 3: Snapshot T=0
BSC block height is fixed • StakePositions are recorded • Merkle root is published • BSC → read-only
Phase 4: Genesis Creation T+1 day
Genesis includes: migrated balances, StakePositions with parameters, Bridge lock balance
Phase 5: Claim Period T+1 to T+90
Claim for unregistered • Proof of ownership • After 90 days: unclaimed → treasury

12.2.2. Parameter preservation

The key principle of migration is the complete preservation of all stake parameters. This means that a user who staked tokens on BSC 1.5 years ago for a 4-year term will continue staking on DeflationChain with the same startTime, and will have 2.5 years left until completion. xMultiplier will correspond to the elapsed time without resetting to the initial value.

The MigratedStake structure contains all the original parameters plus migration metadata: the hash of the original BSC transaction creating the stake, the BSC block number (for auditing), and the DC block number of the migration. This information allows independent verification of the correctness of the migration.

It is critically important to preserve lastClaimed — the month of the last dividend claim in YYYYMM format. If a user has claimed dividends for December 2024 on BSC, they will not be able to reclaim the same dividends on DeflationChain. claimedStaking and claimedDividends track accumulated payments for the correct calculation of future rewards.

// Structure for migration
struct MigratedStake {
    // Original parameters (copied 1:1)
    uint256 initialAmount;
    uint256 amount;
    uint256 finishedAmount;
    uint256 startTime;        // Original timestamp is preserved
    uint8 year;
    uint256 lastClaimed;      // YYYYMM format
    uint256 claimedStaking;
    uint256 claimedDividends;

    // Migration metadata
    bytes32 bscTxHash;        // Original stake tx on BSC
    uint256 bscBlockNumber;   // Creation block on BSC
    uint256 migrationBlock;   // Migration block on DC
}

contract StakeMigration {
    bytes32 public merkleRoot;  // Root of all BSC stakes
    mapping(address => bool) public claimed;

    /// @notice Claim migrated stake
    function claimMigratedStake(
        address bscAddress,
        MigratedStake[] calldata stakes,
        bytes calldata ownershipProof,
        bytes32[] calldata merkleProof
    ) external {
        // 1. Verify ownership of BSC address
        require(
            verifyOwnership(bscAddress, msg.sender, ownershipProof),
            "Not owner of BSC address"
        );

        // 2. Verify Merkle proof
        bytes32 leaf = keccak256(abi.encode(bscAddress, stakes));
        require(
            MerkleProof.verify(merkleProof, merkleRoot, leaf),
            "Invalid Merkle proof"
        );

        // 3. Mark as claimed
        require(!claimed[bscAddress], "Already claimed");
        claimed[bscAddress] = true;

        // 4. Create stakes on DeflationChain
        for (uint i = 0; i < stakes.length; i++) {
            _createMigratedStake(msg.sender, stakes[i]);
        }

        emit StakesMigrated(bscAddress, msg.sender, stakes.length);
    }

    function _createMigratedStake(address user, MigratedStake memory stake) internal {
        // The stake is created with the original startTime
        // This means that the remaining time is preserved
        // For example: a 4-year stake, 1 year has passed → 3 years remain

        staking.createMigratedPosition(
            user,
            stake.amount,
            stake.year,
            stake.startTime,  // Original timestamp preserved!
            stake.lastClaimed
        );
    }
}

Migration example:

User: 0x1234... (BSC)
StakePosition on BSC:
- initialAmount: 10,000 DEF
- amount: 10,000 DEF
- startTime: 2023-06-15 (block 29000000)
- year: 4
- lastClaimed: 202312

Migration at: 2025-01-15

DeflationChain StakePosition:
- initialAmount: 10,000 DEF ✓ (preserved)
- amount: 10,000 DEF ✓ (preserved)
- startTime: 2023-06-15 ✓ (preserved - NOT reset!)
- year: 4 ✓ (preserved)
- lastClaimed: 202312 ✓ (preserved)

Remaining time: 4 years - 1.5 years elapsed = 2.5 years
User receives same xMultiplier benefits they earned on BSC

12.3. Parallel operation period

Migration does not happen instantly — a transition period is required when both networks operate in parallel. This ensures a smooth transition for users and allows issues to be detected and corrected before BSC is completely shut down.

12.3.1. Transition Timeline

The timeline is calculated for 180 days with a gradual tightening of restrictions on BSC. The first 60 days are for preparation and announcement, active communication with the community. The next 30 days are for active migration after the snapshot. Then, the BSC network will transition to modes with increasingly greater restrictions: READ_ONLY (no transfers or staking, only view), CLAIM_ONLY (only unstake finished positions and claim), EMERGENCY (emergency withdrawal with penalty), and finally DEPRECATED (contract frozen).

This gradation allows users to adapt gradually. Early adopters receive bonuses for migrating in the first week. Latecomers lose opportunities (transfers, new stakes) but retain the right to their funds. Only after 180 days will a governance decision be made on the fate of the remaining unclaimed funds.

Parallel Operation Period
Timeline
Announce
T-60 → T-30
Pre-reg
T-30 → T=0
Snapshot
T=0
Migration
T → T+90
Sunset
T+90 → T+180
BSC Contract States
ACTIVE (T-60 to T=0)
All functions are operational
Transfers, staking, trading
READ-ONLY (T=0 to T+30)
Transfers/Staking disabled
View + claims possible
CLAIM-ONLY (T+30 to T+90)
Unstake finished positions
Claim dividends, Bridge to DC
EMERGENCY (T+90 to T+180)
Emergency withdrawal (penalty)
Support for edge cases
DEPRECATED (T+180+)
Contract frozen • Remaining funds → governance decision

12.3.2. BSC Read-Only Mode

Technically, Read-Only Mode is implemented through a state machine in a smart contract. Enum ContractState defines possible states, modifiers check the current state before executing functions. Transitions between states are controlled by the admin (ultimately — multisig governance).

In the ACTIVE state, all functions work normally. In READ_ONLY, transfer and stake are blocked — users can only view balances and claim accumulated rewards. CLAIM_ONLY further restricts staking operations, leaving only the ability to withdraw finished stakes. EMERGENCY allows emergency unstake with a penalty (for users who have missed all deadlines). DEPRECATED completely freezes the contract.

Important detail: modifiers check the state but do not change it. This prevents reentrancy-like attacks, where an attacker could attempt to change the state while a function is executing. State transitions are only performed through dedicated admin functions with appropriate access controls.

contract DeflationCoinBSC {
    enum ContractState { ACTIVE, READ_ONLY, CLAIM_ONLY, EMERGENCY, DEPRECATED }

    ContractState public currentState;
    uint256 public stateChangeBlock;

    modifier whenActive() {
        require(currentState == ContractState.ACTIVE, "Not active");
        _;
    }

    modifier whenClaimable() {
        require(
            currentState == ContractState.ACTIVE ||
            currentState == ContractState.READ_ONLY ||
            currentState == ContractState.CLAIM_ONLY,
            "Claims disabled"
        );
        _;
    }

    /// @notice Admin transitions to READ_ONLY after snapshot
    function transitionToReadOnly() external onlyAdmin {
        require(currentState == ContractState.ACTIVE, "Invalid transition");
        currentState = ContractState.READ_ONLY;
        stateChangeBlock = block.number;
        emit StateTransition(ContractState.READ_ONLY, block.number);
    }

    /// @notice Transfer disabled in non-active state
    function transfer(address to, uint256 amount) external whenActive returns (bool) {
        return _transfer(msg.sender, to, amount);
    }

    /// @notice Staking disabled in non-active state
    function stake(uint256 amount, uint8 years) external whenActive {
        _stake(msg.sender, amount, years);
    }

    /// @notice Claims work until EMERGENCY state
    function claimDividends(uint256 stakeId) external whenClaimable {
        _claimDividends(msg.sender, stakeId);
    }

    /// @notice Unstaking finished positions always works
    function unstakeFinished(uint256 stakeId) external whenClaimable {
        StakePosition storage pos = stakes[msg.sender][stakeId];
        require(
            block.timestamp >= pos.startTime + pos.year * 365 days,
            "Stake not finished"
        );
        _unstake(msg.sender, stakeId);
    }
}

12.3.3. Liquidity Migration

Liquidity migration is a separate task from token migration. PancakeSwap LP tokens represent a share in the liquidity pool (DEF + paired token), and their direct transfer is not possible. Instead, DeflationChain uses a snapshot-based approach: LP balances are fixed, and equivalent positions are created on DeflationDEX.

The strategy is three-stage. First, LP Token Conversion: snapshot of all LP holders, calculation of their share in DEF and paired token, issuance of new LP tokens on DeflationDEX with identical proportions. Users claim via Merkle proof, just like regular stakes.

Second, Trading Pair Establishment: genesis DeflationChain includes basic DEF/USDC and DEF/WETH pools with initial liquidity from the protocol treasury. Liquidity Bootstrapping Pool (LBP) is used for price discovery — a mechanism that prevents front-running and manipulation at launch.

Third, Migration Incentives: early liquidity providers receive increased rewards (+50% for the first 30 days) to encourage rapid migration and ensure sufficient liquidity from day one.

Liquidity Migration Strategy
PancakeSwap (BSC) → DeflationDEX (DC)
1. LP Token Conversion
Snapshot LP balances • Calculate DEF + paired token • Issue equivalent LP on DeflationDEX • Claim via Merkle proof
2. Trading Pair Establishment
Genesis: DEF/USDC, DEF/WETH pools • Treasury liquidity • LBP for price discovery • +50% rewards (30 days)
3. CEX Listings
Coordinate listing transition • Support BEP-20 + native DEF • Clear network communication
Incentive Structure
Early migrator (first 7 days) +10% airdrop
LP migration +50% rewards (30 days)
Validator setup Priority slot

13. Conclusion

13.1. Summary of Innovations

DeflationChain represents the next generation of Layer-1 blockchains, combining several revolutionary concepts into a single, integrated architecture:

Key innovations:

⚡ DeflationChain: Summary of Innovations
1 Proof-of-Deflation (PoD)
The first consensus mechanism that integrates a deflationary economy directly into the validation process.
PoD_weight = Σ(stake × years) / β_PoD
Long-term stakers → greater influence
Natural alignment of interests
Resistance to attacks
2 Geopolitical decentralisation max ~195 validators
Unique model: 1 validator per country
🛡️ Protection against regulatory attacks
🌍 Global decentralisation
⚖️ Geopolitical neutrality
🔐 KYC against Sybil attacks
3 Hybrid Trading Infrastructure
Centralised matching + decentralised settlement
<1ms
Latency (CEX-grade)
250K
Orders/sec
Self-custody
On-chain settle
50x
Max Leverage
4 Confidential Compute Layer (CCL)
Native AI inference with privacy guarantee
🔒 Intel TDX/SGX hardware security
RA-TLS remote attestation
📜 On-chain Root Contract
🤖 GPU support for LLM
5 Progressive Deflation 🔥 Doubling Burn
Mathematically guaranteed supply reduction
Daily burn from the balance:
Day 1: 1% Day 2: 2% Day 3: 4% Day 4: 8%
Day 5: 16% Day 6: 32% Day 7: 64% Day 8: 100%
🔄 Active usage → reset to Day 0
📈 Staking: up to 20x multiplier (12 years)
💰 50% burned → dividend pool

13.2. Comparative analysis

Characteristic Ethereum HyperLiquid Solana DeflationChain
Consensus PoS HyperBFT PoH + PoS PoD
TPS ~30 200,000 ~65,000 250,000
Block time 12 s < 1 s 400 ms < 1 s
Finality ~15 min < 1 s ~2 s < 1 s
Deflationary model Partially No No Yes (natively)
Compatibility with EVM Native No No Yes
Native trading No Yes No Yes
AI calculations No No No Yes (CCL)
Validator model Open Open Open Geo-restricted
Max. validators ~1 million Unlimited ~3,400 ~195
Governance On-chain Limited Off-chain Hybrid

13.3. Final Words

DeflationChain is not just another Layer-1 blockchain — it is a reimagining of how the cryptocurrency ecosystem should work. By improving proven technologies (HyperBFT, Intel TDX) with an innovative economic model, we are creating a platform that:

  1. Solves the problem of inflation — unlike most cryptocurrencies, DEF is mathematically guaranteed to be deflationary
  2. Ensures true decentralisation — the geographical distribution of validators protects against regulatory attacks
  3. Offers CEX-grade performance — without compromising security
  4. Integrates AI natively — enabling the construction of a new generation of dApps

DeflationChain is the infrastructure for the next decade of decentralised finance and computing.

Sources

  1. HyperLiquid Documentation - https://hyperliquid.gitbook.io/hyperliquid-docs
  2. HyperBFT Wiki - https://hyperliquid-co.gitbook.io/wiki/architecture/hyperbft
  3. Cocoon Architecture (TON Decentralised AI) - https://cocoon.org/architecture
  4. Cocoon GitHub - https://github.com/TelegramMessenger/cocoon
  5. Intel TDX Documentation - https://www.intel.com/content/www/us/en/products/docs/accelerator-engines/trust-domain-extensions.html
  6. Ethereum Yellow Paper - https://ethereum.github.io/yellowpaper/paper.pdf
  7. HotStuff: BFT Consensus with Linearity and Responsiveness - ACM PODC 2019
  8. EIP-1967: Standard Proxy Storage Slots - https://eips.ethereum.org/EIPS/eip-1967
  9. BLS Signatures (IETF Draft) - https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/
  10. Verkle Trees - https://verkle.info/

🛡️ DeflationChain — Deflationary Layer-1 Blockchain with Native AI Computing