> **Source:** https://permissionless.fi/en/30-embedded-compliance
> From *Permissionless Finance* (Permissionless Finance: From Perpetual Futures to the On-Chain Global Market) by Eric Cheung. Licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/).

# Chapter 30: Embedded Compliance and Automated Governance

In November 2022, the collapse of the cryptocurrency exchange FTX exposed a shortfall in customer funds of as much as $8.7 billion; the subsequent bankruptcy investigation and criminal trial revealed the complete failure of its internal controls and large-scale misappropriation of assets [1]. This event marked the structural bankruptcy of the trust model underlying centralized crypto-finance institutions. Its core lesson was not merely the isolated failure of a single institution, but the structural fragility of the traditional financial compliance paradigm when confronted with digital-native institutions that hold complete control over assets. Traditional financial compliance is essentially an external enforcement mechanism that relies on ex post penalties; it presupposes that an institution is physically and technically capable of violating the rules and that its incentive to comply derives solely from avoiding those penalties (its logic and premises are detailed in Section 30.1.1). When a centralized institution holds unrestricted private keys to assets and the power to modify databases, the lag inherent in external supervision means that no periodic compliance check can prevent the asset misappropriation or ledger tampering that has already occurred [2]. This systemic risk raises the central question of this chapter: how can regulatory compliance requirements and system governance mechanisms be embedded directly into the architecture of on-chain financial systems, thereby transforming compliance from an external mandate that depends on institutional self-discipline into a built-in guarantee that makes violations physically impossible at the system level?

Embedded compliance proposes a paradigm fundamentally different from traditional regulation. Its underlying logic is to use cryptography and smart-contract technology to design a system that, at the architectural level, excludes the possibility of specific violations [3]. Under this paradigm, rules are no longer legal provisions on paper or entries in a compliance manual; they are compiled directly into the execution logic of smart contracts. If the system requires that customer assets be strictly segregated, this rule is encoded as a contract function that permits withdrawals only when triggered by the customer's own private-key signature, making it technically impossible for the protocol developers or the operating team to misappropriate any assets. This design, which converts behavioral constraints into architectural constraints, achieves a paradigm shift from requiring institutions to obey the law to making it impossible for them to break it. Yet hard-coding rules into smart contracts is not a panacea. The complexity of financial systems requires a balance between the security of immutability and the flexibility to adapt to changing markets: complete rigidity would leave a system unable to cope with extreme market volatility or protocol vulnerabilities, whereas excessive flexibility could reintroduce the single-point-of-failure and trust risks that administrator privileges entail. Building a robust on-chain financial system therefore requires careful engineering trade-offs in both the embedding depth of rules and the design of governance mechanisms. Crucially, embedded compliance rests on the premise that the correctness of smart-contract code can be guaranteed through means such as formal verification; if the code implementing a compliance rule itself contains a vulnerability, the credibility of the architectural constraint is fundamentally undermined.

This chapter takes an engineering-implementation perspective to systematically construct the theory and methodology for embedding compliance and governance into on-chain architecture. The three-tier compliance spectrum divides compliance mechanisms by embedding depth into hard-coded, parameterized, and reporting-based compliance. Hard-coded compliance applies to non-negotiable security baselines such as asset segregation; parameterized compliance handles operational parameters such as the margin ratio, which must be adjustable yet remain transparent; and reporting-based compliance leverages the openness of on-chain data to enable automated transaction monitoring and real-time risk disclosure. At the governance layer, the dual architecture of timelock and emergency powers strikes a balance between immutability and flexible response through a mandatory delayed review for routine changes and a constrained fast track for extreme situations. Finally, the chapter translates the regulatory frameworks and principles discussed earlier into a concrete inventory of on-chain technical implementations, completing the mapping from regulatory requirements to engineering code.

## 30.1 The theoretical foundations of embedded compliance

Traditional financial compliance relies on external enforcement to constrain institutional behavior, and this model has exposed structural limitations in cost, timeliness, and cross-border coordination. By embedding compliance rules into the execution logic of smart contracts, on-chain financial systems offer an alternative that shifts from behavioral constraints to architectural constraints. However, different types of compliance requirements differ significantly in how much embedding depth and flexibility they demand, which calls for engineering trade-offs across the three tiers of hard-coded, parameterized, and reporting-based compliance. This section first analyzes the limitations of the traditional model, then sets out the core concept of embedded compliance and the three-tier spectrum, and finally shows how macro-level regulatory principles can be mapped onto concrete on-chain implementation paths.

### 30.1.1 The limits of the traditional compliance model

The core logic of traditional financial compliance rests on the dual assumptions of trust and verification. Regulators set the rule framework, financial institutions pledge to comply with those rules, and internal compliance departments, external auditors, and regulators then verify compliance through periodic inspections. The fundamental premise of this model is that a financial institution is fully capable, physically and technically, of violating the rules, and that it chooses to comply mainly out of fear of reputational damage and legal penalties. This model of external enforcement grounded in ex post sanctions, however, is exposing increasingly severe structural limitations.

The most conspicuous limitation lies in the ever-rising cost of compliance. In modern financial systems, compliance has become a high-cost operational burden. According to industry research, compliance costs account for roughly 10% to 20% of a financial institution's operating expenses, and the proportion is higher for some small community banks and regional financial institutions [4]. Since the 2008 global financial crisis, the operating costs that retail and corporate banks devote to compliance have risen by more than 60% [5]. These high costs are ultimately passed on to end consumers through higher service fees and lower deposit rates. In addition, global spending on the anti-money laundering (AML) systems (software and systems) market is projected to reach $51.7 billion by 2028 [6]. Despite the enormous investment, this resource-intensive compliance model has not fully prevented financial crime or systemic risk. To be sure, the high cost of the traditional compliance system is not entirely wasted: macroprudential regulatory frameworks have demonstrable empirical effects in reducing the frequency of systemic crises and limiting their reach. The improvement that embedded compliance offers lies mainly in reallocating the wasteful overhead of "compliance theater" in the traditional model into architectural-level, built-in guarantees, rather than simply replacing every traditional compliance function.

A second structural flaw of the external-enforcement model is its lack of timeliness. Traditional compliance checks are typically based on quarterly reports or annual audits, and such low-frequency, snapshot-style reviews cannot capture violations that occur between two checks. By the time an auditor or regulator discovers a problem, the violation has often persisted for months or even years, and the resulting damage may already be irreparable. The FTX case is an extreme manifestation of this limitation. Although the institution claimed to have strict internal controls, when its de facto controller decided to misappropriate customer assets, no periodic inspection mechanism was able to intercept the behavior before or as it occurred.

This lag further gives rise to the phenomenon of "compliance theater." At many financial institutions, the purpose of compliance activity has gradually shifted from "effectively reducing risk" to "passing regulatory inspections" [4]. Institutions devote substantial resources to filling out forms, generating reports, and designing complex compliance workflows; these activities superficially satisfy regulatory requirements but do not substantively change the business's risk exposure. When compliance becomes a formalistic exercise aimed at meeting regulatory metrics, it not only wastes social resources but also manufactures a false sense of security.

The compliance predicament of centralized cryptocurrency exchanges pushes these structural flaws to an extreme. Unlike traditional banks, the core business of a centralized exchange (CEX) runs entirely on digital infrastructure: order matching is completed on off-chain centralized servers, customer assets are stored in hot and cold wallets whose private keys the exchange controls, and the internal ledger exists as database records that administrators can modify at will. This architecture means that external auditors cannot verify in real time the consistency between the asset status the exchange claims and the actual on-chain address balances. Even a periodic financial audit is effective only to the extent that the exchange voluntarily provides complete and truthful data, and the collapse of FTX is precisely an extreme confirmation of this architectural flaw.

The fragmentation of cross-border compliance makes these problems even more complex. In globally operating financial markets, different jurisdictions have starkly different and sometimes conflicting compliance requirements. A global financial institution must satisfy dozens of different regulatory frameworks simultaneously, which not only causes compliance costs to grow exponentially but also leaves institutions stretched thin across regulatory regimes, unable to build a unified and coherent risk-control system.

### 30.1.2 The core concept of embedded compliance

Confronted with the structural failure of the traditional compliance model, on-chain financial systems propose a paradigm shift: embedded compliance. The core of this concept is to convert compliance from a "behavioral constraint" into an "architectural constraint." Under the behavioral-constraint model, rules tell participants "what they should not do," but participants still retain the physical ability to do it; under the architectural-constraint model, the system is designed so that violations become physically and technically impossible.

This concept can be likened to the evolution of building fire codes. Modern building codes no longer rely solely on periodic inspections by fire marshals; instead, they fix firewall materials and sprinkler coverage in the building's blueprint at the design stage, so that the physical structure of the building excludes the possibility of specific fire-code violations. Embedded compliance follows the same engineering logic, moving constraints forward into the system design stage.

In on-chain financial systems, the smart contract serves as the execution engine of this concept. Once a smart contract is deployed to a blockchain, its logic executes strictly according to its code. Code execution is unaffected by conflicts of interest or operational negligence; its output is determined entirely by its inputs and logic. If we encode compliance rules as part of a smart contract, those rules become an inseparable property of the system, giving concrete form, in the domain of financial regulation, to Lawrence Lessig's idea that "code is law" [3][7][8]. When a transaction is broadcast to the network, the system verifies not only its technical validity but also, at the compliance level, whether it is permitted. If a transaction violates the preset compliance logic, the smart contract simply refuses to execute it, making the violation impossible to occur on-chain in the first place.

This shift from ex post detection to ex ante prevention means that compliance is no longer an add-on process separate from the core business but an intrinsic feature of the financial infrastructure itself. It substantially reduces the reliance on human intervention found in traditional compliance, lowers the ongoing operational cost of compliance, and raises the certainty of compliance from the probabilistic level to the level of cryptographic guarantee.

Embedded compliance, however, is not without limits. First, not all regulatory rules are suitable for, or capable of, being translated into deterministic code logic. Many compliance requirements contain fuzzy boundaries and room for subjective judgment. Second, code itself may contain vulnerabilities; if compliance logic is incorrectly encoded, it may cause legitimate transactions to be rejected or non-compliant transactions to be admitted. More complex still, the regulatory environment and market conditions change continuously, and if rules are hard-coded into the system in a completely rigid form, the system loses the ability to adapt to future change. A deeper limitation is that although embedded compliance eliminates human bias at the execution level, the code itself is written by developers who carry cognitive biases; availability bias, for example, may lead to over-guarding against recently known risks while ignoring unknown ones, and hard-coding a biased judgment into immutable logic effectively locks that bias in—converting it from a "correctable operational decision" into an "immutable system architecture." Moreover, in the traditional compliance framework, legal liability for violations is clearly attributed to the financial institution; once compliance rules are embedded in a smart contract, if the contract's behavior produces a law-violating outcome, the attribution of liability becomes highly ambiguous among the contract deployer, the code developers, the auditing firm, and the governance voters. This "accountability gap" is one of the core practical obstacles to regulators' acceptance of embedded compliance. These limitations raise a key question: how can the rigidity of rules be preserved while endowing the system with the necessary capacity to evolve?

### 30.1.3 The three-tier compliance spectrum

To resolve the tension between flexibility and certainty in embedded compliance, this chapter proposes the theory of the "three-tier compliance spectrum." This theory holds that compliance requirements should not be hard-coded indiscriminately; rather, compliance mechanisms should be divided into three distinct tiers by "embedding depth," according to the nature of the rule, the consequences of violating it, and the need for flexibility.

These three tiers each strike their own balance between flexibility and certainty, and together they constitute a complete on-chain compliance framework.

![Figure 30-1](./images/fig-30-1-en.png)

**Figure 30-1.** The three-tier compliance spectrum and its relationship to embedding depth, flexibility, and certainty [3]

Hard-coded compliance represents the deepest embedding and the highest certainty. In this tier, compliance rules are written directly into the underlying logic of the smart contract, with no interface for modification. Such rules typically concern the system's security baseline; their defining features are that they are "non-negotiable" and that a single violation would lead to severe consequences. Asset segregation, for example, must be hard-coded. The system must ensure through code that, apart from the user's own cryptographic-signature authorization and liquidation events that satisfy strict trigger conditions, no administrator key or protocol backdoor can move a user's funds. An absolute leverage cap is another typical application of hard-coding: by setting an insurmountable maximum leverage multiple at the code level, the system effectively prevents the emergence of extreme risk exposure. The cost of hard-coded compliance is a significant reduction in flexibility, as any modification of the rules requires a complex contract upgrade.

Parameterized compliance sits in the middle of the spectrum, offering a compromise in which "the rule framework is fixed but the specific parameters are adjustable." Many operational compliance rules must be dynamically adjusted in response to market volatility and changes in regulatory policy. The margin ratio, for example, must rise as market volatility increases in order to absorb larger potential losses. Under parameterized compliance, "margin must be collected" and "the formula for computing the margin ratio" are hard-coded, but the specific coefficients within the formula are parameterized. These parameters are stored in a dedicated registry contract and can be modified through an established governance process. This design both guarantees the stability of the compliance framework and endows the system with the flexibility to adapt to environmental change.

Reporting-based compliance represents the shallowest embedding. Not all compliance requirements are suited to serving as ex ante restrictions. For behaviors that require holistic judgment or ex post tracing—such as detecting abnormal trading patterns, identifying wash trading, and preventing market manipulation—forcibly intercepting transactions before execution could seriously impair system throughput and the trading experience of legitimate users. Reporting-based compliance exploits the full transparency and immutability of blockchain data, exporting on-chain data in real time and feeding it into analytical models to achieve automated ex post monitoring. In addition, real-time risk disclosure and proof of reserves belong to this tier; they do not restrict user behavior but satisfy the regulatory demand for transparency by providing ample information visibility.

These three tiers are not mutually exclusive but highly complementary. Hard-coded compliance guards the system's untouchable security baseline, parameterized compliance provides the elasticity needed for day-to-day operations, and reporting-based compliance supplements the ongoing monitoring of complex behaviors. No single tier can cover all compliance requirements; only by organically combining the three can one build an on-chain financial system that is both secure and sustainable.

### 30.1.4 From regulatory principles to engineering implementation

