Fluent 백서

Fluent

원문

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

On this page Fluent ships every standard Ethereum precompile at addresses 0x01 through 0x11 . Each is implemented as a system contract that wraps the corresponding revm_precompile function — semantics are byte-for-byte identical to mainnet Ethereum, with one minor implementation note in BN254. Address Description 0x0000000000000000000000000000000000000001 ecrecover — secp256k1 signature recovery (Frontier) 0x0000000000000000000000000000000000000002 SHA-256 hash (Frontier) 0x0000000000000000000000000000000000000003 RIPEMD-160 hash (Frontier) 0x0000000000000000000000000000000000000004 Identity / data copy (Frontier) 0x0000000000000000000000000000000000000005 Modular exponentiation — EIP-198 (Berlin gas schedule) 0x0000000000000000000000000000000000000006 BN254 G1 addition — EIP-196 0x0000000000000000000000000000000000000007 BN254 G1 scalar multiplication — EIP-196 0x0000000000000000000000000000000000000008 BN254 pairing check — EIP-197 0x0000000000000000000000000000000000000009 BLAKE2 F compression — EIP-152 0x000000000000000000000000000000000000000a KZG point evaluation — EIP-4844 0x000000000000000000000000000000000000000b BLS12-381 G1 addition — EIP-2537 0x000000000000000000000000000000000000000c BLS12-381 G1 multi-scalar multiplication — EIP-2537 0x000000000000000000000000000000000000000d BLS12-381 G2 addition — EIP-2537 0x000000000000000000000000000000000000000e BLS12-381 G2 multi-scalar multiplication — EIP-2537 0x000000000000000000000000000000000000000f BLS12-381 pairing — EIP-2537 0x0000000000000000000000000000000000000010 BLS12-381 map FP → G1 — EIP-2537 0x0000000000000000000000000000000000000011 BLS12-381 map FP² → G2 — EIP-2537 Implementations live under fluentbase/contracts/<name>/ , where <name> matches the precompile: ecrecover , sha256 , ripemd160 , identity , modexp , bn256 , blake2f , kzg , bls12381 . Address constants are defined in fluentbase/crates/types/src/genesis.rs as PRECOMPILE_<NAME> via Address::with_last_byte(0xNN) . Notes on implementation ​ BN254 (BN256) endianness : the implementation converts between Ethereum's big-endian inputs and SP1's little-endian internal representation at the boundary ( bn256/src/lib.rs — point_be_to_le / point_le_to_be ). The external interface remains EIP-196/197 compliant; the conversion is invisible to callers. One contract crate, several addresses : the BN254 family shares one bn256 contract crate dispatched by caller address; the BLS12-381 family shares one bls12381 crate the same way. The genesis build installs the same compiled rWasm at every address in each family. Source ​ Implementations delegate to revm_precompile for the underlying math, so any divergence from mainnet semantics would be visible in the wrapper code. Notes on implementation Source ## /fluentbase-sdk/router On this page Dispatch Methods with the Router ​ The router macro provides a robust method dispatch system for Fluentbase smart contracts. It automatically transforms function calls with Solidity-compatible selectors into appropriate Rust function calls, handling parameter decoding and result encoding. 💡 Tip The router macro serves as the foundation for building interoperable smart contracts and ultimately blended applications, that can be called from EVM-compatible environments. It works hand-in-hand with the client generation system to enable cross-contract interactions. Overview ​ The router system works by generating a main() method that: Reads the first 4 bytes of input data as a function selector Matches the selector against available methods Decodes parameters based on the method signature Calls the appropriate method with decoded parameters Encodes the return value and writes it to output This enables seamless interoperability between Rust contracts and EVM-compatible environments like Solidity. Usage Patterns ​ 1. Trait Implementation (Recommended) ​ The preferred approach is to define a trait interface and implement it with the router macro: #![cfg_attr(target_arch = "wasm32" , no_std, no_main)] extern crate alloc ; extern crate fluentbase_sdk ; use alloc :: string :: String ; use fluentbase_sdk :: { basic_entrypoint , derive :: { router , Contract } , SharedAPI , Address , U256 , } ; #[derive(Contract)] struct TokenContract < SDK > { sdk : SDK , } // Define the contract interface pub trait ERC20Interface { fn total_supply ( & self ) -> U256 ; fn balance_of ( & self , owner : Address ) -> U256 ; fn transfer ( & mut self , to : Address , amount : U256 ) -> bool ; fn approve ( & mut self , spender : Address , amount : U256 ) -> bool ; } // Implement the interface with automatic routing #[router(mode = "solidity" )] impl < SDK : SharedAPI > ERC20Interface for TokenContract < SDK > { fn total_supply ( & self ) -> U256 { // Implementation here U256 :: from ( 1000000 ) } fn balance_of ( & self , owner : Address ) -> U256 { // Implementation here U256 :: from ( 100 ) } fn transfer ( & mut self , to : Address , amount : U256 ) -> bool { // Implementation here true } fn approve ( & mut self , spender : Address , amount : U256 ) -> bool { // Implementation here true } } impl < SDK : SharedAPI > TokenContract < SDK > { pub fn deploy ( & self ) { // Deployment logic here } } basic_entrypoint! ( TokenContract ) ; 2. Direct Implementation ​ For simpler contracts, you can implement methods directly on your struct: #![cfg_attr(target_arch = "wasm32" , no_std, no_main)] extern crate alloc ; extern crate fluentbase_sdk ; use alloc :: string :: String ; use fluentbase_sdk :: { basic_entrypoint , derive :: { router , Contract } , SharedAPI , U256 , } ; #[derive(Contract)] struct SimpleStorage < SDK > { sdk : SDK , } #[router(mode = "solidity" )] impl < SDK : SharedAPI > SimpleStorage < SDK > { // Only public methods are included in routing pub fn store ( & mut self , value : U256 ) { // Store implementation } pub fn retrieve ( & self ) -> U256 { // Retrieve implementation U256 :: from ( 42 ) } // Private methods are excluded from routing fn internal_helper ( & self ) { // This won't be accessible via function selectors } // Special method - always excluded from routing pub fn deploy ( & self ) { // Deployment logic } } basic_entrypoint! ( SimpleStorage ) ; Function Selectors ​ Function selectors are 4-byte identifiers that uniquely identify functions in smart contracts. They are typically the first 4 bytes of the keccak256 hash of the function signature (function name and parameter types), but can also be customized to use different values. Function selectors are used in Ethereum and other EVM-compatible blockchains to determine which function to call when a transaction is sent to a contract. Automatic Selector Generation ​ By default, function selectors are calculated from the method signature using keccak256: // Selector calculated from "transfer(address,uint256)" -> 0xa9059cbb fn transfer ( & mut self , to : Address , amount : U256 ) -> bool { // Implementation } Custom Selector Specification ​ You can override the default selector using the #[function_id] attribute: #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { // Specify using Solidity signature #[function_id( "greeting(string)" )] pub fn greeting ( & self , message : String ) -> String { message } // Specify using direct hex value #[function_id( "0xe8927fbc" )] pub fn custom_method ( & self , value : U256 ) -> bool { ! value . is_zero ( ) } // Specify using raw bytes # [ function_id ( [ 169 , 5 , 156 , 187 ] ) ] pub fn another_method ( & self ) -> U256 { U256 :: from ( 123 ) } } Selector Validation ​ Enable validation to ensure your selectors match the expected function signature: #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { // Validation enabled - will check that the selector matches transfer(address,uint256) #[function_id( "transfer(address,uint256)" , validate(true))] pub fn transfer ( & mut self , to : Address , amount : U256 ) -> bool { true } // Uses selector as-is without verification #[function_id( "0xdeadbeef" , validate(false))] pub fn custom_selector ( & self ) -> String { "custom" . to_string ( ) } } When to use validation: During development to catch type mismatches When maintaining compatibility with existing contracts During refactoring to prevent accidental selector changes Encoding Modes ​ The router supports two encoding modes for parameter and return value handling: Solidity Mode (Default) ​ Full EVM compatibility using standard Solidity ABI encoding: #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { // Uses Solidity ABI encoding - compatible with EVM contracts pub fn standard_method ( & self , addr : Address , amount : U256 ) -> bool { // Implementation true } } Characteristics: Big-endian byte order 32-byte alignment Compatible with web3.js , ethers.js , and other EVM tools Larger payload size This mode uses the same encoding as described in the Codec System documentation . Fluent Mode ​ Optimized encoding for WASM environments: #[router(mode = "fluent" )] impl < SDK : SharedAPI > MyContract < SDK > { // Uses optimized Fluent encoding - smaller payloads pub fn optimized_method ( & self , data : Vec < u8 > ) -> String { // Implementation String :: from_utf8 ( data ) . unwrap_or_default ( ) } } Characteristics: Little-endian byte order 4-byte alignment Smaller payload size Optimized for WASM execution Not directly compatible with standard EVM tools This mode uses the same encoding as described in the Codec System documentation . Special Methods ​ Deploy Method ​ The deploy method is automatically excluded from routing and serves as the contract initialization function: impl < SDK : SharedAPI > MyContract < SDK > { pub fn deploy ( & self ) { // Called once during contract deployment // Initialize contract state here // Set up initial storage values // Emit deployment events } } Key points: Always excluded from function selector routing Called automatically during contract deployment Should contain initialization logic Can be pub or private - visibility doesn't matter for routing exclusion Fallback Method ​ Handle unmatched function selectors with a fallback method: #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { pub fn standard_method ( & self ) -> U256 { U256 :: from ( 1 ) } // Handles any selector that doesn't match other methods fn fallback ( & self ) { // Log unknown function call // Return default values // Or implement proxy logic } } Behavior: Called for any unrecognized function selector Must have signature fn fallback(&self) with no parameters or return value If no fallback is defined, unmatched selectors cause a panic Useful for implementing proxy contracts or logging Advanced Examples ​ Multi-Function Contract with Events ​ #![cfg_attr(target_arch = "wasm32" , no_std, no_main)] extern crate alloc ; extern crate fluentbase_sdk ; use alloc :: string :: String ; use alloy_sol_types :: { sol , SolEvent } ; use fluentbase_sdk :: { basic_entrypoint , derive :: { router , Contract } , emit_event , Address , SharedAPI , U256 , } ; sol! { event Transfer ( address indexed from , address indexed to , uint256 value ) ; event Approval ( address indexed owner , address indexed spender , uint256 value ) ; } #[derive(Contract)] struct TokenContract < SDK > { sdk : SDK , } pub trait ERC20Events { fn transfer ( & mut self , to : Address , amount : U256 ) -> bool ; fn approve ( & mut self , spender : Address , amount : U256 ) -> bool ; } #[router(mode = "solidity" )] impl < SDK : SharedAPI > ERC20Events for TokenContract < SDK > { fn transfer ( & mut self , to : Address , amount : U256 ) -> bool { let from = self . sdk . msg_sender ( ) ; // Emit event emit_event ( & mut self . sdk , Transfer { from , to , value : amount } ) ; true } fn approve ( & mut self , spender : Address , amount : U256 ) -> bool { let owner = self . sdk . msg_sender ( ) ; // Emit event emit_event ( & mut self . sdk , Approval { owner , spender , value : amount } ) ; true } } basic_entrypoint! ( TokenContract ) ; Contract with Error Handling and Fallback ​ #![cfg_attr(target_arch = "wasm32" , no_std, no_main)] extern crate alloc ; extern crate fluentbase_sdk ; use alloc :: string :: String ; use fluentbase_sdk :: { basic_entrypoint , derive :: { router , Contract } , SharedAPI , U256 , } ; #[derive(Contract)] struct RobustContract < SDK > { sdk : SDK , } #[router(mode = "solidity" )] impl < SDK : SharedAPI > RobustContract < SDK > { pub fn safe_divide ( & self , numerator : U256 , denominator : U256 ) -> U256 { if denominator . is_zero ( ) { // Return zero on division by zero U256 :: zero ( ) } else { numerator / denominator } } pub fn require_positive ( & self , value : U256 ) -> bool { if value . is_zero ( ) { panic! ( "Value must be positive" ) ; } true } pub fn safe_operation ( & self , operation : String ) -> String { if operation == "allowed" { "Success" . to_string ( ) } else { panic! ( "Operation failed as requested" ) ; } } // Handle unknown function calls fn fallback ( & self ) { // Log the unknown call attempt // In a real implementation, you might want to: // - Log the selector that was called // - Return an error code // - Implement proxy logic to another contract } pub fn deploy ( & self ) { // Deployment initialization } } basic_entrypoint! ( RobustContract ) ; Error Handling and Debugging ​ Common Compilation Errors ​ Function Selector Collisions: // This will cause a compile-time error #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { pub fn method_a ( & self ) -> U256 { U256 :: from ( 1 ) } #[function_id( "methodA()" )] // Same selector as method_a pub fn method_b ( & self ) -> U256 { U256 :: from ( 2 ) } } Solution: Use unique function signatures or custom selectors. No Public Methods: // This will cause a compile-time error in direct implementations #[router(mode = "solidity" )] impl < SDK : SharedAPI > MyContract < SDK > { fn private_method ( & self ) -> U256 { U256 :: from ( 1 ) } // Not public! } Solution: Mark methods as pub or use trait implementations. 🏆 Best Practice Use Trait Implementations: They provide better organization and interface clarity Enable Validation During Development: Catch selector mismatches early Handle Edge Cases: Use Option/Result types for fallible operations Implement Fallback Handlers: Provide graceful handling of unknown calls Test Selector Generation: Verify your selectors match expected values Use Meaningful Names: Function names should reflect their Solidity equivalents Document Custom Selectors: Explain why custom selectors are used Testing Router Functions ​ #[cfg(test)] mod tests { use super :: * ; use fluentbase_sdk_testing :: HostTestingContext ; use alloy_sol_types :: { SolCall , sol } ; #[test] fn test_transfer_selector ( ) { // Define the Solidity function for selector calculation sol! ( function transfer ( address to , uint256 amount ) returns ( bool ) ) ; // Generate the call data let call_data = transferCall { to : Address :: ZERO , amount : U256 :: from ( 100 ) , } . abi_encode ( ) ; // Test the contract let sdk = HostTestingContext :: default ( ) . with_input ( call_data ) ; let mut contract = TokenContract :: new ( sdk . clone ( ) ) ; contract . deploy ( ) ; contract . main ( ) ; // Verify the output let output = sdk . take_output ( ) ; // Assert expected behavior } } Integration with Other SDK Features ​ The router system integrates seamlessly with other Fluentbase SDK features: Storage System : Use solidity_storage! for persistent state Events: Emit events using sol! macro and emit_log Client Generation : Generate clients using the client macro Cross-Contract Calls: Call other contracts using generated clients This makes the router the central dispatch mechanism in a comprehensive smart contract development framework. See Also ​ Overview : Return to the main SDK documentation Codec System : Understand how parameters are encoded/decoded Storage Patterns : Learn about state management ⚠️ Performance Considerations Solidity Mode: Larger payloads but full EVM compatibility Fluent Mode: Smaller payloads and faster processing but limited compatibility Function Count: Large numbers of functions increase dispatch time linearly Parameter Complexity: Complex types require more encoding/decoding overhead Validation: Minimal runtime impact, mostly compile-time checking The router system provides an efficient and type-safe way to build interoperable smart contracts that can seamlessly interact with EVM-compatible environments while maintaining the performance benefits of Rust and WASM execution. Dispatch Methods with the Router Overview Usage Patterns 1. Trait Implementation (Recommended) 2. Direct Implementation Function Selectors Automatic Selector Generation Custom Selector Specification Selector Validation Encoding Modes Solidity Mode (Default) Fluent Mode Special Methods Deploy Method Fallback Method Advanced Examples Multi-Function Contract with Events Contract with Error Handling and Fallback Error Handling and Debugging Common Compilation Errors Testing Router Functions Integration with Other SDK Features See Also ## /fluentbase-sdk/storage On this page Solidity Compatible Storage ​ The Fluentbase storage system implements Solidity-compatible storage in Rust contracts, following Solidity's storage layout specification . It provides significant code size reduction through direct storage access for primitive types while maintaining full compatibility with EVM storage patterns. 🧱 Prerequisite This documentation assumes familiarity with the Router System for building contracts. Storage is typically used within router-enabled contracts to manage persistent state. Overview ​ The solidity_storage! macro automatically generates type-safe storage access methods that: Calculate storage keys using the same hashing as Solidity Optimize storage access for primitive types ≤ 32 bytes Handle complex types through encoding/decoding Provide a familiar API similar to Solidity storage This ensures that Rust contracts can seamlessly interact with Solidity contracts and maintain storage compatibility across different execution environments. Storage Types and Layout ​ 1. Simple Values (Primitive Types) ​ Simple values are stored directly in their assigned slot: use fluentbase_sdk :: { derive :: solidity_storage , Address , SharedAPI , U256 , I256 , FixedBytes , } ; solidity_storage! { Address Owner ; // Slot 0 bool Paused ; // Slot 1 U256 TotalSupply ; // Slot 2 I256 Price ; // Slot 3 u64 Timestamp ; // Slot 4 [ u8 ; 32 ] Hash ; // Slot 5 FixedBytes < 20 > Data ; // Slot 6 } // Usage example impl < SDK : SharedAPI > MyContract < SDK > { pub fn deploy ( & mut self ) { // Set initial values Owner :: set ( & mut self . sdk , self . sdk . context ( ) . contract_caller ( ) ) ; Paused :: set ( & mut self . sdk , false ) ; TotalSupply :: set ( & mut self . sdk , U256 :: from ( 1000000 ) ) ; } pub fn transfer_ownership ( & mut self , new_owner : Address ) { let current_owner = Owner :: get ( & self . sdk ) ; if current_owner == self . sdk . context ( ) . contract_caller ( ) { Owner :: set ( & mut self . sdk , new_owner )
프로젝트로 돌아가기