Fluent 백서

Fluent

원문

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

; } } } Storage key calculation: key = slot_number 2. Mappings ​ Mappings store key-value pairs with keys calculated using Solidity's keccak256 hashing: use fluentbase_sdk :: { derive :: solidity_storage , Address , SharedAPI , U256 , Bytes , } ; solidity_storage! { // Simple mapping mapping ( Address => U256 ) Balance ; // Nested mapping mapping ( Address => mapping ( Address => U256 ) ) Allowance ; // Mapping to complex type mapping ( U256 => Bytes ) Metadata ; } impl < SDK : SharedAPI > TokenContract < SDK > { pub fn transfer ( & mut self , to : Address , amount : U256 ) -> bool { let from = self . sdk . context ( ) . contract_caller ( ) ; let from_balance = Balance :: get ( & self . sdk , from ) ; if from_balance < amount { return false ; } // Update balances Balance :: set ( & mut self . sdk , from , from_balance - amount ) ; Balance :: set ( & mut self . sdk , to , Balance :: get ( & self . sdk , to ) + amount ) ; true } pub fn approve ( & mut self , spender : Address , amount : U256 ) { let owner = self . sdk . context ( ) . contract_caller ( ) ; Allowance :: set ( & mut self . sdk , owner , spender , amount ) ; } } Storage key calculation: Simple mapping: key = keccak256(h(k) . p) where h(k) is the padded key and p is the slot Nested mapping: key = keccak256(h(k2) . keccak256(h(k1) . p)) 3. Dynamic Arrays ​ Arrays with dynamic size are supported with element access by index: solidity_storage! { U256 [ ] Values ; Address [ ] [ ] [ ] NestedArr ; } impl < SDK : SharedAPI > ArrayContract < SDK > { pub fn add_value ( & mut self , value : U256 ) { // In real implementation, you'd track the array length separately let index = U256 :: from ( 0 ) ; // For example Values :: set ( & mut self . sdk , index , value ) ; } pub fn get_value ( & self , index : U256 ) -> U256 { Values :: get ( & self . sdk , index ) } pub fn set_nested ( & mut self , i : U256 , j : U256 , k : U256 , addr : Address ) { NestedArr :: set ( & mut self . sdk , i , j , k , addr ) ; } } Storage key calculation: Element at index i is at keccak256(slot) + i 4. Complex Types (Structs) ​ Custom types that implement the Codec trait can be stored. See the Codec documentation for details on making types codec-compatible: use fluentbase_sdk :: { codec :: Codec , derive :: solidity_storage } ; #[derive(Codec, Debug, Default, Clone, PartialEq)] pub struct UserProfile { pub username : Bytes , pub reputation : U256 , pub is_verified : bool , pub metadata : Bytes , } solidity_storage! { UserProfile CurrentUser ; mapping ( Address => UserProfile ) Profiles ; } impl < SDK : SharedAPI > ProfileContract < SDK > { pub fn update_profile ( & mut self , profile : UserProfile ) { let user = self . sdk . context ( ) . contract_caller ( ) ; Profiles :: set ( & mut self . sdk , user , profile ) ; } pub fn get_profile ( & self , user : Address ) -> UserProfile { Profiles :: get ( & self . sdk , user ) } } Storage Optimization ​ The macro automatically selects the most efficient storage method: Direct Storage` ​ Used for types ≤ 32 bytes:: All integer types (u8, u16, u32, u64, u128, U256, I256) Boolean values Addresses Fixed-size byte arrays up to 32 bytes FixedBytes<N> where N ≤ 32 Benefits: No encoding/decoding overhead Minimal gas consumption Reduced contract size StorageValueSolidity ​ Used for complex types: Structs (with #[derive(Codec)] ) Dynamic arrays (Vec<T>, Bytes) Strings Large fixed arrays (> 32 bytes) Features: Automatic serialization/deserialization Support for nested structures Compatibility with Solidity ABI encoding Generated API ​ For each storage variable, the macro generates: // For simple value: Address Owner; pub struct Owner { } impl Owner { const SLOT : U256 = U256 :: from_limbs ( [ 0u64 , 0u64 , 0u64 , 0u64 ] ) ; fn get < SDK : SharedAPI > ( sdk : & SDK ) -> Address { // Implementation } fn set < SDK : SharedAPI > ( sdk : & mut SDK , value : Address ) { // Implementation } fn key < SDK : SharedAPI > ( sdk : & SDK ) -> U256 { // Returns the storage key } } // For mapping: mapping(Address => U256) Balance; pub struct Balance { } impl Balance { const SLOT : U256 = U256 :: from_limbs ( [ 2u64 , 0u64 , 0u64 , 0u64 ] ) ; fn get < SDK : SharedAPI > ( sdk : & SDK , arg0 : Address ) -> U256 { // Implementation } fn set < SDK : SharedAPI > ( sdk : & mut SDK , arg0 : Address , value : U256 ) { // Implementation } fn key < SDK : SharedAPI > ( sdk : & SDK , arg0 : Address ) -> U256 { // Returns the calculated storage key } } 🏆 Best Practice 1. Storage Packing ​ Unlike Solidity, the current implementation doesn't automatically pack multiple values into a single slot. Each variable gets its own slot: solidity_storage! { u8 Small1 ; // Slot 0 (full slot used) u8 Small2 ; // Slot 1 (full slot used) U256 Large ; // Slot 2 } 2. Initialization ​ Always initialize storage values in the deploy method: impl < SDK : SharedAPI > MyContract < SDK > { pub fn deploy ( & mut self ) { Owner :: set ( & mut self . sdk , self . sdk . context ( ) . contract_caller ( ) ) ; Paused :: set ( & mut self . sdk , false ) ; // Initialize all storage variables } } 3. Access Patterns ​ Use the generated methods for all storage access: // Good let balance = Balance :: get ( & self . sdk , user ) ; // Not possible - storage is only accessible through generated methods let balance = self . balance [ user ] ; // This won't compile Testing Storage ​ #[cfg(test)] mod tests { use super :: * ; use fluentbase_sdk_testing :: HostTestingContext ; #[test] fn test_storage_operations ( ) { let mut sdk = HostTestingContext :: default ( ) ; // Test simple value let owner = Address :: from ( [ 1u8 ; 20 ] ) ; Owner :: set ( & mut sdk , owner ) ; assert_eq! ( Owner :: get ( & sdk ) , owner ) ; // Test mapping let user = Address :: from ( [ 2u8 ; 20 ] ) ; let balance = U256 :: from_str_radix ( "1000000000000000000000000" , 10 ) . unwrap ( ) ; Balance :: set ( & mut sdk , user , balance ) ; assert_eq! ( Balance :: get ( & sdk , user ) , balance ) ; // Test nested mapping let spender = Address :: from ( [ 3u8 ; 20 ] ) ; let allowance = U256 :: from ( 1000 ) ; Allowance :: set ( & mut sdk , user , spender , allowance ) ; assert_eq! ( Allowance :: get ( & sdk , user , spender ) , allowance ) ; } } Integration with Other Features ​ The storage system integrates seamlessly with: Router System : Access storage in routed methods Event System : Emit events when storage changes Client System : Read storage from other contracts This provides a complete framework for building complex smart contracts with persistent state management. See Also ​ Overview : Return to the main SDK documentation Solidity Storage Layout : Official Solidity documentation Type Conversions : Solidity to Rust type mappings Solidity Compatible Storage Overview Storage Types and Layout 1. Simple Values (Primitive Types) 2. Mappings 3. Dynamic Arrays 4. Complex Types (Structs) Storage Optimization Direct Storage` StorageValueSolidity Generated API 1. Storage Packing 2. Initialization 3. Access Patterns Testing Storage Integration with Other Features See Also ## /fluentbase-sdk/codec On this page Codec ​ The Fluentbase codec system manages encoding and decoding of smart contract data. 💡 How to Use the Codec The Fluentbase SDK largely automates serialization. Your primary interaction with the codec is through the #[derive(Codec)] macro. Applying this to custom structs automatically integrates them into the SDK. 🎨 Summary The codec system is designed for flexibility and performance: no_std Compatible : Suitable for constrained environments without the standard library. Multiple Encoding Modes : Supports both EVM-compatible ( SolidityABI ) and WASM-optimized ( CompactABI ) formats. Automatic Implementation : Automatically implements serialization logic with #[derive(Codec)] . Rich Type Support : Handles primitives, collections ( Vec , HashMap ), tuples, and nested structs. Partial Decoding : Allows accessing specific parts of serialized data without fully decoding the entire stream, enhancing efficiency. Enabling Custom Types with #[derive(Codec)] ​ To integrate custom structs with Fluentbase serialization, derive the Codec trait: use fluentbase_sdk :: Codec ; // Adding `#[derive(Codec)]` makes this struct usable // in function parameters, return values, and storage. #[derive(Codec, Debug, Default, Clone, PartialEq)] pub struct UserProfile { pub name : String , pub level : u64 , pub is_active : bool , } Deriving Codec generates implementations of the core Encoder trait, making your structs recognizable across Fluentbase SDK components such as #[router] and solidity_storage! macros. Automatic Argument Encoding and Decoding ​ With SDK macros ( #[router] , #[client] , solidity_storage! , etc), encoding and decoding of arguments and return values occur transparently. Once you've added #[derive(Codec)] to your custom types, you can work with function arguments and returns as regular Rust types, without explicit encoding or decoding logic. Example of Manual Encoding and Decoding ​ Here's an explicit example of how encoding and decoding works under the hood: use fluentbase_sdk :: codec :: SolidityABI ; use bytes :: BytesMut ; let data = UserProfile { name : "Alice" . into ( ) , level : 42 , is_active : true , } ; let mut buf = BytesMut :: new ( ) ; SolidityABI :: encode ( & data , & mut buf , 0 ) . unwrap ( ) ; let decoded : UserProfile = SolidityABI :: decode ( & buf , 0 ) . unwrap ( ) ; assert_eq! ( data , decoded ) ; Encoding Modes ​ The codec provides multiple encoding strategies ("modes") tailored to specific use cases. SDK macros ( #[router] , #[client] ) automatically select the appropriate mode based on their configuration. SolidityABI (Default for EVM) ​ Primary mode for compatibility with EVM, Solidity, Ethereum wallets, and tools like Ethers.js. Byte Order : Big-endian Alignment : 32-byte word alignment Dynamic Types : Uses offsets for types like String , Bytes , and Vec<T> CompactABI ("Fluent" Mode) ​ WASM-optimized format for performance and smaller payloads within Fluentbase. Byte Order : Little-endian Alignment : 4-byte alignment Dynamic Types : Compact headers for dynamic types SolidityPackedABI ​ Mimics Solidity's abi.encodePacked for tightly packed data. Purpose : Typically used for creating unique hashes Rules : Sequential encoding without padding Supports only static-sized types Troubleshooting ​ Common Issues ​ "Type doesn't implement Codec" Ensure the macro is derived on custom types: #[derive(Codec, Debug, Clone, PartialEq)] struct MyType { field : U256 , } Mode mismatch between router and client Ensure matching modes: #[router(mode = "solidity" )] #[client(mode = "solidity" )] Large struct encoding failures For large types, consider splitting them into smaller structs: // Too large #[derive(Codec)] struct LargeType { /* too many fields */ } // Better approach #[derive(Codec)] struct Part1 { /* fewer fields */ } #[derive(Codec)] struct Part2 { /* fewer fields */ } ⚠️ Important Notes Determinism ​ Encoded binaries are non-deterministic; intended only for parameter passing. Encoding order of non-primitive fields affects data layout, but decoding remains consistent. Order Sensitivity ​ The sequence of encoding operations matters, especially for non-primitive types, influencing the final binary layout. Automation with SDK Macros ​ The #[router] and #[client] macros automate codec interactions by generating helper structs for each function ( ...Call , ...Return ), responsible for: Calculating the 4-byte function selector Encoding arguments into a byte payload Decoding payloads into Rust types This automation connects high-level Rust code seamlessly to low-level serialization processes. 🎨 Summary For most smart contract development: Derive Codec on custom types. Choose mode = "solidity" for EVM compatibility. Choose mode = "fluent" for optimized Rust communication (non-EVM). Let router, storage, and client macros manage encoding. See Also ​ Router System : Parameter handling with codec Storage System : Codec's role in storage Client Generation : Codec for cross-contract calls SDK Overview : Main SDK documentation Codec Implementation : Technical details Codec Enabling Custom Types with #[derive(Codec)] Automatic Argument Encoding and Decoding Example of Manual Encoding and Decoding Encoding Modes SolidityABI (Default for EVM) CompactABI ("Fluent" Mode) SolidityPackedABI Troubleshooting Common Issues Determinism Order Sensitivity Automation with SDK Macros See Also ## /fluentbase-sdk/client On this page Client Generation ​ The client generation system creates type-safe client code for interacting with Fluentbase smart contracts. It automatically generates client structs and methods from trait definitions, handling parameter encoding, contract calls, and result decoding. This enables seamless interaction with deployed contracts while maintaining type safety and consistency with the contract interface. 🧱 Prerequisite This documentation assumes you've already built contracts using the Router System . Clients are generated from trait definitions that match your contract's router interface. 🎨 Summary Client generation bridges the gap between contract interfaces and contract usage. When you have a contract deployed on the network, you need a way to call its methods from other contracts or external applications. The client system: Takes a trait definition that matches your contract's interface Generates a client struct with methods for each trait method Handles all encoding/decoding automatically Provides type-safe contract calls with proper parameter validation Manages gas, value, and addressing transparently Basic Usage ​ Defining a Client Interface ​ Start by defining a trait that matches your target contract's interface: use fluentbase_sdk :: { derive :: client , Address , SharedAPI , U256 , } ; #[client(mode = "solidity" )] trait TokenInterface { #[function_id( "balanceOf(address)" )] fn balance_of ( & self , owner : Address ) -> U256 ; #[function_id( "transfer(address,uint256)" )] fn transfer ( & mut self , to : Address , amount : U256 ) -> bool ; #[function_id( "approve(address,uint256)" )] fn approve ( & mut self , spender : Address , amount : U256 ) -> bool ; #[function_id( "allowance(address,address)" )] fn allowance ( & self , owner : Address , spender : Address ) -> U256 ; #[function_id( "transferFrom(address,address,uint256)" )] fn transfer_from ( & mut self , from : Address , to : Address , amount : U256 ) -> bool ; } Using the Generated Client ​ The macro generates a client struct named {TraitName}Client : use fluentbase_sdk :: { basic_entrypoint , derive :: { router , Contract } , Address , SharedAPI , U256 , } ; #[derive(Contract)] struct DeFiContract < SDK > { sdk : SDK , } impl < SDK : SharedAPI > DeFiContract < SDK > { pub fn deploy ( & self ) { // Deployment logic } pub fn swap_tokens ( & mut self , token_a : Address , token_b : Address , amount : U256 ) -> bool { // Create a client for token interactions let mut token_client = TokenInterfaceClient :: new ( self . sdk . clone ( ) ) ; // Check balance of token A let user = self . sdk . context ( ) . contract_caller ( ) ; let balance = token_client . balance_of ( token_a , // Contract address to call U256 :: zero ( ) , // No ETH to send with call 50000 , // Gas limit user // Function parameter: owner address ) ; if balance < amount { return false ; } // Approve this contract to spend tokens let approval_success = token_client . approve ( token_a , // Contract address U256 :: zero ( ) , // No ETH to send 50000 , // Gas limit self . sdk . context ( ) . contract_address ( ) , // Spender (this contract) amount // Amount to approve ) ; if ! approval_success { return false ; } // Transfer tokens from user to this contract let transfer_success = token_client . transfer_from ( token_a , // Contract address U256 :: zero ( ) , // No ETH to send 50000 , // Gas limit user , // From address self . sdk . context ( ) . contract_address ( ) , // To address (this contract) amount // Amount to transfer ) ; transfer_success } } basic_entrypoint! ( DeFiContract ) ; Generated Client Methods ​ For each trait method, the client generates a corresponding method. All generated client methods follow a consistent signature pattern: Contract Address ( Address ): The target contract to call ETH Value ( U256 ): How much ETH to send with the call (usually U256::zero() for view methods) Gas Limit ( u64 ): Maximum gas to use for the call Original Parameters : The actual function parameters from your trait definition This pattern ensures that every client call includes the necessary metadata for contract interaction while maintaining the original function signature for the actual parameters. For the example above: impl < SDK : SharedAPI > TokenInterfaceClient < SDK > { // For view methods (using &self) pub fn balance_of ( & self , contract_address : Address , // Target contract value : U256 , // ETH to send (usually zero for view methods) gas_limit : u64 , // Gas limit for the call owner : Address , // Original method parameter ) -> U256 { // Original return type // Generated implementation: // 1. Encode parameters using the codec system // 2. Make contract call with proper selector // 3. Decode return value // 4. Return typed result } // For state-changing methods (using &mut self) pub fn transfer ( & mut self , contract_address : Address , value : U256 , gas_limit : u64 , to : Address , amount : U256 , ) -> bool { // Similar encoding, calling, and decoding process } } Advanced Usage Patterns ​ Complex Data Types ​ The client system handles complex types automatically when they implement the Codec trait (see Codec documentation ): use fluentbase_sdk :: codec :: Codec ; #[derive(Codec, Debug, Clone, PartialEq)] pub struct VotingConfig { pub threshold : U256 , pub voting_period : u64 , pub required_quorum : U256 , } #[derive(Codec, Debug, Clone, PartialEq)] pub struct Proposal { pub id : U256 , pub title : String , pub description : String , pub targets : Vec < Address > , pub values : Vec < U256 > , } #[client(mode = "solidity" )] trait GovernanceInterface { #[function_id( "getConfig()" )] fn get_config ( & self ) -> VotingConfig ; #[function_id( "propose(string,string,address[],uint256[])" )] fn propose ( & mut self , title : String , description : String , targets : Vec < Address > , values : Vec < U256 > , ) -> U256 ; // Returns proposal ID #[function_id( "getProposal(uint256)" )] fn get_proposal ( & self , proposal_id : U256 ) -> Proposal ; #[function_id( "vote(uint256,bool)" )] fn vote ( & mut self , proposal_id : U256 , support : bool ) -> bool ; } // Usage in a contract impl < SDK : SharedAPI > MyContract < SDK > { pub fn create_proposal ( & mut self , gov_contract : Address ) -> U256 { let mut gov_client = GovernanceInterfaceClient :: new ( self . sdk . clone ( ) ) ; // Get current governance configuration let config = gov_client . get_config ( gov_contract , U256 :: zero ( ) , 100000 , ) ; println! ( "Governance threshold: {}" , config . thre
프로젝트로 돌아가기