In Chapter 26, we proposed six core regulatory principles applicable to decentralized finance (DeFi): asset segregation as the baseline, disclosure first, functional regulation, embracing embedded compliance, combining international minimum standards with flexible adjustment, and evidence-based evolution. These macro-level principles constitute the requirements specification for on-chain compliance engineering, and the three-tier compliance spectrum provides a systematic implementation path from "what should be regulated" to "what is technically guaranteed." The next three sections respectively develop hard-coded (Section 30.2), parameterized (Section 30.3), and reporting-based compliance (Section 30.4), and Section 30.7 closes the loop from regulatory requirement to engineering code with a complete mapping table.

## 30.2 Hard-coded compliance

In the architectural design of embedded compliance, hard-coding represents the deepest constraint. The violation of certain rules would lead to systemic catastrophe, so those rules should possess no flexibility. The core logic of hard-coded compliance is to write these non-negotiable baselines directly into the immutable logic of the smart contract, so that no one, under any circumstances, can physically circumvent them.

### 30.2.1 When hard-coding applies

The core criterion for judging whether a rule should be hard-coded is whether the consequences of violating it are severe and irreversible. If a violation can inflict serious damage on the system before it is discovered, ex post punishment and compensation lose their meaning. In such cases, making violations physically impossible ex ante through code becomes the only engineering option.

Rules suited to hard-coding typically possess broad universality and a low update frequency. The asset-segregation mechanism is the most typical scenario for hard-coding. Customer assets must be independent of protocol operating funds—a baseline that does not change under any market environment or regulatory framework. If a protocol operator or administrator were allowed to withdraw user assets through some privilege, the system would revert to the traditional trust model, whose fragility the FTX case demonstrated. The absolute leverage cap likewise falls within the scope suited to hard-coding. When leverage exceeds a certain critical value, even a minuscule price movement can trigger liquidation, which in turn causes a liquidation cascade. This systemic risk should not be left to dynamic adjustment by operational parameters but must be capped by an insurmountable constraint at the code level [9]. The conditions for using the insurance fund must also be hard-coded: its funds may be used only to absorb liquidation losses, and any attempt to divert them to other uses should be automatically rejected at the contract level.

By contrast, many operational rules are not suited to hard-coding. The margin ratio must be dynamically adjusted according to market volatility, the determination of abnormal trades depends on complex pattern recognition and subjective judgment, and specific identity-verification standards evolve with the legal developments of different jurisdictions [10]. Hard-coding rules that require flexible response would trap the system in excessive rigidity, ultimately leaving it unable to meet the market's real needs. The scope of hard-coding must be strictly limited to the core logic that defines the system's baseline for survival.

### 30.2.2 Hard-coding asset segregation

In the traditional financial system, asset segregation relies on complex institutional design. Take the Depository Trust & Clearing Corporation (DTCC): it ensures the segregation of customer assets from the institution's own funds through strict legal contracts, periodic external audits, and a multi-tiered account structure. Although this segregation mechanism grounded in institutional trust has proven highly reliable over the past 200 years, its essence remains guarding against violations rather than eliminating the ability to violate [11]. When this trust model is transplanted to an offshore cryptocurrency exchange that lacks strong regulation, its inherent fragility is fully exposed.

The asset-custody model of centralized cryptocurrency exchanges amplifies this fragility. Mainstream CEXs commonly adopt an omnibus wallet architecture, pooling all customer assets into a small number of on-chain addresses controlled by the exchange, while individual customer balances exist only as mappings in the exchange's internal database. This means that at the on-chain level, an external observer cannot distinguish the exchange's own assets from customer assets, let alone verify the accuracy of the internal ledger. The exchange holds complete control over the private keys of its hot and cold wallets, order matching is completed off-chain, and asset transfers require no customer authorization. The FTX case is precisely an extreme manifestation of this architectural flaw: Alameda Research was able to directly deploy FTX customer assets for its own trading, while external audits failed to uncover this fact for as long as two years. This model, in which a single entity simultaneously controls asset custody and ledger records, stands in fundamental contrast to the self-custody architecture of on-chain finance.

On-chain financial systems achieve a paradigm shift in asset segregation through smart contracts. The stablecoins or other collateral that users deposit are locked in an on-chain margin contract. The logic of this contract is strictly delimited, permitting changes in the margin balance only under four conditions explicitly defined in code. First, the user cryptographically signs a withdrawal transaction with their own private key. Second, when the user's position health falls below the liquidation threshold, the liquidation engine triggers the forced-liquidation logic. Third, periodic settlement transfers are executed automatically between longs and shorts according to the funding rate formula. Fourth, when the insurance fund is insufficient to cover shortfall losses, the auto-deleveraging (ADL) mechanism forcibly and partially closes the positions of profitable counterparties. Beyond these code-defined liquidation and trading operations (and analogous code-defined paths such as the deduction of trading fees and the settlement of realized profit and loss upon position closure), no discretionary administrative instruction can move a user's assets; neither the protocol development team, nor operational administrators, nor any third party holds a privileged interface capable of bypassing these paths. These guarantees carry one caveat: when this logic is deployed in an upgradeable proxy contract, they amount only to "version-level hard-coding," whose strength depends on the constraint mechanisms governing the upgrade authority itself (see Section 30.6.3).

Figure 30-2 presents this smart-contract-based asset-segregation architecture: user assets are locked in a non-custodial margin contract, and the trigger conditions and execution scope of all four asset-movement paths are explicitly defined in code.

![Figure 30-2](./images/fig-30-2-en.png)

**Figure 30-2.** The hard-coded design architecture for asset segregation [11]

The core constraint of this design is that it eliminates administrator privileges in the traditional sense. Even the protocol development team that deploys the contract cannot use a backdoor key or superuser privilege to withdraw a user's margin. The security of assets no longer depends on the team's moral integrity or on legal constraints but is guaranteed by the consensus mechanism and cryptographic primitives of the underlying blockchain, such as Ethereum.

The effectiveness of code-level asset segregation rests on a series of operational premises. On the user side, private-key security is the first line of defense: if a user's private key is stolen through a phishing attack, the attacker can withdraw all of the user's assets through a completely "legitimate" signature path, against which the hard-coded segregation logic is powerless. On the system side, the liveness guarantee of the liquidation engine is a critical operational dependency of the segregation mechanism: if the liquidation bots go down, if network congestion prevents liquidation transactions from being confirmed on-chain in time, or if a spike in gas prices makes liquidation unprofitable, the liquidation path fails and the system may incur shortfalls. The reliability and timeliness of oracle price feeds constitute an equally critical premise. In addition, there is a significant gap between "having the right to withdraw" and "being able to withdraw in a timely manner": network congestion may prevent a withdrawal transaction from being confirmed for a long time, a suspension of cross-chain bridging may block assets from returning to the mainnet, and an emergency-pause mechanism may temporarily restrict an individual user's withdrawals even as it protects the system. Hard-coded compliance eliminates the risk of an administrator misappropriating assets, but it cannot cover these operational-level failure modes.

