Gravity 백서

Gravity

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 23쪽 중 15쪽

sender: * Escrows `amount` G tokens (ERC-20) in itself. * Calls `GravityPortal.send(abi.encode(amount, recipient))` with an ETH fee. `GravityPortal.send` uses a compact 36-byte header format: ``` payload = sender (20 bytes) || nonce (16 bytes) || message ``` This trims the typical 128+ bytes of `abi.encode` overhead down to 36, charged as: ``` fee = baseFee + (36 + message.length) * feePerByte // wei, paid in ETH ``` The portal rejects both under- and over-payment (`InsufficientFee` / `ExcessiveFee`) to keep fees deterministic. It then assigns a monotonic `uint128` nonce and emits: ```solidity event MessageSent( uint128 indexed nonce, uint256 indexed block_number, bytes payload ); ``` ### Step 2 — Validator observation & attestation Every Gravity validator's observer polls Ethereum for `MessageSent` events, filtered on the GravityPortal address, between its cursor and the latest finalized block. New events with `nonce > last_processed_nonce` are accepted and emitted into AptosBFT. The BFT layer reaches agreement on the observed batch in the same finality window as normal transactions. There's no delayed settlement — the validators that order blocks also order observations. ### Step 3 — On-chain commit The agreed batch becomes a `SYSTEM_CALLER` transaction calling: ```solidity nativeOracle.recordBatch( /* sourceType */ 0, // BLOCKCHAIN /* sourceId */ 1, // Ethereum mainnet /* nonces */ [...], // strictly sequential /* blockNumbers */ [...], // provenance from MessageSent /* payloads */ [...], // raw PortalMessage bytes /* callbackGasLimits */ [...] ); ``` Native Oracle enforces `nonces[i] == currentNonce + 1` for each entry, reverting `NonceNotSequential(...)` on any gap or duplicate. For each accepted record, it resolves the callback — `(sourceType=0, sourceId=1) → GBridgeReceiver` — and invokes it. ### Step 4 — Callback & native mint `GBridgeReceiver` extends `BlockchainEventHandler` and implements `IOracleCallback`. On invocation it: 1. Decodes the PortalMessage: `(sender, messageNonce, message) = decode(payload)`. 2. Verifies `sourceId == trustedSourceId` (Ethereum mainnet) — rejects with `InvalidSourceChain(...)` otherwise. 3. Verifies `sender == trustedBridge` (the deployed `GBridgeSender`) — defense in depth. 4. Decodes the application message: `(amount, recipient) = abi.decode(message, (uint256, address))`. 5. Calls the native mint precompile: ``` NativeMintPrecompile → 0x00000000000000000000000000000001625F5000 ``` The precompile mints native G tokens directly to the recipient — **no wrapper, no synthetic asset.** The user holds the L1's native gas asset, just as if it had been minted at genesis. Total trip from `bridgeToGravity` call to native G in the recipient's address: one Ethereum-finality window plus one Gravity finality window. No external relayer, no wrapped representation, no separate signer set. *** ## Reliability & Recovery A few mechanics that matter for operators and integrators: * **Finalized-only polling.** Observers only ingest events past Ethereum finality. Reorgs on the source chain cannot land on Native Oracle — by definition, they cannot land on a finalized block. * **Persisted cursors.** Each observer writes `(cursor_block, last_processed_nonce)` to disk per source. After a crash or restart, the observer resumes from its checkpoint instead of rescanning from genesis. * **On-chain reconciliation.** On startup, the observer reads `NativeOracle.getLatestNonce(sourceType, sourceId)`. If the on-chain nonce is ahead of the local checkpoint (e.g., the validator was offline while peers committed), the observer fast-forwards both cursor and last-processed state. No duplicate delivery, no missed events. * **Exactly-once delivery, structurally.** Combining (a) sequential nonces in the contract, (b) strictly monotonic filtering in the observer, and (c) finalized-only polling: each `MessageSent` event maps to at most one `record(...)` call across the whole network. There is no per-handler dedup logic to get wrong. * **Fail-safe callback semantics.** A bug in the callback contract — revert, out-of-gas, wrong logic — does not block the oracle. The record is committed, `CallbackFailed(reason)` is emitted, and operators can patch the handler (via governance-managed callback registration) without losing data. *** ## Live Contract Map | Chain | Contract | Address | | ---------- | ---------------------- | ----------------------------------------------------- | | Ethereum | `GravityPortal` | `0x76cf8526Fa9461e50B2c6702a7246ce6915f6E53` | | Ethereum | `GBridgeSender` | `0xE82c61Ac9Ec2041b493118051afa4F18a55dC876` | | Ethereum | `G` (ERC-20) | `0x9C7BEBa8F6eF6643aBd725e45a4E8387eF260649` | | Gravity L1 | `NativeOracle` | `0x00000000000000000000000000000001625F4000` (system) | | Gravity L1 | `NativeMintPrecompile` | `0x00000000000000000000000000000001625F5000` (system) | Source addresses for the system precompiles are fixed; ABIs are available in the [gravity\_chain\_core\_contracts](https://github.com/Galxe/gravity_chain_core_contracts) repository. *** ## Beyond the Bridge: What the Primitive Enables ![Native Oracle as a primitive: asset bridge, perp DEX oracle, payments / x402, on-chain AI agent, and generic messaging — five application lanes around one consensus-attested core](https://1664081133-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZtdkwV6IW7ZSjaMZNmkU%2Fuploads%2Fgit-blob-01e2dc157a743530d8fb63c442b44583e7dcd5d2%2Fnative-oracle-substrate-fanout.png?alt=media) Native Oracle isn't *the* bridge — the bridge is the first application built on Native Oracle. The primitive itself is just `(sourceType, sourceId, nonce, payload, callback)`; everything above that line is policy. The substrate that today routes Ethereum deposits to a mint precompile can route any externally attested event to any callback governance approves. The primitive doesn't change; only the tuples registered on top of it do. To make that concrete, here are application shapes the primitive supports **by design**, not by deployment. Each is a different `(sourceType, sourceId, callback)` registration: **Asset bridges (today).** Validators observe `MessageSent` events on Ethereum; the callback decodes `(amount, recipient)` and mints native G. More chains under `sourceType = 0` are a governance registration, not a code change. Bidirectional flow — burn on Gravity, release on Ethereum — is the symmetric callback on the same primitive. **Perp DEX oracles.** Mark price, index price, and funding-rate updates require fresh, consensus-attested data — exactly what most perp DEXes today pay an external oracle network for. A registered price-feed source, observed by validators and routed to the perp protocol's callback, removes that external dependency. Liquidations execute against prices the chain itself agreed to, not prices a side network signed. **Payments and x402.** The bridge is one shape of payment; payments in general are another. A payer authorizes on chain A, validators attest it on Gravity, a callback credits the payee — same primitive, different decoder. HTTP-402-style pay-per-call services can use this to verify "the client paid X on chain Y" inside the same finality window that serves the request: no off-chain receipt, no trusted indexer. **On-chain AI agents.** Agents acting on-chain need verifiable inputs they can react to — prices, balances on other chains, the result of off-chain computation they didn't perform themselves. Native Oracle is the substrate they read from. An agent does not have to trust an oracle network the chain itself doesn't trust; whatever the chain sees, the agent sees, in the same finality window. **Arbitrary application messaging.** The PortalMessage format already carries an opaque `message` field. Fungible-token transfer is the first decoder; arbitrary cross-chain calls are a small step from there. The connective thread: every one of these uses the same `(sourceType, sourceId, nonce, payload, callback)` shape, the same AptosBFT machinery, the same fail-safe callback resolution. Adding a new application doesn't mean adding a new trust assumption — it means writing a callback contract and asking governance to register it. The security envelope doesn't expand; only what lives inside it does. # Build Your Own 100k+ TPS Chain Using Gravity SDK A developer-focused guide explains how to build a fully functional, custom L1 blockchain application using the Gravity SDK framework. This developer-focused guide explains how to build a fully functional, custom L1 blockchain application using the **Gravity SDK** framework. We walk through the end-to-end development process with a simple **`key-value store (KvStore)`** application as the running example ([repository](https://github.com/Galxe/gravity-kvstore)). This guide covers: * **Core Architecture**: How Gravity SDK decouples complex consensus from application logic through a modular pipeline model. * **Key Module Implementation**: How to implement the **TxPool** and **Executor/Committer** modules that interface directly with Gravity SDK. * **Full Lifecycle**: The journey of a transaction—submission, ordering, execution, consensus, and durable persistence. *** ### **1. Core Architecture: The Decoupled Pipeline Model** At its core, building a blockchain node means constructing a distributed state machine. The design philosophy of **Gravity SDK** is to decompose this complexity into a clear, parallelizable **pipeline model**. This dramatically lowers the development barrier, allowing developers to focus on business logic rather than low-level networking or consensus algorithms. The pipeline cleanly separates responsibilities between **Gravity SDK** and the **application developer**. #### **Gravity SDK’s Responsibilities (Consensus & Scheduling Layer)** * **Consensus Engine**: The heart of Gravity SDK, responsible for the most challenging distributed-systems problems: * **Transaction Ordering**: Pulling transactions from the pool and determining their global order in a block. * **Block Production & Broadcast**: Packaging ordered transactions into blocks and propagating them across the network. * **Networking**: Managing node-to-node P2P communication. * **Consensus Finalization**: Running the AptosBFT consensus algorithm to ensure all honest nodes agree on both block contents and execution results. * **BlockBufferManager**: The bridge between the consensus layer and the execution layer. It tracks block states across their lifecycle (`Ordered`, `Executed`, `Committed`) and enables pipeline parallelism. #### **Developer’s Responsibilities (Application Logic / State Machine)** * **Transaction Pool (TxPool / Mempool)**: The entry point for user transactions, buffering them before consensus. * **Executor**: Where your business logic lives. It receives ordered blocks from the consensus engine, executes each transaction, and computes the resulting state transitions. * **State / Storage**: The blockchain’s ledger. It maintains the latest in-memory state (balances, KV pairs, etc.) and persists finalized changes to a database. * **RPC Service**: The application’s external interface, enabling users to query chain data or submit new transactions. > **Key Advantages: Decoupling & Parallelism** > > By abstracting away networking and consensus complexity, Gravity SDK frees developers to focus solely on evolving the state machine through a few well-defined traits. > > Furthermore, the three pipeline stages — **Ordering (Consensus)**, **Execution (Executor)**, and **Commit (Committer)** — run as independent, parallel tasks. This architecture enables high throughput (TPS) by fully leveraging concurrency. This document will guide you through implementing the two most critical developer-side components: the **transaction pool** and the **execution/commit logic**. The architecture is illustrated in the diagram below: ![image.png](https://1664081133-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZtdkwV6IW7ZSjaMZNmkU%2Fuploads%2Fgit-blob-5af76ce4a980253046e1ce8573b7c568cccf4122%2Fimage.png?alt=media) *** ### **2. Step 1: Implementing the Transaction Pool (TxPool) – Connecting to Transaction Sources** The transaction pool is the first stop for any transaction entering the consensus pipeline. Once a user submits a transaction (txn), the consensus engine continuously pulls from your implemented TxPool, selecting the most suitable transactions to package into a new block. #### **2.1 Understanding Gravity SDK’s Transaction Format (`VerifiedTxn`)** Regardless of how your application-level transaction (Transaction) is defined, it must be convertible into the standardized `VerifiedTxn` format that Gravity SDK recognizes. This structure bridges your application logic and the SDK. ```rust // Standardized transaction format defined by Gravity SDK pub struct VerifiedTxn { // The transaction payload, serialized into bytes pub bytes: Vec<u8>, // The sender’s account address, used for identity and filtering pub sender: ExternalAccountAddress, // Nonce to prevent replay attacks pub sequence_number: u64, // Chain ID, ensuring transactions are not reused across different chains pub chain_id: ExternalChainId, // Transaction hash, serving as the unique identifier. // OnceCell ensures the hash is computed only once for efficiency. #[serde(skip)] pub committed_hash: OnceCell<TxnHash>, } ``` In our **KvStore** example, we define an `into_verified()` method to perform this conversion. The process typically involves two steps: 1. **Serialization**: Use a serialization library (e.g., `serde` + `bcs`) to encode the custom transaction object into a byte stream (`Vec<u8>`). 2. **Metadata Population**: Fill in essential metadata such as sender address, nonce, and other fields to complete the `VerifiedTxn` structure. #### **2.2 Implementing the `TxPool` Trait** The next step is to implement the `TxPool` trait provided by Gravity SDK. Among its methods, the most critical—and the only one you must implement—is `best_txns`. ```rust pub trait TxPool: Send + Sync + 'static { // Returns a batch of the most suitable "Pending" transactions to be included in a block. fn best_txns( &self, filter: Option<Box<dyn Fn((ExternalAccountAddress, u64, TxnHash)) -> bool>> ) -> Box<dyn Iterator<Item = VerifiedTxn>>; } ``` The purpose of this method is straightforward: **return a batch of the highest-quality pending transactions from your pool for block inclusion.** **Key detail: the `filter` function** Gravity SDK supplies a `filter` closure when calling `best_txns`. Apply it before returning any transactions; it removes transactions that the consensus engine has already cached or is actively processing. Why is this necessary? The consensus engine and your transaction pool operate asynchronously. After the engine pulls a batch of transactions, your pool may not change before the next pull. Without the `filter`, the same transactions could be repackaged into multiple blocks. The `filter` ensures uniqueness and prevents duplication. *** #### **2.3 Example: `KvStore` Implementation** Below is the `best_txns` implementation from the KvStore example, with detailed inline commentary: ```rust impl TxPool for KvStoreTxPool { fn best_txns( &self, filter: Option<Box<dyn Fn((ExternalAccountAddress, u64, TxnHash)) -> bool>>, ) -> Box<dyn Iterator<Item = VerifiedTxn>> { // Step 1: Take a snapshot of all transactions in the mempool. // Locking and cloning ensures thread safety during iteration. let txns = (*self.mempool.mempool.lock().unwrap()).clone(); let filter = Arc::new(filter); // Wrap the filter in Arc for thread-safe sharing. // Step 2: Flatten user -> transaction list into a single iterator. let res = Box::new(txns.into_iter().flat_map(move |(addr, user_txns)| { let filter_clone = filter.clone(); user_txns.into_iter().filter_map(move |(seq, txn)| { let verified_txn = txn.raw_txn.clone().into_verified(); // Step 3: Apply filter if provided. if let Some(f) = filter_clone.as_ref() { // `f` expects (address, nonce, hash) as input. // If it returns false, this txn should be discarded. if !f(( addr.clone(), seq, TxnHash::new(verified_txn.committed_hash()), // Compute txn hash )) { return None; } } // Step 4: If filter passes (or no filter exists), return the transaction. Some(verified_txn) }) })); res } } ``` Once the `TxPool` trait is implemented, the Gravity SDK consensus engine can automatically start pulling transactions from your pool. It will call `best_txns` periodically, order the returned transactions, and generate blocks. ### **3. Step 2: Implementing Execution Logic (Executor) – Processing Ordered Blocks** Once the consensus engine agrees on the order of a batch of transactions, it produces an **Ordered Block**—a set of transactions and their agreed-upon order, accepted by all honest nodes in the network. The Executor continuously fetches these ordered blocks from the `BlockBufferManager` in a dedicated asynchronous task, executes the transactions, and updates the in-memory state. *** #### **3.1 `execute_task` Pseudocode Walkthrough** ```rust // Example: Execution task logic pub async fn execute_task(state: State, pending_blocks: PendingBlocks) { loop { // Step 1: Fetch ordered blocks that have not yet been executed // from the BlockBufferManager. This is async; if no blocks are // available, it will wait. let ordered_blocks = get_block_buffer_manager() .get_ordered_blocks(start_num, max_size) .await; for (block, _) in ordered_blocks { // Step 2: Core execution logic // 2.1 Deserialize: Convert Gravity SDK's VerifiedTxn // back into the application’s native transaction type. // 2.2 Apply business logic: Iterate over transactions // and update the in-memory state. // (e.g., in KvStore: `map.insert(key, value)`). // 2.3 Compute StateRoot: After all txns are executed, // compute the new global state Merkle Root (StateRoot), // a cryptographic commitment to the current state. let exec_res = Self::execute_block(block, &state, &pending_blocks).await; // Step 3: Report execution results back to BlockBufferManager. // This updates the block’s lifecycle from "Ordered" → "Executed". get_block_buffer_manager() .set_compute_res(block.block_meta.block_id, exec_res, ...) .await; // Step 4: Increment to the next block number. start_num += 1; } } } ``` *** > **Key Insight: In-Memory Execution & Result Consensus.** > > At this stage, all state changes occur only in memory. **Why?** Although transactions have been executed, the results have not yet gone through consensus. Only after the network agrees on the execution results can the block be considered finalized. > > The computed results (`StateRoot/ExecHash`) are sent back to Gravity SDK for a **second round of consensus**. ### **4. Step 3: Implementing Commit Logic (Committer) – Persisting the Final State** A block and its associated state changes can be considered **finalized** only after a majority of nodes have also reached consensus on the **execution result** (i.e., the `StateRoot/ExecHash`). At this point, it is safe to persist the data to disk. This is the role of the Commit stage. Similar to the execution task, the commit logic runs in its own dedicated asynchronous task. #### **4.1 `commit_task` Pseudocode Walkthrough** ```rust // Example: Commit task logic pub async fn commit_task(storage: Storage, pending_blocks: PendingBlocks) { loop { // Step 1: Fetch blocks whose execution results // have already reached consensus and are ready to commit. // Within Gravity SDK, these blocks are now marked as "Committed". let committed_blocks = get_block_buffer_manager() .get_committed_blocks(start_num, max_size) .await; for block_info in committed_blocks { // Step 2: Retrieve the previously executed block data // and state changes from the in-memory cache (e.g., pending_blocks
프로젝트로 돌아가기