This purely code-level segregation, however, faces significant challenges in engineering practice. The largest risk exposure often lies in the cross-chain bridging step. In app-chain architectures such as Hyperliquid, a user's native assets (such as USDC on the Ethereum mainnet) typically must be locked through a bridge contract in order to mint an equivalent synthetic asset on the app-chain. A series of major bridge-security incidents between 2022 and 2024 revealed several attack paths: a flaw in a bridge contract's verification logic may allow an attacker to forge cross-chain messages; the leakage of validator private keys or a social-engineering attack can directly seize control of the bridge (in the 2022 Ronin incident, for example, the attacker gained signing control over 5 of 9 validators—four Sky Mavis validator keys were stolen, plus the abuse of a third-party validator's authorization—causing losses of approximately $625 million); relayer spoofing may bypass message-verification mechanisms (as in the message-verification bypass in the Nomad incident); and if an attacker obtains the upgrade authority over a bridge contract, they may fundamentally alter its asset-transfer logic. Any one of these attack vectors could allow an attacker to move assets without a user's signature, thereby circumventing the segregation constraints of the margin contract. For an architecture like Hyperliquid's, which uses a "native bridge" that shares the same validator set as the consensus layer, bridge security and consensus security are fully coupled: the compromise of the validator set means the simultaneous failure of both the bridge and consensus. This risk-concentration property differs fundamentally from a general-purpose cross-chain bridge that uses an independent validator set.

In addition, the upgrade authority over the margin contract itself constitutes another layer of risk. If the contract retains an upgrade authority, the entity holding that authority could, in theory, lift the segregation constraints by replacing the contract logic. This makes the management of the upgrade authority the most sensitive trust assumption in a hard-coded compliance system.

Hard-coded asset segregation also faces a structural challenge arising from the composability of smart contracts. In an on-chain financial ecosystem, when the assets or derivative certificates in a margin contract can be referenced by other protocols or used as collateral, interactions between contracts may circumvent the segregation constraint at the economic level, even if the code logic of each individual contract is correct. System designers face a trade-off between "closed segregation" and "open segregation": the former maintains the strictest segregation guarantee by prohibiting margin assets from participating in any external contract interaction, but sacrifices capital efficiency; the latter permits limited cross-protocol interaction subject to additional constraints, but introduces a new risk dimension in the complexity of security auditing.

Moreover, the discussion of smart-contract asset segregation above implies an important distinction: on a general-purpose public chain such as Ethereum, the logic of a margin contract can be independently audited and formally verified by any third party; but in an app-chain architecture such as Hyperliquid, the core margin-management logic runs in the consensus-layer state machine rather than in an independently auditable smart contract. This means that the trust assumption for asset segregation shifts from "the correctness of the code logic" to "an honest-majority assumption among validators," and in a network with only about two dozen active validators, this consensus security is far below the security guarantee that the thousands of validators on the Ethereum mainnet provide. The "architectural-level guarantee" described here therefore needs to be qualified according to the consensus-security model of the specific system, rather than treated as a universal conclusion about on-chain finance.

### 30.2.3 Hard-coding the leverage cap

Leveraged trading is a core function of derivatives markets, but excessive leverage is a primary source of market fragility. In decentralized perpetual futures, if traders are allowed to use extreme leverage (such as 500x or 1,000x), the bankruptcy price of their position lies extremely close to the entry price. Under the constraints of block-confirmation latency on a blockchain network and the discreteness of oracle price updates, the liquidation engine simply cannot complete a forced liquidation before the position's net value reaches zero, which inevitably leads to the rapid depletion of the insurance fund and system shortfalls [12].

Hard-coding the leverage cap is the most direct means of guarding against this kind of systemic risk. In the smart contract's position-opening logic, the system computes the ratio of the requested notional value to the user's available margin. The code explicitly stipulates that if this ratio exceeds a preset absolute cap (for example, 50x), the transaction is automatically reverted. This constraint requires no real-time approval from a risk-control team and does not depend on alerts from a post-trade monitoring system. When a transaction is submitted to the blockchain network, the deterministic execution logic of the Ethereum Virtual Machine (EVM) ensures that any request violating the leverage cap cannot alter the system's global state.

In actual engineering design, the hard-coded absolute cap is typically nested with a parameterized dynamic cap. The hard-coded cap sets a physical ceiling that the system cannot exceed under any extreme circumstances, while the dynamic cap is adjusted in real time according to the current market's liquidity depth, the asset's volatility characteristics, and the user's position size. For example, the contract code might hard-code an absolute cap of 100x, but during periods of high volatility a governance mechanism or automated risk engine would adjust the dynamic cap actually enforced down to 20x. This nested design both preserves the flexibility to respond to market changes and, through hard-coding, establishes an absolute baseline for the system's survival.

The calibration of a hard-coded leverage cap should not be an arbitrary number but should establish a quantitative constraint relationship with the latency parameters of the underlying infrastructure: the maximum leverage must ensure that the liquidation engine completes forced liquidation before the position's net value reaches zero. If the oracle's maximum update latency is 2 seconds and the maximum expected price movement of a major asset within that window is 0.5%, then the critical point at which the price move exactly exhausts all margin corresponds to about 200x leverage (that is, $1/0.5\% = 200$). But 200x is merely the absolute cap at which the position's net value reaches zero, not a "safe" level of leverage: the usable buffer is in fact the initial margin minus the maintenance margin, and one must further deduct the liquidation delay caused by network congestion and the execution slippage caused by evaporating liquidity. Safe leverage must therefore satisfy $\text{safe leverage} < \dfrac{1}{\text{maintenance margin ratio} + \text{max adverse move within latency} + \text{execution slippage} + \text{congestion buffer}}$, and its actual value is far below 200x—which also explains why the earlier examples set the hard-coded absolute cap in the 50x–100x range. In addition, the hard-coded check should not be limited to the initial verification at the moment of opening a position: in a unified margin account, the unrealized loss on one position reduces the account's available margin, causing the effective leverage of other positions to rise implicitly. Even if every position passed the leverage check when opened, the system must continuously verify at each mark-price update whether the effective leverage of the entire account still lies within the hard-coded cap. Finally, a hard-coded leverage cap has one fundamental limitation: it constrains only the leverage within a single protocol. In a composable on-chain financial ecosystem, a trader can open same-direction positions across multiple protocols simultaneously, achieving effective leverage far exceeding the cap of any single protocol. This cross-protocol synthetic leverage cannot be resolved through hard-coded compliance; it requires ecosystem-level leverage tracking at the reporting-based compliance layer for monitoring and early warning.

### 30.2.4 The cost of hard-coding

Hard-coding rules into a smart contract provides cryptographic-level execution certainty, but this certainty comes at the cost of extreme system rigidity. The immutability of the underlying blockchain architecture means that once a smart contract is deployed, the bytecode it contains resides permanently on the distributed ledger. If a hard-coded rule needs to be modified—even by changing a single small constant value—a completely new smart contract must be deployed, and all users and liquidity must be migrated to it. This migration process is not only costly but also causes severe fragmentation of liquidity.

Over-reliance on hard-coding leaves a system unable to adapt in rapidly evolving financial markets. The microstructure, asset types, and attack vectors of cryptocurrency markets are all constantly changing. A hard-coded rule that appears perfect in the current market environment may, a year later, become a serious constraint that impedes the protocol's development. Only underlying security logic that has withstood the test of time and possesses broad applicability is therefore qualified to be hard-coded.

Furthermore, the security of hard-coding rests entirely on the correctness of the code. If the hard-coded logic contains an implementation vulnerability, a rule intended to protect the system may be exploited by an attacker. In complex DeFi protocols, interactions among smart contracts can produce unforeseeable edge cases. Traditional software-testing methods cannot cover all possible execution paths, which makes formal verification a necessary complementary discipline for hard-coded compliance [13]. Formal verification abstracts a smart contract into a mathematical model and uses logical reasoning to prove whether it satisfies specific properties (such as safety and liveness). Only hard-coded rules that have been rigorously proven mathematically can truly provide a security guarantee that surpasses traditional institutional trust. The engineering solution to this cost of rigidity—the proxy contract pattern and governance constraints—is developed systematically in Section 30.6.

## 30.3 Parameterized compliance

Most operational compliance rules are not suited to hard-coding, because they must be dynamically adjusted as market conditions and regulatory requirements change. Parameterized compliance offers a compromise in which the rule framework is fixed while parameters can be adjusted through governance, endowing a protocol with the flexibility to adapt to a complex financial environment while keeping its basic logic immutable.

### 30.3.1 When parameterization applies

Whereas hard-coded compliance applies to security baselines that must never be violated, the applicable boundary of parameterized compliance lies in operational metrics that must be dynamically optimized across different market cycles. The core criterion for judging whether a rule is suited to parameterization is whether its mathematical framework or logical structure is stable while its specific values must respond to changes in the external environment. When market volatility rises sharply, a fixed margin ratio may fail to cover the potential liquidation-slippage risk; when the efficiency of cross-chain arbitrage improves, the settlement frequency of the funding rate may need to be increased accordingly. These scenarios require the system to have a capacity for self-regulation, but that regulation must occur within a preset framework, and the adjustment process must be fully transparent to all participants.

The applicable scenarios for parameterized compliance fall into five categories. The first is the margin ratio: as discussed in Section 29.3, the maintenance margin requirement must vary dynamically with asset volatility and position size in order to guard against liquidation-cascade risk under extreme market conditions [14]. The second is rate parameters, including the settlement frequency, upper and lower bounds of the funding rate, and the size of the risk buffer pool; these parameters directly affect the holding costs of longs and shorts and the protocol's solvency [15]. The third is liquidation parameters, such as the trigger line and execution speed of progressive liquidation, which determine the degree of market impact during deleveraging. The fourth is market-making obligations: an on-chain order book or automated market maker pool must set a minimum liquidity depth, a maximum permissible spread, and obligation-waiver conditions under extreme market conditions in order to ensure the continuous operation of the market. The fifth is access parameters, which concern the compliance requirements of different jurisdictions, such as trading restrictions on specific assets or tiered standards for risk limits.

Hard-coding these operational parameters would leave the system rigid and without means to respond to sudden events; leaving them entirely to arbitrary modification by off-chain administrators would undermine the trustless foundation of DeFi. Parameterized compliance resolves this contradiction through a parameter-registry mechanism in the smart contract. The rule's execution logic is written permanently into the code, while the specific values are stored in a separate registry contract. Any modification to a value in the registry must go through an explicit governance process and is subject to a timelock, thereby achieving an engineering optimum between flexibility and transparency [16].

The engineering design of the parameter registry follows the principle of separation of concerns. In a traditional monolithic-contract architecture, parameters and execution logic are intermingled, and modifying a parameter often requires redeploying the entire contract—which is not only costly but also prone to introducing new vulnerabilities. In a parameterized architecture, parameters are stored in a dedicated registry contract responsible only for data management and access control, without complex business logic. The execution contract reads parameters from the registry through a standard interface, much like querying a database. This separation allows parameter updates to be carried out independently without affecting the security of the core trading logic. At the same time, the history of parameter changes is preserved completely on the blockchain, forming an immutable audit trail, so that any regulator or user can trace the evolution of the protocol's parameters and verify its compliance.

### 30.3.2 Parameterizing the margin ratio

The margin ratio is the core line of defense in the risk management of a derivatives protocol. In an on-chain environment, setting the margin ratio is not merely an economic question but a compliance-engineering one. A traditional static margin ratio may cause low capital efficiency during low-volatility periods and fail to provide an adequate buffer during high-volatility periods, and this mismatch is an important structural cause of liquidation cascades [17]. To address this problem, on-chain protocols have introduced a volatility-adaptive margin-computation model and nested the regulatory baseline and the dynamic-adjustment mechanism within the smart-contract architecture.

Figure 30-3 presents the three-tier nesting of margin parameterization—a hard-coded regulatory baseline, a fixed adaptive-formula framework, and governance-adjustable parameter coefficients—which the following text develops tier by tier.

![Figure 30-3](./images/fig-30-3-en.png)

**Figure 30-3.** The three-tier nested design of margin parameterization [14][18] (the 10% maintenance-margin-ratio floor shown is illustrative)

The bottom of this design is the hard-coded regulatory baseline. At the code level, the smart contract mandates an absolute minimum for the maintenance margin ratio—for example, 10%. No matter how calm the market or how the governance committee votes, the system refuses to execute any operation that would drive the margin ratio below this floor. This hard-coding ensures that the protocol always meets the strictest regulatory requirements, eliminating the possibility that human negligence or malicious manipulation could create systemic risk.

Above the floor is the adaptive-formula layer. The formula for computing the margin ratio is hard-coded into the contract and typically comprises a base rate, a volatility multiplier, and a position-size penalty term. For example, the maintenance margin requirement rises in tiers as the notional value of a position increases; when position value increases from $100,000 to $1 million, the required margin ratio may automatically rise from 0.4% to 0.5% [18]. This logical framework is fixed, ensuring the objectivity and consistency of risk assessment.

In fact, the tiered margin mechanism is not an on-chain invention; mainstream centralized exchanges have long widely adopted a similar tiered margin structure. Take Bybit: the maintenance margin ratio on its USDC perpetual futures rises from 0.40% at the first tier to more than 5.00% at the higher tiers [18]. The low-tier maintenance margin ratios among these CEX tier parameters (e.g., 0.40%, nominally corresponding to maintenance leverage of about 250x, i.e., $1/0.40\% = 250$) fall below the initial-margin level implied by the leverage cap derived from oracle latency in Section 30.2.3 (the maintenance margin ratio and the latency buffer are different measures and should not be equated directly), and the hard-coded floor of an on-chain system constrains the lower bound of the tier parameters, ensuring that even the lowest-tier margin ratio is not below the system's security baseline. Binance, OKX, and other exchanges adopt similar tiered systems, while Deribit has introduced a portfolio margin model in its options market that dynamically computes net risk exposure through hedging relationships. However, these CEX tiered margin systems have one fundamental difference: the authority to change parameters lies entirely and unilaterally with the platform. An exchange can adjust tier thresholds and margin ratios without any public-notice procedure, and users are informed only after the parameters take effect. By contrast, an on-chain system ensures the process transparency and auditability of every margin-parameter adjustment through a parameter registry and a governance-voting mechanism, which constitutes the core advantage of on-chain parameterized compliance over CEX dynamic-margin systems.

The top layer is the real-time adjustment of parameterized coefficients. The multipliers and thresholds in the adaptive formula are stored as parameters in the registry contract. When a macroeconomic event triggers a structural change in the market, the governance mechanism can adjust these coefficients so that the margin model captures risk more sharply. For example, during a period of sharply rising expected volatility, the volatility multiplier can be raised to tighten leverage system-wide. This three-tier nested architecture allows regulators to be confident of the system's security floor, allows traders to know clearly the computational logic of margin requirements, and leaves protocol operators the tools they need to respond to unknown risks.

In practice, the parameterized coefficients of a volatility-adaptive formula typically span three dimensions. The first is the volatility-sensitivity coefficient, which controls how much the margin ratio increases for each 1% rise in market volatility. This coefficient might be set at 0.15 in a calm market, but during a period of persistently elevated historical volatility the governance committee might vote to raise it to 0.25 in order to guard against a potential liquidity crisis in advance. The second is the position-size penalty coefficient, which reflects the systemic-risk contribution of large positions to the market. When an individual trader's position size exceeds a certain threshold of market liquidity, this coefficient is automatically triggered, requiring a higher margin ratio. The third is the time-decay coefficient, used to gradually loosen margin requirements after the market returns to calm, avoiding excessive liquidity tightening. The calibration of these coefficients should be based on a target coverage probability—that is, ensuring that, at a given confidence level, the margin can cover the maximum expected price movement over the period from liquidation trigger to completed closure—rather than being set arbitrarily by experience. The combined use of these coefficients forms a multidimensional risk-assessment model capable of capturing both changes in market microstructure and macroeconomic shocks.

While improving capital efficiency, the volatility-adaptive margin model introduces a systemic risk that cannot be ignored: procyclicality. When market volatility rises, the adaptive model automatically raises the margin ratio, forcing leveraged traders to add margin or face liquidation. Large-scale liquidations themselves further intensify market volatility, pushing volatility metrics still higher, which tightens the margin ratio further; this positive-feedback spiral of "rising volatility → tightening margin → forced liquidation → further rising volatility" is the core driving mechanism of a liquidation cascade. During Black Thursday in March 2020, this effect was amply demonstrated empirically in DeFi liquidations. To mitigate procyclicality risk, the engineering design of margin parameterization should introduce a countercyclical buffer mechanism: the margin ratio should respond quickly to rising volatility, but its relaxation should be slow and subject to a "look-back period" constraint (asymmetric decay); the magnitude and rate of a single margin-ratio adjustment should be capped to prevent violent tightening within a short time; and during low-volatility periods, the margin ratio should be pre-emptively set above the model's raw output to reserve a buffer against future volatility shocks.

### 30.3.3 Parameterizing rate parameters

The funding rate mechanism is the core engine by which perpetual futures anchor to the spot price. Its design goal is to correct the deviation between the derivative price and the spot index through periodic funding exchanges between longs and shorts. In an on-chain implementation, the funding rate's computation logic is typically hard-coded, but its operational efficiency and risk boundaries depend heavily on several key parameterized settings.

The settlement frequency determines arbitrageurs' capital-turnover efficiency and the market's responsiveness. Traditional centralized exchanges typically adopt a discrete settlement mechanism every 8 hours, whereas in on-chain protocols, constrained by block-generation time and transaction costs, the parameterized choice of settlement frequency faces different engineering constraints [19]. A higher settlement frequency can anchor the price more tightly but significantly increases the computational overhead of oracle price feeds and state updates. Parameterizing the settlement frequency allows a protocol, as the underlying public chain scales or Layer 2 costs fall, to transition smoothly through governance voting toward higher frequencies and even per-block settlement (in a discrete blockchain architecture, per-block settlement is the finest granularity physically achievable) without restructuring the core trading logic. The effect of shortening the settlement interval is not linear: while a higher settlement frequency improves price-anchoring precision, it also raises the capital-efficiency requirements of arbitrage strategies, accelerates market makers' hedging-frequency needs, and may increase the volatility of each individual rate value—second-order effects that must be fully evaluated when adjusting the parameter.

Parameterizing the upper and lower bounds of the rate serves to prevent systemic collapse under extreme one-sided market conditions. When the spot price fluctuates violently, the theoretical funding rate may spike to extreme levels, subjecting market makers or hedgers to unbearable cash-flow pressure. The smart contract sets an absolute upper and lower bound on the funding rate through parameterization; this band is wide enough under normal conditions to accommodate normal arbitrage space but acts as a circuit breaker when an extreme deviation occurs [20]. These boundary parameters can be configured differently according to the underlying asset's liquidity depth and historical volatility characteristics, and can be gradually loosened by the community as the asset matures. However, setting a rate cap embeds a mechanism-stability trade-off that cannot be ignored: the core function of the funding rate is to correct the basis between the perpetual futures and the spot price through a price signal, and when the rate hits its cap and is truncated, the price-correction mechanism fails, the perpetual futures may become persistently unanchored from the spot price, and this instead leads to larger basis accumulation and an eventual violent correction. The setting of the rate cap must therefore strike a balance between "preventing extreme rate pressure" and "maintaining the effectiveness of price anchoring." One possible alternative is to dynamically tighten the open-interest cap as the rate approaches its upper bound, relieving basis pressure from the demand side by restricting the size of new positions.

Parameterizing the size of the risk buffer pool bears directly on the protocol's ultimate solvency. The funding ratio of the insurance fund, the share drawn from liquidation penalties, and the critical value at which auto-deleveraging is triggered when the insurance fund is depleted are all key parameters for maintaining the system's credit. Linking these parameters to the protocol's total value locked or total open interest, and allowing them to be dynamically adjusted through governance, ensures that the protocol's capital adequacy remains within a safe range as it scales.

In practice, the parameterized settings of the insurance fund must confront a structural problem. In the liquidation mechanisms of both centralized exchanges and on-chain protocols, when the liquidation engine executes a forced liquidation, if insufficient market liquidity causes the actual closing price to be worse than the position's bankruptcy price, the resulting shortfall loss is borne by the insurance fund. However, when the cumulative rate of shortfall losses exceeds the rate at which the insurance fund is replenished, the protocol faces solvency risk. The parameterized settings of the insurance fund should therefore be conservative and cannot be computed based solely on the historical average loss rate. The calibration of the insurance fund's size should not rely solely on historical backtesting, because the history of the crypto market spans little more than a decade and its structure continues to change rapidly, so future maximum shortfall losses will almost certainly exceed the historical record. A more robust approach is to base the calibration on forward-looking stress testing, simulating extreme but plausible market scenarios (such as a major asset dropping 30% within 1 hour while market liquidity evaporates, a major stablecoin depegging and causing collateral values to plunge, or oracles failing simultaneously and causing liquidation delays) and computing the total shortfall loss under those scenarios. The risk metric should adopt a measure capable of capturing tail risk, such as conditional value at risk (CVaR), rather than relying solely on the historical backtest of extreme quantiles.

### 30.3.4 Parameterizing market-making obligations

In a decentralized derivatives market, the continuous supply of liquidity is the foundation for guarding against price manipulation and liquidation cascades. Centralized exchanges typically constrain the behavior of designated market makers through bilateral legal contracts, whereas in an on-chain environment market-making obligations must be converted into parameterized rules that a smart contract can verify and enforce.

Traditional securities and derivatives exchanges have mature institutional frameworks for market-making obligations. The Chicago Mercantile Exchange's (CME) market maker program requires a designated market maker to maintain two-sided quotes at least 85% of the time during a trading session, with a maximum bid-ask spread not exceeding a cap specified for the particular contract and a minimum quote size on each side that meets a specified number of contracts. The New York Stock Exchange's (NYSE) designated market maker (DMM) system imposes stricter continuous-quoting obligations on specific stocks while providing an obligation-waiver mechanism during periods of extreme volatility: when an underlying asset triggers a circuit breaker or the market enters a volatility-interruption state, market-making obligations are automatically suspended. These traditional frameworks use legal contracts and regulatory licenses as enforcement backstops, and the consequences of default include fines, suspension of eligibility, and even revocation of the market-making license. On-chain systems convert these obligations from legal contracts into parameterized rules in a smart contract; while this improves execution certainty, it also faces the engineering challenge of designing equivalent incentive and penalty mechanisms in an environment beyond legal jurisdiction.

Minimum depth and maximum spread constitute the core quantitative metrics of market-making obligations. A protocol sets, through the parameter registry, the amount of liquidity that must be maintained within a specific price range and the maximum spread permitted between bid and ask quotes. These parameters are not fixed but are set in tiers according to the market-capitalization size and trading activity of the underlying asset. For major assets, the parameter requirements are stricter, so as to provide execution quality comparable to that of a centralized exchange; for long-tail assets, the parameters are relatively lenient, so as to attract early liquidity providers. Market makers' rewards are tied directly to their attainment rate on these parameterized metrics, and the smart contract automatically computes and distributes rewards each epoch.

In a parameterized market-making-obligation framework, the parameters for minimum depth and maximum spread should be set in tiers according to the characteristics of the underlying asset. For major assets such as Bitcoin and Ethereum, the parameters can be set very strictly—for example, requiring market makers to maintain a bid-ask spread of no more than 3 to 5 basis points (bps) within a certain range around the midprice. The cost structure of on-chain market making differs markedly from that of a centralized exchange: each quote update requires submitting an on-chain transaction and paying a gas fee, and the information asymmetry caused by block latency further intensifies market makers' adverse-selection costs. These factors jointly constrain the range within which on-chain market-making-obligation parameters can be set, making it difficult to reach the sub-1-basis-point spread levels seen on centralized exchanges. For newly listed long-tail assets, the parameters can be relatively lenient in order to attract early liquidity providers. This tiered parameter setting embodies a core principle of on-chain finance: optimizing every participant's experience to the greatest extent without introducing systemic risk. Moreover, to prevent market makers from placing a burst of orders at the end of an evaluation epoch merely to satisfy the obligation requirement, the measurement of market-making obligations should adopt a time-weighted liquidity-presence rate rather than a simple attainment-rate assessment based on an epoch-end snapshot.

Parameterizing obligation-waiver conditions is the protective mechanism of the on-chain market-making scheme under extreme market conditions. When the market experiences violent turbulence, oracle-quote delays, or underlying network congestion, forcing market makers to maintain tight quotes could subject them to severe adverse-selection losses. The protocol introduces a parameterized trigger based on volatility or price deviation; when the market state exceeds the preset normal range, the smart contract automatically loosens the maximum-spread constraint or temporarily suspends the assessment of market-making obligations. This parameterized waiver mechanism protects the capital of liquidity providers while also avoiding the liquidity vacuum that would result from a collective withdrawal of quotes by market makers. However, an automated waiver mechanism faces two engineering-level challenges. The first is manipulation-resistant design: if the waiver trigger condition is based on instantaneous volatility, a market maker might strategically manufacture a volatility signal by submitting a large market order during a thin-liquidity period, thereby triggering the waiver to escape its market-making obligation. The waiver trigger should therefore use a time-weighted average volatility combined with cross-validation across multiple oracles. The second is the liveness guarantee: during extreme market conditions, on-chain infrastructure is most prone to congestion, yet this is precisely the moment when market makers most need the protection of a waiver, and the waiver-triggering transaction itself may fail to be confirmed on-chain in time due to gas competition. For this reason, the system should design a time-based automatic waiver as a fallback mechanism: if no quote-update transaction from a market maker is detected across several consecutive blocks, the system automatically treats the waiver state as in effect, without requiring the market maker to proactively submit a waiver request.

### 30.3.5 The governance mechanism for parameter adjustment

The effectiveness of parameterized compliance ultimately depends on the power structure that modifies the parameters. If parameters can be arbitrarily tampered with by a handful of insiders, all promises of transparency lose their meaning. Parameter adjustment must therefore be placed within a rigorous governance framework that balances immutability against flexible response.

Parameter adjustment in an on-chain protocol is subject to three tiers of governance constraint. The first tier is routine adjustment executed automatically by code—for example, a volatility metric computed from oracle price feeds automatically updating the margin multiplier without human intervention. The second tier is the governance review of structural parameter changes, which requires an on-chain proposal and community vote and is executed only after a timelock delay [16]. The third tier is an emergency multisig committee mechanism for extreme market crises, which permits rapid adjustment of key parameters within a strictly delimited scope [21]. The complete design and engineering implementation of these three tiers of governance constraint are developed systematically in Section 30.6.

## 30.4 Reporting-based compliance

Within the three-tier compliance spectrum, reporting-based compliance has the shallowest embedding but the broadest coverage. For requirements whose ex ante restriction is technically difficult to define precisely and whose forcible interception could impair the system's normal operation, reporting-based compliance exploits the immutability and global visibility of on-chain data, converting them into data-driven ex post monitoring and automated auditing that satisfy the regulatory demand for transparency without adding friction to transaction execution (the four core scenarios are discussed in Section 30.4.1).

### 30.4.1 When reporting-based compliance applies

As set out in the three-tier spectrum of Section 30.1.3, hard-coded compliance guards non-negotiable security baselines and parameterized compliance adjusts operational rules that must vary flexibly with market conditions; but not all regulatory requirements are suited to being implemented through ex ante restriction. In some scenarios, ex ante restriction is not only technically difficult to define precisely but could also seriously and adversely affect the system's normal operation and market efficiency. For such requirements, reporting-based compliance offers a superior engineering solution: converting compliance from a behavioral constraint into ex post monitoring and automated auditing based on on-chain data.

The core logic of reporting-based compliance is not to restrict participants' specific behaviors but to ensure the visibility, traceability, and analyzability of all behaviors. This mechanism is especially suited to four core scenarios. The first is transaction monitoring and anomaly detection. In complex financial markets, malicious behaviors such as wash trading, price manipulation, or insider trading are often difficult to intercept with a simple rule before a transaction occurs. Forcibly imposing ex ante interception is highly prone to false positives, thereby impeding legitimate market-making and arbitrage activity. The second is proof of reserves. Proving that a protocol holds enough assets to cover user liabilities is a system state that requires continuous verification, not a static metric controllable through a single parameter. The third is risk disclosure. Displaying the system's overall risk exposure and an individual account's distance to liquidation in real time to market participants falls within the category of information accessibility; its value lies in reducing information asymmetry rather than directly restricting trading. The fourth is regulatory reporting. Providing regulators with a complete data record of the system's operation is the basis for satisfying compliance-audit requirements.

In all four scenarios, reporting-based compliance fully exploits the underlying properties of blockchain technology. The immutability of on-chain data ensures the authenticity of historical records, while the global visibility of the data breaks down the data silos pervasive in traditional financial systems. By converting these four requirements into structured extraction and automated analysis of on-chain data, reporting-based compliance not only reduces the system's operating friction but also surpasses the traditional external-enforcement model in both the depth and breadth of compliance.

### 30.4.2 Transaction monitoring and anomaly detection

Transaction monitoring at a traditional centralized exchange depends heavily on internal data systems, and when regulators conduct an audit, they can obtain only the data snapshots or aggregate reports that the exchange selectively provides. This architecture entails systemic information asymmetry: the completeness and authenticity of the data depend entirely on the honesty of the centralized institution. By contrast, on-chain systems have an inherent architectural advantage in transaction monitoring. All order submissions, execution records, fund transfers, and liquidation events are permanently recorded on the distributed ledger in the form of cryptographic proofs. For a fully on-chain system, this nearly complete data coverage allows the transaction-monitoring system to reconstruct historical market states with high precision (for hybrid and app-chain architectures whose core state runs on the consensus layer or off-chain, the degree of coverage depends on the observability of that state).

On this foundation of high-precision data, the effectiveness of automated anomaly-detection models is significantly enhanced. In an on-chain environment, every transaction is bound to a specific cryptographic address, and the flow path of funds is fully transparent. By applying machine-learning algorithms and graph-network analysis, a monitoring system can automatically identify complex market-manipulation patterns. For example, if the same address or a cluster of related addresses repeatedly trades on both the buy and sell sides within a very short time, the system can quickly flag it as potential wash trading; or if a specific address builds a large leveraged position that sharply departs from its historical behavior just before a major protocol upgrade or governance proposal is announced, this pattern can be captured in real time and flagged as suspected insider trading [22]. This automated detection mechanism does not introduce additional latency into the consensus path of transaction execution but is completed asynchronously by independent monitoring nodes after the data is committed to the chain. However, the precision of on-chain anomaly detection still faces inherent technical bottlenecks. In an order-book environment, the legitimate two-sided quoting activity of a market maker and wash trading are highly similar in their on-chain data form, since both manifest as frequent trading by the same entity on both the buy and sell sides. Moreover, wash traders can evade correlation analysis by creating a large number of mutually unrelated addresses, and this Sybil attack subjects detection methods based on address clustering to a fundamental accuracy constraint. On-chain transparency provides a complete data foundation, but a significant analytical gap remains between the data and a reliable determination of a violation.

More importantly, the openness of on-chain data gives rise to an entirely new compliance paradigm: crowdsourced compliance. Under the traditional framework, transaction monitoring is the exclusive prerogative of regulators or an exchange's internal compliance department. In an on-chain system, anyone—independent researchers, competitors, data-analytics firms, and even ordinary users—can obtain the complete transaction dataset and run their own monitoring algorithms. This distributed oversight significantly raises the probability that malicious behavior will be discovered. When compliance is no longer the exclusive responsibility of a single centralized entity but evolves into a public activity in which the entire community participates, the system's overall resistance to malfeasance is markedly strengthened. However, the effectiveness of crowdsourced monitoring is constrained by the free-rider problem: when everyone can monitor, each individual lacks the economic incentive to bear the cost of monitoring, and the result may be that no one performs systematic in-depth analysis. To turn crowdsourced compliance from a theoretical advantage into a practical effect, complementary economic-incentive mechanisms must be designed, such as a bounty pool for effective reports and a requirement that reporters stake a bond to deter malicious false reports.

### 30.4.3 Automating proof of reserves

In the development history of centralized cryptocurrency exchanges, the evolution of proof-of-reserves mechanisms deeply reflects the transformation of trust architecture. Early centralized exchanges relied entirely on reputational endorsement, until a series of severe incidents of customer-asset misappropriation led the industry to widely adopt Merkle-tree-based proof of reserves. However, this proof of reserves, voluntarily initiated by a centralized institution, has significant limitations. It can typically prove only that, at a specific time snapshot, the known on-chain addresses controlled by the exchange contained a specific amount of assets; it cannot prove that these assets were not misappropriated at points outside the snapshot, still less fully rule out the possibility that the exchange has hidden liabilities [23]. In essence, a centralized exchange's proof of reserves is a discrete audit activity rather than an intrinsic property of the system architecture.

On-chain financial systems restructure the implementation logic of proof of reserves through the self-custody property of smart contracts. In a fully on-chain architecture, users' asset balances and the protocol's total reserves are all publicly queryable global state variables. Anyone can independently compute the system's total liabilities and total assets at any moment and verify whether the latter is greater than or equal to the former—without relying on a report from a third-party auditor and without waiting for the exchange to release a quarterly snapshot. The marginal cost of this verification process approaches zero and is not controlled by any centralized entity.

Centralized exchanges are themselves drawing on on-chain technology to improve their proof-of-reserves mechanisms. In November 2022, Binance launched a Merkle-tree-based proof of reserves, and in February 2023 it introduced zk-SNARKs to strengthen it, forming a hybrid scheme combining Merkle trees and zk-SNARKs. Users can verify the path of their own leaf node within the Merkle tree to confirm that their assets are included in the total-reserve calculation, while the zero-knowledge proof is used to prove that all user balances are non-negative and that their sum matches the on-chain address balances. OKX (using zk-STARKs) has also launched a zero-knowledge-proof-based scheme, while Bybit and others provide verifiable-reserve schemes based on Merkle trees and third-party audits. This trend indicates that the technical standards for reserve transparency established by on-chain systems are being fed back to centralized institutions, pushing up the compliance baseline of the entire industry. However, CEXs' zk-PoR schemes still rely on the exchange to proactively initiate the proof and cannot cover hidden liabilities; their architectural-level limitations differ fundamentally from the continuous guarantee of an on-chain system.

Thus, an on-chain system's proof of reserves achieves a leap from a one-time audit to a continuous guarantee. The data itself is a continuous, immutable record, and the proof process is embedded automatically into the logic of reading the data. As long as the consensus mechanism of the underlying blockchain is not compromised, the reserve data recorded in the smart contract possesses a high degree of certainty. This architectural-level guarantee substantially compresses the room a centralized institution has to falsify balance-sheet data, making reserve transparency an inherent, default property of the system.

The description of proof of reserves above applies mainly to spot-custody protocols, whose liability calculation is relatively simple—that is, total assets need only be no less than total deposits. For derivatives protocols such as perpetual futures, however, the engineering implementation of proof of reserves is far more complex. The "total liabilities" of a derivatives protocol include not only users' margin balances but also the unrealized profit and loss (P&L) of all active positions, the funding rate pending settlement, and the shortfall losses already borne by the insurance fund. Because unrealized P&L changes in real time with the mark price, precise liability calculation requires traversing all active positions at each point in time and revaluing them at the current mark price. This means that a derivatives protocol's proof of reserves is not a simple state query but a computation-intensive process involving global state traversal and real-time revaluation, whose engineering complexity and computational overhead should not be underestimated.

### 30.4.4 Real-time risk disclosure

Risk disclosure is one of the core requirements of consumer protection. On traditional derivatives-trading platforms, risk disclosure often takes the form of an after-the-fact static report or a disclaimer at account opening. A trader holding complex positions finds it difficult to intuitively assess their real-time risk exposure, especially when violent market swings cause margin requirements to change dynamically. The reporting-based compliance mechanism of an on-chain system builds a dynamic risk-reporting system by converting underlying state data into a real-time, trader-facing view.

This real-time risk disclosure spans several key dimensions. The system can precisely compute and display a trader's current margin ratio and the specific price distance to the trigger of a forced liquidation. If the underlying asset's price moves adversely by a specific magnitude, the trader can precisely compute the percentage distance from their current position to the liquidation-trigger price. In addition, the system can display in real time the current balance of the insurance fund and its ratio to total open interest, allowing traders to assess the system's capacity to absorb shortfall losses under extreme market conditions [19]. Under an auto-deleveraging mechanism, a trader can even view their position in the deleveraging queue in real time, forming a prior judgment about the potential risk of passive closure.

Providing this high-granularity real-time data essentially surpasses the passive compliance traditionally undertaken merely to satisfy regulatory inspection. It constitutes a mechanism of responsible information provision to traders and directly improves the system's transparency and user experience. By converting the complex state hidden deep within the matching engine and liquidation logic into intuitive risk metrics, on-chain systems achieve a structural improvement over centralized exchanges on the key dimension of information accessibility, enabling traders to manage risk on a fully informed basis.

### 30.4.5 The regulatory interface

In the traditional financial compliance model, persistent gaming and friction exist between regulators and regulated entities. Regulators must periodically dispatch auditors into an institution or require the institution to submit cumbersome compliance reports in a specific format. This model not only incurs substantial compliance costs but also suffers from severe time lag, so that regulators often discover the first signs of a problem only through ex post review after a systemic risk has already erupted.

On-chain systems offer an entirely new technical path to resolve this predicament: designing a standardized regulatory interface for regulators. Its core idea is that, rather than having regulators laboriously inspect the system, the system should proactively and in real time report its operating status to regulators. By exposing a specific application programming interface (API), regulators can at any time pull key metrics such as the system's total open interest, the distribution of the liquidation queue, the adequacy of the insurance fund, and the margin coverage ratio for specific assets. This mechanism eliminates information asymmetry, because the data regulators read through the interface is fully homologous with, and synchronized to, the system's actual operating state.

Figure 30-4 presents the end-to-end technical pipeline of reporting-based compliance, from data collection and automated auditing through to outputs for three audiences—traders, the public, and regulators—driven entirely by code, eliminating the reliance on manual data organization and report preparation found in traditional compliance workflows.

![Figure 30-4](./images/fig-30-4-en.png)

**Figure 30-4.** The three-stage pipeline of reporting-based compliance, from data collection and automated auditing to outputs for traders, the public, and regulators [3][22]

This interface-based automated reporting mechanism brings multiple significant benefits. It significantly reduces a protocol's operational compliance costs, because report generation is driven entirely by code and requires no human intervention. At the same time, regulators gain real-time insight synchronized with the system's state, enabling them to issue early warnings during the risk-accumulation stage rather than merely assigning blame after the fact. To be sure, the broad application of this mechanism still faces engineering challenges, particularly because regulators in different jurisdictions require different data formats and granularity, which calls for the industry to jointly promote the standardization of regulatory data interfaces. A further key direction for reporting-based compliance is to protect ordinary traders' privacy through cryptographic techniques such as zero-knowledge proofs while still giving regulators adequate transparency.

The effectiveness of reporting-based compliance depends on the global visibility of on-chain data, but this visibility conflicts structurally with user privacy: the contradiction between regulators' demand for penetrating visibility into traders' identities and the sources of their funds, and traders' basic need for financial privacy, cannot be resolved through a simple trade-off but requires a cryptographic-level technical reconciliation, which the next section addresses specifically.

## 30.5 The technical reconciliation of privacy and compliance

Embedding compliance rules into an on-chain system confronts a core tension: regulators demand full penetrating visibility into participants' identities and fund flows, whereas the global visibility of a public blockchain means that any identity linkage would expose a user's entire transaction history. Under the traditional framework, this contradiction between privacy protection and compliance requirements can be handled only by choosing one over the other. The maturation of zero-knowledge-proof technology offers an engineering path to reconcile this contradiction, enabling a trader to prove to the system that they satisfy specific compliance conditions without exposing the underlying identity data.

### 30.5.1 The structural conflict between compliance and privacy

The cornerstone of the traditional financial-regulatory system is complete knowledge of participants' identities, whereas the native design of crypto-asset markets is built on decentralization and pseudonymity. This architectural difference produces a structural conflict between know-your-customer (KYC) requirements and traders' demand for privacy protection. The logical starting point for regulators is information transparency—collecting, storing, and monitoring traders' personal identity information and fund flows in order to guard against illicit activities such as money laundering, terrorist financing, and sanctions evasion. Within this framework, any technology or mechanism that impedes information penetration is regarded as a potential compliance risk, and anonymous transactions therefore become the primary target of regulatory intervention.

However, directly implementing the traditional information-collection model on the transparent ledger of a public blockchain would bring severe privacy-leakage risk. The global visibility of a public blockchain means that once a user's real identity is bound to an on-chain address, all of their historical transactions, asset balances, interacted protocols, and even fund-flow patterns become public to everyone. This mandatory transparency not only exposes a trader's commercial secrets and trading strategies but also subjects them to targeted cyberattacks, phishing scams, and even threats to real-world personal safety. When traders use tools such as mixers, privacy coins, or multiple addresses to sever the link between their identity and their on-chain activity, this is not necessarily for illicit purposes but rather to rebuild basic financial privacy on a transparent ledger.

This opposition between compliance and privacy is especially evident in current regulatory policy. The EU's Markets in Crypto-Assets (MiCA) regulation requires crypto-asset service providers to be able to identify the holders and transaction histories of assets with built-in anonymization features; otherwise, the platform must block trading in such assets [24]. Similarly, the sanctions imposed on Tornado Cash by the U.S. Treasury's Office of Foreign Assets Control (OFAC) reflect regulators' tendency to equate anonymity directly with an illicit financial instrument [25]. However, the legal basis for this position has been challenged in court. In November 2024, the U.S. Court of Appeals for the Fifth Circuit ruled in Van Loon v. Department of the Treasury that OFAC's sanctions on Tornado Cash's immutable smart contracts exceeded its statutory authority, on the grounds that immutable smart contracts do not constitute "property" under the International Emergency Economic Powers Act (IEEPA). This ruling provides an important precedent for the legal positioning of embedded compliance—namely, that immutable on-chain compliance logic may not be subject to the same sanctions-review framework as mutable systems—but it also raises a new question of how "immutability" should be defined under an upgradeable proxy-contract architecture. This either-or dichotomy confronts on-chain finance with a dilemma: either abandon privacy entirely to satisfy compliance requirements, reducing the public blockchain to a high-risk transparent database; or refuse compliance to protect privacy, thereby marginalizing itself from the mainstream financial system.

### 30.5.2 Compliance applications of zero-knowledge proofs

The evolution of cryptographic technology, and in particular the maturation of the zero-knowledge proof, provides an engineering solution to reconcile the contradiction between compliance and privacy. A zero-knowledge proof allows a prover to convince a verifier of the truth of a statement without revealing any additional information beyond the fact that the statement is true. In the compliance scenarios of on-chain finance, this property achieves a paradigm shift from "information disclosure" to "fact verification": a trader can prove to a smart contract or a regulatory node that they satisfy specific compliance conditions without submitting any underlying identity data or transaction details.

This "prove-without-revealing" mechanism significantly changes the logic of processing compliance information. Take anti-money-laundering review: the traditional model requires a user to submit a passport, proof of address, and records of the source of funds, which the platform manually reviews and stores as sensitive data. Under a zero-knowledge-proof-based framework, the user need only generate a cryptographic proof locally attesting that "I am not a citizen of a sanctioned country" or "the source of my funds does not include any flagged high-risk address." Acting as the verifier, the smart contract need only confirm the validity of the proof through mathematical computation to admit the transaction, and the entire process involves no on-chain transfer or storage of any specific nationality or historical transaction record.

A study based on Monte Carlo simulation (Decker, 2025, an SSRN preprint that has not been peer-reviewed) estimates that a zero-knowledge-proof-based KYC verification framework can reduce the volume of exposed user data by approximately 97% and, when combined with an artificial intelligence (AI) model, can achieve approximately 96.7% anomaly-detection accuracy within its stipulated simulation scenario [26]. These figures, however, come from a single simulation study that has not been independently replicated; moreover, zero-knowledge proofs themselves constrain the scope of data exposure rather than directly improving detection accuracy (the latter depends on the AI model with which they are combined). This technology offers not only significant advantages in privacy protection but also eliminates, at the system-security level, the single-point-of-failure risk of a centralized institution acting as a data honeypot. Because compliance verification is converted into pure mathematical computation, an on-chain financial system can build compliance requirements into its architecture without bearing the legal and security responsibility of safeguarding vast amounts of sensitive personal information. This is a core dimension on which on-chain finance surpasses the traditional financial system in the design of compliance mechanisms.

The applicable boundary of zero-knowledge-proof compliance solutions must be honestly delimited. At the current stage, the compliance obligations that zero-knowledge proofs can effectively satisfy are concentrated mainly in the onboarding stage, including sanctions-list screening, accredited-investor verification, and basic anti-money-laundering risk rating. However, the full set of anti-money-laundering and counter-terrorist-financing (CTF) compliance obligations extends far beyond onboarding review. The Financial Action Task Force's (FATF) "Travel Rule" requires that the identity information of both the sender and the receiver be transmitted in virtual-asset transfers, which conflicts structurally with the core logic of zero-knowledge proofs, "proof without exposure." The obligation of continuous transaction monitoring requires the compliance-obligated party to be able to access underlying transaction data in order to identify suspicious patterns, and the obligation to proactively file suspicious transaction reports further requires disclosing the detailed information of specific transactions to regulators. Under the current technical framework, these obligations cannot yet be satisfied by a pure zero-knowledge-proof solution. Acknowledging this boundary does not weaken the value of zero-knowledge proofs but delineates a realistic scope for their engineering application, avoiding the erosion of regulatory trust that overpromising would cause.

Figure 30-5 presents the complete workflow of this "prove-without-revealing" mechanism in an on-chain system: off-chain, a trusted KYC provider verifies identity and issues a cryptographic credential containing only specific attribute claims; the user then generates a zero-knowledge proof locally on that basis; and the on-chain smart contract admits the transaction once it confirms the proof's validity through mathematical computation alone—the entire process involving no on-chain transmission or storage of any identity information.

![Figure 30-5](./images/fig-30-5-en.png)

**Figure 30-5.** The workflow of zero-knowledge-proof-based compliance credentials [26] (the 97% and 96.7% figures shown are single-simulation estimates from Decker 2025 and are not peer-reviewed)

### 30.5.3 Designing compliance credentials

To turn the theoretical advantages of zero-knowledge proofs into an executable engineering scheme, a system must introduce a modular "compliance credential" design. This design follows the principle of minimal necessary information, deconstructing complex identity attributes into independent, separately verifiable claims and thereby avoiding the "all-or-nothing" data-bundled submission of traditional identity verification. The lifecycle of a compliance credential spans three key stages—issuance, verification, and revocation—which together constitute a closed-loop on-chain identity-management system.

In the issuance stage, a trusted off-chain entity (such as a licensed KYC provider or a government agency) is responsible for verifying the user's real identity. Once verification is complete, this entity does not put the user's identity information on-chain but instead issues a cryptographic credential containing specific attribute claims and digitally signs it with its private key. These credentials are typically stored in the user's local wallet, under the user's full control. For example, a credential might contain only the claim that "this user has passed a level-one anti-money-laundering review" or "this user is an accredited investor," without any redundant information such as name or ID number.

In the verification stage, when a user attempts to interact with a compliance-constrained smart contract, the contract states a specific attribute requirement. The user uses the locally stored credential to generate a zero-knowledge proof attesting that they hold a valid credential, issued by a trusted issuer, that satisfies the contract's requirement. The smart contract verifies the mathematical correctness of the proof and the validity of the issuer's signature, and if both pass, it automatically authorizes the transaction to execute. The entire verification process is completed on-chain, achieving a decentralized and automated compliance check.

The revocation mechanism is an indispensable security baseline in compliance-credential design. When a user's compliance status changes (such as being placed on a sanctions list or the credential expiring), the issuer must be able to invalidate the already-issued credential. This is typically implemented by maintaining an on-chain revocation registry or accumulator. When generating a zero-knowledge proof, the user must prove not only that the credential is valid but also, simultaneously, that it is not included in the latest revocation list. This design ensures the capacity to update compliance status dynamically while maintaining the decentralized nature of the verification process.

### 30.5.4 Engineering challenges and progress

Although zero-knowledge proofs perfectly reconcile the contradiction between privacy and compliance in theory, their practical engineering deployment still faces significant technical and economic challenges. The foremost bottleneck lies in computational overhead and proof-generation time. Generating a zero-knowledge proof is a highly computation-intensive process, and for a circuit containing complex compliance logic, generating a proof on a mobile device or an ordinary personal computer may take seconds or even minutes. This latency is unacceptable in trading scenarios that demand high-frequency, low-latency execution. In addition, although verifying a proof is relatively lightweight, executing the verification logic on a mainnet such as Ethereum still consumes considerable computational resources, thereby pushing up users' transaction costs.

The complexity of circuit design constitutes another engineering obstacle. Converting complex laws, regulations, and compliance requirements into mathematical constraints in a zero-knowledge-proof circuit requires spanning the two distinct professional domains of law and cryptography. Any logical flaw in the circuit could allow the compliance mechanism to be bypassed, and such a bypass is extremely difficult to discover after the fact because of the zero-knowledge property. The development, auditing, and formal verification of compliance circuits are therefore costly, which limits their rapid iteration and broad deployment.

Despite the many challenges, industry exploration in privacy-preserving compliance has made substantial progress. Polygon ID, the first identity solution to allow users to generate zero-knowledge proofs from off-chain credentials, has built a complete verifiable-credential ecosystem that enables decentralized applications to implement access control without collecting user data [27]. Meanwhile, fully decentralized zkKYC solutions launched by projects such as zkMe further minimize the trust assumptions of identity verification, ensuring the censorship-resistance and privacy of the credential-issuance process through a decentralized oracle network and multi-party computation [28]. These engineering practices indicate that zero-knowledge-proof-based embedded compliance is moving from the proof-of-concept stage toward large-scale application, laying the technical foundation for building the next generation of on-chain financial infrastructure that both satisfies regulatory requirements and defends user privacy.

## 30.6 Engineering the governance layer

When compliance rules are embedded into smart contracts in a hard-coded or parameterized form, the system gains a sense of immutable security but simultaneously loses the flexibility to respond to unknown risks and adapt to regulatory change. If the design stage fails to provide a secure upgrade channel for these rules, the system will lose its usability in a rapidly evolving market environment because of excessive rigidity. This predicament raises the core question of this section: how can a governance mechanism be designed within an architecture that pursues trustlessness so as to guarantee both immutability and secure upgradeability?

### 30.6.1 Immutability versus the need to upgrade

The core value proposition of a smart contract is immutability—once code is deployed, its execution logic is free from interference by any centralized entity. In on-chain financial systems, this property is the cornerstone of building user trust, because it eliminates the risk that an operator could misappropriate assets or unilaterally modify liquidation rules. However, a fully immutable system has proven fragile in engineering practice. The complexity of financial markets, the potential code vulnerabilities of smart contracts, and continuously evolving regulatory requirements jointly constitute a rigid demand for system upgradeability [29].

This contradiction is especially pronounced in the process of embedding compliance rules. Although hard-coded compliance (such as the absolute leverage cap and asset-segregation logic) provides the highest level of certainty, once a logical flaw is discovered or an extreme market condition arises, these protective measures may, absent an upgrade mechanism, instead become the trigger for the system's collapse. For example, when the operating environment of the underlying blockchain changes, or when regulators adjust the compliance standards for specific assets, a fully immutable contract would force the entire system to undergo a destructive hard fork or asset migration [29].

The engineering design of the governance layer is therefore essentially a precise calibration of the distribution of power. Granting an administrator key unrestricted upgrade authority means reverting to the trust model of a traditional centralized exchange; completely abandoning the capacity to upgrade places the system in an unrepairable and dangerous position. In the blueprint of a trustless architecture, the governance layer (Layer 5) must serve as the connective layer between static code and dynamic reality. This requires converting governance itself into a verifiable on-chain process, so that every rule modification or parameter adjustment is strictly constrained by cryptographic and game-theoretic mechanisms.

### 30.6.2 The dual architecture of timelock and emergency powers

To balance immutability against flexible response, on-chain governance has, in engineering practice, formed a dual architecture: a routine governance path controlled by a timelock, and an emergency-powers path held by a multisignature (multisig) committee. This design acknowledges the fundamental difference in time sensitivity between routine operational upgrades and extreme-risk response, and configures different security safeguards for each [30].

Figure 30-6 contrasts the operating logic of the dual governance architecture: the routine path is executed after a community vote and a timelock delay, providing a window for public review and allowing dissenting users to withdraw their funds and exit; the emergency path allows a multisig committee to bypass the timelock and immediately execute defensive operations, while triggering mandatory ex post public disclosure. The figure systematically compares the trigger conditions, authority boundaries, and accountability mechanisms of the two paths.

![Figure 30-6](./images/fig-30-6-en.png)

**Figure 30-6.** The dual governance architecture of timelock and emergency powers [30][31]

The routine governance path applies to parameter adjustments, new-feature deployments, and non-urgent code upgrades. On this path, the timelock mechanism plays the core defensive role. After a governance proposal passes, its execution code does not take effect immediately but is placed within a mandatory waiting period (typically around 48 hours—Compound, for instance, uses 48 hours, and some protocols use longer). This delay serves a dual purpose: on the one hand, it provides the community a window to review the code about to be executed, ensuring that the proposal's content is consistent with the actual execution logic; on the other hand, if some users disagree with the change, the timelock gives them ample time to withdraw their funds and exit the system [31]. During the timelock period, if malicious code or a serious vulnerability is discovered in the proposal, the community can cancel the execution through a preset veto mechanism.

The emergency-powers path is dedicated to scenarios requiring immediate intervention, such as a zero-day-vulnerability attack, a serious oracle failure, or an extreme market crash. In such cases, a 48-hour delay could allow the system's funds to be completely drained. The architecture therefore typically sets up an emergency committee controlled by a multisig, which is granted the power, under specific conditions, to bypass the timelock and immediately execute defensive operations such as pausing the system or triggering a parameter circuit breaker [32].

However, the existence of emergency powers inevitably introduces centralization risk. To limit the abuse of this power, the engineering design must impose strict constraints. The scope of the emergency committee's authority is typically hard-coded and limited to defensive operations (such as being able only to pause withdrawals, not to transfer funds). More importantly, any exercise of emergency power must trigger an ex post public-disclosure and retrospective-audit procedure. If the community determines in an ex post review that the emergency operation was improper, it can replace committee members or restore the system state through the routine governance path. This mechanism of "ex ante authorization, ex post accountability" constitutes the key to safeguarding the trust baseline within the dual architecture.

In a multi-protocol composable on-chain financial ecosystem, the emergency-pause mechanism also faces a risk dimension that transcends the boundary of a single protocol: cross-protocol spillover effects. When one protocol pauses its liquidation function, other protocols that depend on its price signal may experience an oracle-data interruption; when one protocol pauses withdrawals, other protocols that use its assets as collateral may trigger a cascade of liquidations because the collateral is frozen. To minimize this spillover, the engineering design of the emergency pause should adopt a tiered strategy, imposing differentiated restrictions by functional module rather than a global shutdown. For example, when facing an attack, one can pause only new position openings while retaining closing and withdrawal functions; when an oracle fails, one can freeze only the specific trading pairs that depend on that oracle rather than the entire system. This granular control of tiered pausing is a key design element for the emergency-powers architecture to remain effective in a composable ecosystem.

### 30.6.3 The proxy contract pattern and governance constraints

"Hard-coding" requires that rules cannot be violated, while "upgradeability" requires that rules can adapt to change. These two seemingly contradictory demands are reconciled in modern smart-contract engineering through the proxy contract pattern. The proxy pattern separates the system's state (such as a user's margin balance) and its business logic (such as the specific compliance rules) into two independent contracts [33].

Users always interact with the proxy contract, which forwards all function calls to the implementation contract through the underlying delegatecall instruction. The implementation contract contains all the hard-coded rules and business logic. In day-to-day operation, the address of the implementation contract is fixed in a storage slot of the proxy contract, and at this point all rules exhibit complete rigidity, with no one able to circumvent or violate these hard-coded constraints.

When a hard-coded rule genuinely needs to be updated, the system can rewrite the implementation-contract address pointer stored in the proxy contract, redirecting it to a brand-new implementation contract that contains the new rules (Figure 30-7). All user interactions always point to the proxy contract, whose address never changes, and the proxy forwards the calls to the current implementation contract through delegatecall; an upgrade requires only modifying this implementation-address pointer to replace the entire business logic without migrating user assets and state data.

![Figure 30-7](./images/fig-30-7-en.png)

**Figure 30-7.** The upgradeable hard-coded architecture of the proxy contract pattern [33]

To prevent the abuse of upgrade authority from undermining the trust foundation of hard-coding, the upgrade process must be strictly controlled by the governance layer—which is precisely the core application scenario of the timelock and emergency-powers dual architecture discussed in the previous section: after an upgrade proposal is approved, it can take effect only after the mandatory timelock delay, multisig authorization, and veto procedures described in that section, whose mechanism details are not repeated here. Through this combination of the proxy pattern and governance constraints, an on-chain system achieves a balance between the rigidity of day-to-day operations and the flexibility of long-term evolution. Rules are hard-coded and inviolable at every specific moment, but over an extended time dimension the system possesses the ability to iterate and evolve through a rigorous consensus procedure. The proxy contract pattern gives the term "hard-coding" two levels of meaning in this chapter. The first is "absolute hard-coding": constraints written into the proxy contract's own logic that cannot be modified through any upgrade mechanism, such as the fundamental permission structure for moving assets. The second is "version-level hard-coding": constraints that cannot be violated within the current implementation-contract version but can be modified by replacing the implementation contract with a new one through a governance upgrade. The "hard-coded compliance" discussed in the three-tier compliance spectrum in fact covers both levels, and when assessing the strength of a specific protocol's compliance guarantee, one must distinguish which level its key rules belong to.

### 30.6.4 Governance attacks and defenses

As governance tokens have been widely adopted in DeFi, the governance layer itself has become a new vector for attackers to gain control of a system and plunder funds. Unlike a technical attack that exploits a code vulnerability, a governance attack fully follows the rules the system sets, passing a malicious proposal through legitimately acquired voting power. Understanding these distinctive threat models is a prerequisite for designing effective defense mechanisms.

Figure 30-8 organizes the main governance attack vectors (flash-loan voting, whale manipulation, and collusive vote-buying) and their corresponding three-tier escalating security barriers: architectural defense (snapshot voting and timelock), mechanism defense (quadratic voting), and economic defense (governance insurance).

![Figure 30-8](./images/fig-30-8-en.png)

**Figure 30-8.** The threat model of governance attacks and the multi-layer defense system [34][35]

The flash-loan voting attack is a high-severity threat currently facing the governance layer. An attacker uses an uncollateralized flash loan provided by a lending protocol to borrow a huge quantity of governance tokens within a single block, instantly gaining overwhelming voting power, passing and executing a malicious proposal (such as transferring treasury funds to the attacker's address), and then repaying the loan within the same block (the April 2022 Beanstalk incident used exactly this technique to drain approximately $182 million) [34]. This attack exploits the blind spot of traditional voting mechanisms along the time dimension.

Against flash-loan attacks, the first-tier architectural defense typically adopts a combination of snapshot voting and a timelock. The snapshot mechanism requires the system to record the token balances of all addresses in the block immediately preceding the proposal's creation, and to use these as the basis for voting weight. Because a flash loan must be borrowed and repaid within the same block, the snapshot mechanism prevents an attacker from using flash-loan funds to influence the voting weight of a historical block. A snapshot neutralizes only the single-block flash-loan variant; attacks that borrow across multiple blocks, or that purchase tokens on the spot market before voting, remain feasible—which is precisely why the timelock and veto power must serve as the actual backstop. In addition, the timelock mechanism breaks the synchrony between voting and execution, so that even if an attacker manages to pass a malicious proposal, they must wait until the delay period ends before it can be executed; this not only increases the attack's capital cost but also provides defenders a window to intervene [35].

Whale manipulation and collusive vote-buying constitute another kind of long-term governance threat. When a few entities hold a token share sufficient to determine a proposal's outcome, the system's decision process degrades into oligarchic decision-making. To mitigate this problem, quadratic voting has been introduced as a mechanism defense. Quadratic voting was first proposed by Lalley and Weyl [36]: the square of the number of votes a participant allocates to an option equals the voting credits or token cost they expend [37][38]. This nonlinear cost function significantly increases the marginal cost of accumulating votes, making it difficult for a few whales to easily overwhelm the combined will of numerous retail participants, thereby restoring a degree of balance to governance. However, the theoretical effect of quadratic voting is severely constrained in practice by the voter-participation rate. Voter turnout in mainstream DAO governance is typically below 10%, and in a low-participation environment a whale can still dominate the voting outcome with a relatively small outlay even in the face of nonlinear voting costs. In addition, the on-chain effectiveness of quadratic voting also depends on a Sybil-resistant unique-identity layer: absent identity verification, a whale can split its holdings across a large number of addresses to circumvent the quadratic cost, which is also why purely token-weighted quadratic voting is rarely used for high-value DeFi treasury decisions. Quadratic voting therefore needs to be deployed together with a Sybil-resistant identity layer and complementary mechanisms that raise participation (such as delegated voting and voting incentives) in order to truly fulfill its design intent.

Beyond architectural defense and mechanism defense, economic defense (such as governance insurance) constitutes the last line of defense. When an attacker successfully bypasses the first two layers of defense and causes losses, a preset insurance fund can be used to compensate the affected users, preventing a total collapse of trust in the system. These three layers of defense together constitute a multi-layer defense system that significantly raises the difficulty and cost of launching a governance attack.

### 30.6.5 The governance roadmap of progressive decentralization

Over the lifecycle of an on-chain financial system, the governance architecture is not fixed. A significant tension exists between the system's fragility in its early days after launch and the trustlessness it pursues in the long run. If control is handed over to the community prematurely—before the code has been sufficiently battle-tested in live trading and before the economic model has reached equilibrium—the system will face high security risk and coordination failure. To address this path problem, engineering practice has developed the concept of "progressive decentralization" [39]. Synthesizing Walden's idea with industry engineering practice, this book summarizes the handover of governance power as a structured, multi-stage transformation process (the specific three-stage division of "team control—multisig committee—full DAO" and the timelock mechanism below are this book's engineering synthesis, not the framework of Walden's original text).

Figure 30-9 presents the three-stage structure of the progressive handover of power—the team-control period, the multisig-committee period, and the full-community-governance period—in order of increasing decentralization, which the following text develops stage by stage in terms of its authority boundaries and transition conditions.

![Figure 30-9](./images/fig-30-9-en.png)

**Figure 30-9.** The three-stage roadmap of progressive decentralization [39][40] (conceptual illustration; stage durations have no standard)

The first stage is the team-control period, typically covering the initial phase after the system's launch (the specific duration depends on the project, commonly ranging from a few months to about a year, with no uniform standard). In this stage, the core development team retains unilateral control over smart-contract upgrades and key parameter adjustments. This highly concentrated power structure is intended to maximize the system's iteration speed and its ability to respond to sudden events. When the system faces an unknown vulnerability or an economic attack, the team can immediately deploy a patch without going through a lengthy community discussion and voting process. The core goal of this stage is to validate the stability of the system architecture and product-market fit, rather than to pursue formal decentralization. However, to provide users with a basic trust guarantee, the team typically publicly commits to the boundaries of its power and periodically releases security-audit reports.

As the system scales and its operating logic stabilizes, the governance architecture enters the second stage, the multisig-committee period. In this stage, the team begins to proactively reduce its own unilateral control. The administrator keys are transferred to a multisig committee jointly composed of core team members, early investors, well-known security experts, and community representatives. Any operation involving a system upgrade or parameter modification must obtain the signature authorization of a majority of committee members and is mandatorily executed only after a timelock delay [40]. This mechanism not only eliminates the risk of a single point of failure but also provides a time window for community oversight. At the same time, the community begins to be granted the right to propose and vote on non-critical parameters, as a rehearsal for fully taking over governance in the future.

When the system reaches high maturity, its token distribution is sufficiently dispersed, and its core functions have solidified, the governance architecture finally transitions to the third stage, the full-community-governance period. In this end state, the privileges of the multisig committee are completely revoked, and all upgrade authority and parameter-adjustment rights are transferred to a DAO controlled by token holders. Any modification of the smart contracts must strictly follow the standardized process of on-chain proposal, voting, and timelock execution. At this point, the core team steps back to become one of many protocol contributors, no longer enjoying special privileges. This progressive handover of power ensures that the system remains structurally sound throughout its evolution from a "trusted operator" to a "trustless protocol."

However, the theoretical elegance of progressive decentralization faces a serious credible-commitment problem in practice. It is easy for a core team to promise, in the early days after launch, that it will relinquish control in the future; but when decentralization means actually giving up the economic privileges of adjusting fees, managing the treasury, and steering the protocol's direction, the team faces a strong time-inconsistency incentive to extend the first or second stage indefinitely. In reality, a large number of blockchain projects have never completed the handover of power under the banner of "progressive decentralization," and the progressive-decentralization roadmap degenerates into a rhetorical tool for perpetuating centralized control. To resolve this commitment problem, the engineering design can introduce irreversible decentralization milestones—for example, presetting in the smart contract a logic that automatically reduces authority based on a time or system-scale threshold, so that once the system's total value locked exceeds a specific threshold or its operating time exceeds a predetermined term, the administrator authority is automatically downgraded, and this downgrade logic itself cannot be overridden by the upgrade authority.

### 30.6.6 A governance audit of Hyperliquid

Before assessing the governance state of an on-chain system, it is worth contrasting it with the governance structure of a centralized exchange. The governance power of a traditional CEX is concentrated in the corporate board and the internal compliance committee; parameter adjustments (such as changes to margin ratios and listing decisions) are executed unilaterally by management, and users have neither voting rights nor prior knowledge. The external constraints on a CEX come mainly from the conditions of its regulatory license and legal accountability, not from architectural-level checks on power. By contrast, on-chain governance grants stakeholders direct participation through token voting, the timelock mechanism ensures the transparency and predictability of changes, and the multisig structure eliminates single-point decision risk. This governance-paradigm difference from "institutional self-discipline" to "architectural constraint" constitutes the basic frame of reference for assessing the governance maturity of an on-chain system such as Hyperliquid.

Applying the governance theoretical framework above to Hyperliquid, a specific on-chain derivatives-trading infrastructure, allows a clear assessment of the gap between its current governance state and the ideal decentralization goal. As a system built on the customized app-chain HyperEVM, Hyperliquid's governance design involves not only parameter adjustments at the smart-contract level but also, more deeply, the validator mechanism at the consensus layer.

At the architectural level, Hyperliquid's governance core relies on the staking of the HYPE token and a validator-voting mechanism. According to its public roadmap and on-chain data, the system is currently in the critical period of transitioning from the second to the third stage of progressive decentralization [41]. In its early days, network consensus was maintained by a very small number of core nodes, which gave the team the ability to rapidly iterate its HyperBFT consensus algorithm and its liquidation engine. As the system matured, the governance structure underwent significant decentralization. The number of validator nodes expanded from an initial handful operated by the foundation (about 4 to 5) to 21 active validators (the permissionless validator set introduced starting April 2025), and was further expanded to approximately 27 between late 2025 and mid-2026; its permissionless-participation mechanism automatically admits any node whose stake ranking places it within the active-set size cap (then the top 21). However, an increase in the number of validators does not equate to a substantive increase in the degree of decentralization. If a few entities control more than one-third of the stake weight, that is enough to break its Byzantine fault tolerance (BFT) guarantee; the true degree of decentralization should be measured by the number of entities holding more than one-third of the stake (that is, the Nakamoto coefficient), rather than the nominal number of validators. The public disclosure of stake-concentration data is itself an important direction in which Hyperliquid's governance transparency needs improvement.

An audit of Hyperliquid's current governance state reveals several engineering challenges that urgently need to be resolved. First, in the distribution of voting power, although a stake-weight mechanism has been introduced, if tokens are highly concentrated in the hands of a few early participants, the system still faces the threat of whale manipulation. To mitigate this risk, the system needs to further explore nonlinear weighting mechanisms such as quadratic voting to strengthen the voice of the broad retail base in governance. Second, the actual exercise of emergency powers has already directly tested the theoretical framework proposed in Section 30.6.2. During the JELLY perpetual futures incident of March 2025, after detecting large-scale market manipulation, Hyperliquid validators used an emergency vote to freeze trading in the JELLY perpetual futures and forcibly settled the affected positions at a price favorable to the HLP (market-making) vault (approximately $0.0095, rather than the manipulated market price of about $0.50). This action in effect exceeded the scope of "defensive operations" as defined in Section 30.6.2: suspending trading is a defensive measure, but unilaterally setting the settlement price constitutes a direct disposition of users' property. The incident triggered heated debate in the community: do validators have the right to exercise quasi-judicial adjudicatory power in the name of protecting the system's solvency? Although the HLP vault's losses were ultimately contained (the vault even recorded a small surplus in the end), the absence of a community accountability mechanism—no formal ex post review process and no independent operational audit report—exposed an engineering gap in the "ex post accountability" component of the emergency-powers framework. The JELLY incident demonstrates that the boundaries of emergency powers cannot be delimited solely through predefined operation types; they also require mandatory post-operation review and community ratification procedures.

Moreover, in the broader design of the emergency-response mechanism, how to improve the transparency and ex post accountability of emergency operations while ensuring network security is a key focus for optimizing the current governance architecture. In December 2025, a validator vote to permanently remove approximately 37 million HYPE (more than 13% of circulating supply) held in the Assistance Fund from the supply passed on December 24 with approximately 85% approval, demonstrating the community's capacity to participate in major economic decisions; yet the irreversibility of that decision, combined with a voting structure in which stake weight was highly concentrated, still showed how such decisions depend on an adequate time window and a broad basis of consensus [42].

Looking ahead, Hyperliquid's governance architecture needs to deepen along two dimensions. On the technical dimension, as HyperEVM is fully deployed, the governance logic should be embedded more deeply into smart contracts to achieve fully automated proposal execution and reduce reliance on off-chain coordination. On the mechanism dimension, the system should introduce a more granular parameterized-governance framework, separating the authority over routine operations such as fee adjustments and margin-ratio settings from the authority over underlying consensus upgrades, thereby building a layered governance structure. The key bottleneck for this layering is that Hyperliquid's core parameters (margin ratios and liquidation thresholds) run in the consensus-layer state machine rather than the EVM contract layer: parameter changes to the former must be implemented through consensus upgrades, whereas the latter can be managed directly through governance contracts on HyperEVM, and passing permissions between the two layers requires the precompiles interface.

## 30.7 Mapping regulatory requirements to technical implementations

Having explored the layered architecture of on-chain financial systems, the design of the liquidation engine, and the engineering implementation of embedded compliance, this section returns to the regulatory framework proposed in Chapter 26 to form a complete loop between regulatory requirements and technical implementations. Building on the structural risks of traditional centralized exchanges, Chapter 26 proposed six "minimal but effective" regulatory principles. This section maps these principles one by one onto the concrete technical implementation schemes discussed in this chapter, shows how embedded compliance converts external regulatory constraints into built-in architectural guarantees, explores the possibility of regulation and technology forming a combined force, and clarifies the domains in which human judgment remains indispensable within a highly automated system.

### 30.7.1 The technical implementation of the six principles

The six regulatory principles proposed in Chapter 26 set goals for building a secure crypto-finance system, and this chapter's three-tier compliance spectrum (hard-coded, parameterized, and reporting-based compliance) provides an engineering implementation path for those goals. Table 30-1 maps each of these six principles onto the different compliance tiers of an on-chain system, showing the concrete technical implementation scheme and implementation priority corresponding to each principle. The table makes clear that asset segregation, as the highest-priority security baseline, is assigned to the hard-coded tier; principles that require continuous data feedback, such as disclosure and evidence-based evolution, fall into the reporting-based tier; and functional regulation and the localized adjustment of international standards depend on the flexibility of the parameterized mechanism. This tiered mapping embodies the differentiated demands of different regulatory requirements for embedding depth and flexibility.

| Chapter 26 regulatory principle | Compliance tier | On-chain technical implementation | Implementation priority |
| :--- | :--- | :--- | :--- |
| Asset segregation as the baseline | Hard-coded compliance | Smart-contract self-custody and non-appropriation logic | Highest |
| Disclosure first | Reporting-based compliance | Real-time on-chain data extraction and automated audit APIs | High |
| Functional regulation | Parameterized compliance | Independent compliance parameters and governance mechanisms for each functional module | Medium |
| Embrace embedded compliance | Combined tiers | Coordinated design of hard-coded, parameterized, and reporting-based mechanisms | Medium |
| International minimum standards with flexible adjustment | Hard-coded and parameterized combined | Minimum standards hard-coded; flexible parameters adjusted by regional governance | Medium |
| Evidence-based evolution | Reporting-based compliance | Continuous evaluation of on-chain data to support dynamic optimization of compliance rules | Long-term |

**Table 30-1.** Mapping between the six regulatory principles of Chapter 26 and their on-chain technical implementations (Data source: compiled by the author)

The deeper logic of this mapping lies in matching embedding depth to the nature of the rule. Non-negotiable security baselines such as asset segregation are entrusted to the deepest hard-coded compliance, whose architectural-level constraint is more reliable than a traditional legal pledge and ex post audit; disclosure-first and evidence-based evolution rely on the continuous data feedback that reporting-based compliance provides, converting periodic static reports into a dynamic display that can be computed and verified in real time; functional regulation draws on parameterized compliance so that the compliance parameters of each module—trading, liquidation, market making—can be flexibly adjusted through governance without altering the underlying core logic; embracing embedded compliance runs through the coordination of all three; and the coexistence of a globally uniform security baseline (such as the absolute leverage cap) with region-specific requirements (such as the margin ratio for specific assets) is precisely what the nested design of hard-coding and parameterization carries.

This mapping framework faces two unresolved structural challenges in implementation. The first is the enforcement mechanism for cross-border jurisdiction. The "regional governance adjustment" envisioned in Table 30-1 lacks a landing path in a permissionless, global on-chain system: in a smart contract accessible by anyone from any jurisdiction, the system cannot reliably determine the jurisdiction to which a user belongs, and techniques such as VPNs can easily circumvent geographic restrictions based on IP addresses. Jurisdiction-aware access control based on zero-knowledge credentials offers a possible technical solution, allowing users from different jurisdictions to obtain differentiated parameter configurations after proving their compliance status; but the engineering maturity and regulatory acceptance of this scheme remain at an early stage. The second challenge is the absence of systemic-risk monitoring. The six principles above focus mainly on compliance at the level of a single protocol, but in a highly interconnected on-chain financial ecosystem, cross-protocol correlated liquidations, liquidity contagion, and the common-mode failure caused by shared oracles constitute a distinct category of systemic risk. This dimension has not yet been incorporated into the current system of regulatory principles, but it has become an unavoidable compliance requirement in the process of scaling on-chain finance.

### 30.7.2 The synergy of regulation and technology

Traditional financial regulation relies mainly on external constraints on institutional behavior—stipulating what an institution may and may not do, and using periodic inspections and severe penalties to compel compliance. The premise of this model is that the institution is capable of violating the rules, and the essence of compliance is to change the cost-benefit expectations of doing so. Embedded compliance, however, offers an entirely new paradigm: regulators can no longer merely require institutions to "pledge to comply with the rules" but can require them to adopt a system architecture that makes it "impossible to violate the rules."

When regulators require that "assets must be segregated," relying solely on periodic financial audits means, in effect, that they bear enormous information-lag risk. But in an on-chain financial system, regulators can require the platform to adopt a non-custodial smart-contract architecture. Under such an architecture, asset segregation is not an operational activity requiring continuous oversight but an architectural property built in at the moment of system deployment. The focus of regulation shifts from "checking whether the institution has misappropriated assets" to "auditing whether the smart-contract code does indeed restrict the authority to transfer assets." This shift significantly reduces the ongoing cost of enforcement while significantly improving the security of assets.

Similarly, for disclosure requirements, regulators can push the industry to adopt standardized on-chain data interfaces. Rather than requiring platforms to submit complex financial statements each month, it is better to require them to provide a regulatory API that can read on-chain state in real time. This enables regulators to build automated monitoring systems that detect abnormal trading patterns and the accumulation of systemic risk in real time. The driving force of regulation is no longer merely the threat of punishment but the impetus to evolve financial infrastructure toward a more transparent and resilient technical architecture.

The synergy of regulation and technology is also reflected in the standardization of governance mechanisms. Regulators can require that parameter adjustments and contract upgrades in an on-chain system follow specific timelock-delay and multisig-security standards. Such a requirement does not interfere with the community's specific governance decisions but ensures that the governance process itself has sufficient transparency and predictability, providing market participants a buffer period to assess and respond to rule changes. By requiring good architecture, regulators not only achieve the goal of protecting investors but also promote innovation and development in financial technology.

However, the premise of this paradigm shift is that regulators possess the technical capacity to audit smart-contract code—a capacity that at present barely exists anywhere in the global financial-regulatory system. The core technical capabilities of current financial regulators are concentrated in legal analysis and financial auditing, not cryptography and smart-contract engineering. If regulators cannot independently verify whether contract code truly implements the compliance constraints it claims, "auditing the code" may degenerate into another form of "compliance theater," relying solely on third-party audit reports while the auditing firms themselves lack a standardized accountability mechanism. The transition from "auditing institutional behavior" to "auditing system architecture" therefore requires the concurrent advancement of at least two areas of infrastructure: first, establishing certified smart-contract auditing standards (analogous to the international standards in the accounting-audit field) to provide a unified framework for the scope, methods, and report format of contract audits; and second, building a tiered certification and accountability mechanism for auditing firms during the transition period, to ensure the credibility of third-party audit conclusions.

### 30.7.3 Compliance functions that technology cannot replace

Although embedded compliance solves a large number of traditional compliance problems through hard-coding and automation mechanisms, in a complex financial system the application of technology has its inherent boundaries. Certain key compliance functions and the handling of extreme situations still require human judgment, discretion, and social consensus.

First, dispute resolution and legal appeals cannot be fully replaced by code. A smart contract can only execute operations according to predetermined logic; it cannot judge whether that logic is fair in a specific situation. When an unexpected vulnerability causes user losses, or when an extreme market-manipulation event occurs, the victims need to seek redress. On-chain systems lack an intrinsic judicial-adjudication mechanism, and for the determination of complex liability and the recovery of losses, one must still rely on the real-world legal system and the rulings of human judges.

Second, cross-border enforcement coordination and complex crime investigation require human involvement. Although the transparency of on-chain data helps trace fund flows, linking an on-chain address to a real-world entity's identity often requires transnational intelligence sharing, judicial assistance, and traditional investigative methods. Technology can provide clues and evidence, but combating transnational financial crime and enforcing sanctions lists are essentially exercises of state power that require the collaboration of diplomatic and legal professionals.

Moreover, the identification of new risks and the evolution of the compliance framework require human strategic vision. An automated monitoring system can only detect anomalies based on known patterns; it often lacks the forward-looking capacity to identify market manipulation carried out through entirely new mechanisms or the covert accumulation of systemic risk. Compliance experts and regulators must continuously analyze market dynamics and understand newly emerging financial instruments and trading strategies in order to formulate new regulatory principles and guide upgrades to the underlying architecture.

Finally, the enforcement of ethical standards and the ultimate handling of a systemic crisis cannot do without human social consensus. In extreme market turmoil, decisions such as whether to suspend trading or whether to invoke emergency governance powers to intervene often involve complex trade-offs among different interest groups. A purely technical system cannot bear this kind of responsibility, which carries a high degree of political and ethical weight. Humans set the rules at the outset of the system's design, and they must also bear ultimate decision-making responsibility when the system faces a major systemic crisis. Embedded compliance does not eliminate the role of humans; rather, it frees human energy from tedious day-to-day compliance checks and concentrates it on higher-level architectural design, risk anticipation, and crisis management.

## 30.8 Chapter summary

The three-tier compliance-spectrum architecture proposed in this chapter (hard-coded, parameterized, and reporting-based compliance) provides a systematic analytical framework and implementation path for the compliance engineering of on-chain financial systems. Hard-coded compliance, by compiling non-negotiable security baselines such as asset segregation directly into smart-contract logic, achieves a paradigm shift from "requiring institutions to obey the law" to "making it impossible for institutions to break it." Parameterized compliance, within a fixed rule framework, allows operational parameters such as the margin ratio to be dynamically adjusted through transparent governance mechanisms, striking an engineering balance between security and flexibility. Reporting-based compliance leverages the immutability and global visibility of on-chain data to convert ex post auditing into an inherent property of the system. The organic combination of the three completes the full mapping from regulatory requirements to on-chain engineering implementation.

The introduction of zero-knowledge-proof technology breaks the zero-sum game between regulatory transparency and user privacy [26]. Through cryptographic proofs, traders can prove to the system that they satisfy specific compliance conditions without exposing the underlying identity data, allowing on-chain finance to satisfy regulatory standards such as anti-money laundering while preserving its core permissionless character. This technical path demonstrates the potential of a digital-native architecture to surpass traditional finance on the compliance dimension.

The inevitable cost of embedding rules into architecture is an increase in system rigidity. The dual architecture of timelock and emergency powers provides an engineering solution to this contradiction: routine changes are subjected to a mandatory delay for community review in order to maintain immutability, while a constrained fast track for extreme situations ensures the system's capacity for crisis response [43]. This controllable upgradeability, combined with the governance roadmap of progressive decentralization, constitutes the optimal practice for on-chain governance under current technical conditions. However, functions such as dispute resolution, cross-border enforcement coordination, and the forward-looking identification of new risks still lie beyond the capacity boundary of a purely technical system and require human judgment and social consensus to supplement.

Hyperliquid's app-chain architecture and its on-chain central limit order book constitute a frontier practical prototype of embedded compliance, but a significant gap remains between the current prototype and a mature financial infrastructure. Along this evolutionary path, a new force is joining: artificial intelligence. When AI agents can autonomously conduct market making, trading, and risk management on-chain, the operating mode of financial markets will once again undergo a profound change. This evolutionary trend is precisely the core theme explored in Part XI.

## References

[1] Ray, J. J. (2023). *First Interim Report of John J. Ray III to the Independent Directors on Control Failures at the FTX Exchanges*. FTX Debtors. https://www.fishmanhaygood.com/wp-content/uploads/2023/04/April-9-Debtor-Report-on-Failure-of-Internal-Controls-1.pdf

[2] U.S. Department of Justice. (2024). *Samuel Bankman-Fried Sentenced to 25 Years for His Orchestration of Multiple Fraudulent Schemes*. https://www.justice.gov/archives/opa/pr/samuel-bankman-fried-sentenced-25-years-his-orchestration-multiple-fraudulent-schemes

[3] Auer, R. (2019). Embedded supervision: how to build regulation into blockchain finance. *BIS Working Papers*, No 811. Bank for International Settlements. https://www.bis.org/publ/work811.pdf

[4] Thomson Reuters. (2024). *Cost of Compliance Report*. Thomson Reuters Regulatory Intelligence.

[5] Deloitte. (n.d.). *Cost of compliance and regulatory productivity*. Deloitte. https://www.deloitte.com/us/en/services/consulting/articles/cost-of-compliance-regulatory-productivity.html

[6] Research and Markets. (2024). *Global anti-money laundering systems market 2024–2028*. GlobeNewswire. https://www.globenewswire.com/news-release/2024/06/12/2897441/28124/en/Global-Anti-money-Laundering-Systems-Market-2024-2028.html

[7] Auer, R. (2022). Embedded supervision: How to build regulation into decentralized finance. *Crypto Economic Systems*. https://cryptoeconomicsystems.pubpub.org/pub/auer-embedded-supervision/release/1

[8] Lessig, L. (2006). *Code: Version 2.0*. Basic Books.

[9] Jensen, J. R., von Wachter, V., & Ross, O. (2021). Leveraged trading on blockchain technology. *arXiv preprint arXiv:2102.13488*. https://doi.org/10.48550/arXiv.2102.13488

[10] Aquilina, M., Frost, J., & Schrimpf, A. (2024). Decentralized finance (DeFi): a functional approach. *Journal of Financial Regulation*, *10*(1), 1-25. https://doi.org/10.1093/jfr/fjad013

[11] Nabilou, H. (2022). The Law and Macroeconomics of Custody and Asset Segregation Rules: Defining the Perimeters of Crypto-Banking. *Amsterdam Law School Research Paper*.

[12] Zetzsche, D. A., Arner, D. W., & Buckley, R. P. (2020). Decentralized finance. *Journal of Financial Regulation*, *6*(2), 172-203.

[13] Bhargavan, K., Delignat-Lavaud, A., Fournet, C., Gollamudi, A., Gonthier, G., Kobeissi, N., ... & Zanella-Beguelin, S. (2016). Formal verification of smart contracts: Short paper. In *Proceedings of the 2016 ACM Workshop on Programming Languages and Analysis for Security* (pp. 91-96).

[14] He, S., Manela, A., Ross, O., & von Wachter, V. (2022). Fundamentals of perpetual futures. *arXiv preprint arXiv:2212.06888*. https://doi.org/10.48550/arXiv.2212.06888

[15] Ackerer, D., Hugonnier, J., & Jermann, U. (2025). Perpetual futures pricing. *Mathematical Finance*. https://doi.org/10.1111/mafi.70018

[16] Chainlink. (2026). *Onchain Governance: How Smart Contracts Enable Decentralized Control*. https://chain.link/article/onchain-governance

[17] Ali, Z. (2025). Anatomy of the Oct 10-11, 2025 Crypto Liquidation Cascade: Macroeconomic Triggers, Market Microstructure, and Systemic Risk Lessons. *SSRN Electronic Journal*.

[18] Bybit. (2025). *Maintenance Margin Calculation (USDC Perpetual & Futures)*. https://www.bybit.com/en/help-center/article/Maintenance-Margin-Calculation-USDC-Contract

[19] Chen, E., Ma, M., & Nie, Z. (2024). Perpetual future contracts in centralized and decentralized exchanges: Mechanism and traders' behavior. *Electronic Markets*.

[20] Werapun, W., Karode, T., Suaboot, J., & Arpornthip, T. (2025). Exploring Risk and Return Profiles of Funding Rate Arbitrage on CEX and DEX. *Blockchain: Research and Applications*.

[21] Kao, H. T., Chitra, T., Chiang, R., & Morrow, J. (2020). An analysis of the market risk to participants in the compound protocol. *International Symposium on Cyber Security Cryptography and Machine Learning*.

[22] Xu, L. (2024). Blockchain Transaction Monitoring and Anomaly Analysis System. *IEEE Access*. https://doi.org/10.1109/dikw64278.2024.00015

[23] Lazirko, M., Appelbaum, D., & Vasarhelyi, M. (2025). Proof of reserves: A double-helix framework. *The British Accounting Review*.

[24] Azgad-Tromer, S., Garcia, J., & Tromer, E. (2023). The Case for On-Chain Privacy and Compliance. *Stanford Journal of Blockchain Law & Policy*. https://stanford-jblp.pubpub.org/pub/onchain-privacy-compliance

[25] U.S. Department of the Treasury. (2022). U.S. Treasury Sanctions Notorious Virtual Currency Mixer Tornado Cash. https://home.treasury.gov/news/press-releases/jy0916

[26] Decker, N. (2025). Proof Without Exposure: Zero-Knowledge Proofs as a Cryptographic Framework for Institutional Financial Compliance. *SSRN Electronic Journal*. https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5170329 https://doi.org/10.2139/ssrn.5170329

[27] Polygon Technology. (2022). Introducing Polygon ID, Zero-Knowledge Identity for Web3. https://polygon.technology/blog/introducing-polygon-id-zero-knowledge-own-your-identity-for-web3

[28] zkMe. (2024). KYC Explained: Securing Your Identity in the Web3 World. https://medium.com/@zkMe/kyc-explained-securing-your-identity-in-the-web3-world-8cc2a4b47f15

[29] De Filippi, P., Mannan, M., & Reijers, W. (2020). Blockchain as a confidence machine: The problem of trust & challenges of governance. *Technology in Society*, *62*, 101284.

[30] OpenZeppelin. (2021). *Protect Your Users With Smart Contract Timelocks*. https://www.openzeppelin.com/news/protect-your-users-with-smart-contract-timelocks

[31] Joshi, S. (2023). *Timelock Contracts and DeFi Security: Lessons from Compound*. Medium. https://medium.com/@srinivasjoshi66/timelock-contracts-and-defi-security-lessons-from-compound-fe24f3e4574b

[32] Elem, O., & Talmon, N. (2026). Legitimate Overrides in Decentralized Protocols. *arXiv preprint arXiv:2602.12260*. https://doi.org/10.48550/arXiv.2602.12260

[33] Qasse, I., Hamdaqa, M., & Jonsson, B. T. (2026). Immutable in principle, upgradeable by design: Exploratory study of smart contract upgradeability. *Empirical Software Engineering*, *31*(1), 1-35.

[34] Qin, K., Zhou, L., Livshits, B., & Gervais, A. (2021). Attacking the DeFi ecosystem with flash loans for fun and profit. In *Financial Cryptography and Data Security: 25th International Conference, FC 2021*. Springer.

[35] MixBytes. (2022). *DAO Voting Vulnerabilities*. https://mixbytes.io/blog/dao-voting-vulnerabilities

[36] Lalley, S. P., & Weyl, E. G. (2018). Quadratic voting: How mechanism design can radicalize democracy. *AEA Papers and Proceedings*, *108*, 33–37. https://doi.org/10.1257/pandp.20181002

[37] Wright Jr, D. (2019). Quadratic voting and blockchain governance. *UMKC Law Review*, *88*, 451.

[38] Benhaim, A., Falk, B. H., & Tsoukalas, G. (2025). Balancing power in decentralized governance: Quadratic voting and information aggregation. *Management Science*. https://pubsonline.informs.org/doi/abs/10.1287/mnsc.2024.08469 https://doi.org/10.1287/mnsc.2024.08469

[39] Walden, J. (2020). *Progressive Decentralization: A Playbook for Building Crypto Applications*. a16z crypto. https://a16z.com/progressive-decentralization-a-playbook-for-building-crypto-applications/

[40] Walden, J. (2023). *Progressive decentralization: a high-level framework*. a16zcrypto. https://a16zcrypto.com/posts/article/progressive-decentralization-a-high-level-framework/

[41] Hyperliquid. (2025). *Roadmap | Hyperliquid Wiki*. https://hyperliquid-co.gitbook.io/wiki/introduction/roadmap

[42] The Defiant. (2025). *Hyperliquid Proposes Burning 13% of Circulating Supply*. https://thedefiant.io/news/tokens/hyperliquid-proposes-burning-13-percent-of-circulating-token-supply

[43] Wang, Z., Pu, F., Cheung, V., & Hao, R. (2025). Balancing security and liquidity: A time-weighted snapshot framework for DAO governance voting. *arXiv preprint arXiv:2505.00888*. https://arxiv.org/abs/2505.00888 https://doi.org/10.48550/arXiv.2505.00888


