Fluent 백서

Fluent

원문

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

t256 ( & self ) -> U256 ; fn rust_int256 ( & self ) -> I256 ; fn rust_address ( & self ) -> Address ; fn rust_bytes ( & self ) -> Bytes ; fn rust_bytes32 ( & self ) -> B256 ; fn rust_bool ( & self ) -> bool ; } #[router(mode = "solidity" )] impl < SDK : SharedAPI > RouterAPI for ROUTER < SDK > { // ERC-20 with Fluent SDK example: // https://github.com/fluentlabs-xyz/fluentbase/blob/devel/contracts/examples/erc20/lib.rs #[function_id( "rustString()" )] fn rust_string ( & self ) -> String { let string_test = "Hello" . to_string ( ) ; return string_test ; } #[function_id( "rustUint256()" )] fn rust_uint256 ( & self ) -> U256 { let uint256_test = U256 :: from ( 10 ) ; return uint256_test ; } #[function_id( "rustInt256()" )] fn rust_int256 ( & self ) -> I256 { // Declare Signed variables in alloy.rs: // https://docs.rs/alloy-primitives/latest/alloy_primitives/struct.Signed.html#method.from_dec_str let int256_test = I256 :: unchecked_from ( - 10 ) ; return int256_test ; } #[function_id( "rustAddress()" )] fn rust_address ( & self ) -> Address { let address_test : Address = address! ( "d8da6bf26964af9d7eed9e03e53415d37aa96045" ) ; // vitalik.eth 0xd8da6bf26964af9d7eed9e03e53415d37aa96045 return address_test ; } #[function_id( "rustBytes()" )] fn rust_bytes ( & self ) -> Bytes { let bytes_test = Bytes :: from ( "FLUENT" ) ; return bytes_test ; } #[function_id( "rustBytes32()" )] fn rust_bytes32 ( & self ) -> B256 { let bytes256_test = b256! ( "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" ) ; return bytes256_test ; } #[function_id( "rustBool()" )] fn rust_bool ( & self ) -> bool { let bool_test = true ; return bool_test ; } } impl < SDK : SharedAPI > ROUTER < SDK > { fn deploy ( & self ) { // any custom deployment logic here } } basic_entrypoint! ( ROUTER ) ; Detailed Code Explanation 1. #![cfg_attr(target_arch = "wasm32", no_std)] ​ This line is a compiler directive. It specifies that if the target architecture is wasm32 (WebAssembly 32-bit), the code should be compiled without the standard library ( no_std ). This is necessary for WebAssembly, which doesn't have a full standard library available. 2. extern crate alloc; and extern crate fluentbase_sdk; ​ These lines declare external crates (libraries) that the code depends on. alloc is a core library that provides heap allocation functionality. fluentbase_sdk is the SDK provided by Fluent for writing contracts. 3. use alloc::string::{String, ToString}; ​ This line imports the String and ToString types from the alloc crate. This is necessary because the standard std library, which normally includes these, is not available in no_std environments. 4. use fluentbase_sdk::{ basic_entrypoint, derive::{router, function_id, Contract}, SharedAPI }; ​ This line imports various items from the fluentbase_sdk crate: basic_entrypoint is a macro for defining the main entry point of the contract. router and function_id are macros for routing function calls and defining function signatures. Contract Trait enabling contract functionality. SharedAPI is a trait that abstracts the API shared between different environments. 5. #[derive(Contract)] struct ROUTER; ​ This line defines a struct named ROUTER and derives a contract implementation for it. The ROUTER struct will implement the logic for our contract. 6. pub trait RouterAPI { fn greeting(&self) -> String; } ​ This defines a trait named RouterAPI with a single method greeting . This method returns a String . 7. #[router(mode = "solidity")] impl<SDK: SharedAPI> RouterAPI for ROUTER<SDK> { ... } ​ This block implements the RouterAPI trait for the ROUTER struct. The #[router(mode = "solidity")] attribute indicates that this implementation is for a Solidity-compatible router. Inside the Implementation: #[function_id("greeting()"] specifies the function signature in Solidity syntax. This tells the router how to call this function from Solidity. fn greeting<SDK: SharedAPI>(&self) -> String { "Hello".to_string() } is the implementation of the greeting method, which simply returns the string "Hello". 8. impl<SDK: SharedAPI> ROUTER<SDK> { fn deploy(&self) { // any custom deployment logic here } } ​ This block provides an additional method deploy for the ROUTER struct. This method can include custom deployment logic. Currently, it's an empty placeholder. 9. basic_entrypoint!(ROUTER); ​ This macro invocation sets up the ROUTER struct as the main entry point for the contract. It handles necessary boilerplate code for contract initialization and invocation. Summary ​ This Rust code defines a smart contract that will be compiled to WebAssembly. The contract implements a single function greeting that returns the string "Hello". The contract is designed to be called from a Solidity environment, showcasing interoperability between different virtual machines. The basic_entrypoint! macro ties everything together, making ROUTER the entry point for the contract. 1.3 Build the Wasm Project ​ Generate the WASM binary file with: gblend build ⚠️ Warning Note: the first build might take a few minutes and should take a few seconds after the first run. We will deploy the compiled Rust contract with the WASM binary file later in this guide. ⚠️ Warning Note: to update Rust crate fluentbase-sdk if there are issues: # From src/rust-evm-test/ cargo clean cargo update -p fluentbase-sdk Next Up ​ In the following step you'll switch to the Solidity part of the blended project. You've now got the Rust functions the Solidity contract can call, time to implement the calling contract. Step 1: Start Rust Contract 1.1 Project Initialisation 1.2 Write the Rust Smart Contract with Fluentbase SDK Full Contract Source Code 1.3 Build the Wasm Project Next Up ## /developer-guides/building-a-blended-app/start-solidity-contract On this page Step 2: Start Solidity Contract ​ This guide is based off of the template blended application in this Github repo . Solidity Contract with Interface ​ Solidity interfaces are useful for calling external contracts that might have different compiler versions. For example: new protocols might use more recent Solidity compiler versions for contracts while wanting to use WETH9.sol . This can be done using an ERC-20 interface such as IERC20.sol to avoid Solidity compiler errors from using incompatible Solidity compiler versions. In this context, a Solidity interface is used to call an external Rust contract based on its method name and types that were defined in step 1. 2.1 Define the Interface ​ First off, we need to define interface that corresponds to the RouterAPI trait that was defined in step 1 in the Rust contract. For reference: pub trait RouterAPI { // Make sure type interfaces are defined here or else there will be a compiler error. fn rust_string ( & self ) -> String ; fn rust_uint256 ( & self ) -> U256 ; fn rust_int256 ( & self ) -> I256 ; fn rust_address ( & self ) -> Address ; fn rust_bytes ( & self ) -> Bytes ; fn rust_bytes32 ( & self ) -> B256 ; fn rust_bool ( & self ) -> bool ; } The Soldity interface then becomes: interface IRustEvmTypes { // Make sure type interfaces are defined here or else there will be a compiler error. function rustString ( ) external view returns ( string memory ) ; function rustUint256 ( ) external view returns ( uint256 ) ; function rustInt256 ( ) external view returns ( int256 ) ; function rustAddress ( ) external view returns ( address ) ; function rustBytes ( ) external view returns ( bytes memory ) ; function rustBytes32 ( ) external view returns ( bytes32 ) ; function rustBool ( ) external view returns ( bool ) ; } You could then add this interface to the Solidity file with the contract or import it from a separate file but ... 💡 gblend is your friend While manually defining and adding the imported interface works, gblend improves the developer's UX by making it readily available as a build artifact when running gblend build on the Rust contract that defines the trait. So one can just import the interface in a Solidity contract like so: // Import the generated interface import "../out/IRustEvmTypes.wasm/interface.sol" ; 2.2 Write the Solidity Contract ​ All that you need to do now, is write the Solidity contract which: Imports the auto-generated interface from the Rust contract Calls each Rust function and returns the results Handles different data types (string, uint256, int256, address, bytes, bytes32, bool) Shows how Solidity can seamlessly interact with Rust/WASM contracts Create a new Solidity contract FluentEvmRustTypes.sol in the src/ folder: touch src/FluentEvmRustTypes.sol And copy the following contract: // SPDX-License-Identifier: MIT pragma solidity 0.8 .30 ; // Solidity interface automatically generated with shell command `gblend build`. import { IRustEvmTypes } from "../out/RustEvmTypes.wasm/interface.sol" ; contract FluentEvmRustTypes { IRustEvmTypes public immutable RUST_EVM_TYPES ; constructor ( address fluentRustAddress ) { RUST_EVM_TYPES = IRustEvmTypes ( fluentRustAddress ) ; } function getRustUint256 ( ) external returns ( uint256 ) { uint256 rustUint256 = RUST_EVM_TYPES . rustUint256 ( ) ; return rustUint256 ; } function getRustInt256 ( ) external returns ( int256 ) { int256 rustInt256 = RUST_EVM_TYPES . rustInt256 ( ) ; return rustInt256 ; } function getRustAddress ( ) external returns ( address ) { address rustAddress = RUST_EVM_TYPES . rustAddress ( ) ; return rustAddress ; } function getRustBytes ( ) external returns ( bytes memory ) { bytes memory rustBytes = RUST_EVM_TYPES . rustBytes ( ) ; return rustBytes ; } function getRustBytes32 ( ) external returns ( bytes32 ) { bytes32 rustBytes32 = RUST_EVM_TYPES . rustBytes32 ( ) ; return rustBytes32 ; } function getRustBool ( ) external returns ( bool ) { bool rustBool = RUST_EVM_TYPES . rustBool ( ) ; return rustBool ; } function getRustString ( ) external returns ( string memory ) { string memory rustString = RUST_EVM_TYPES . rustString ( ) ; return string ( abi . encodePacked ( rustString , " World" ) ) ; } } 2.3 Compile the Contract(s) ​ Next, we can again compile the contracts wit gblend , now both the Solidity and Rust contracts: gblend build 🏆 Best Practice: use gblend to blend Technically, for this step you could also use forge build to compile the Solidity contracts, as is shown in the Soldiity dev guide . However, this only works because you've already generated the Rust contract build artifacts in step 1. As you are importing the interface from the Rust contract in your Solidity contract, these need to be present beforehand. Hence it is recommended to always use gblend when building blended applications. Next Up ​ In the following step you'll deploy the (compiled) contracts to Fluent Testnet. Step 2: Start Solidity Contract Solidity Contract with Interface 2.1 Define the Interface 2.2 Write the Solidity Contract 2.3 Compile the Contract(s) Next Up ## /developer-guides/building-a-blended-app/deploy-blended-contracts On this page Step 3: Deploy Blended Contracts ​ This guide is based off of the template blended application in this Github repo . Now that both Solidity and Rust contracts have been created and compiled, the next step is to deploy (and verify) them. 3.1 Deploy the Rust Contract with gblend ​ First you'll deploy the Rust contract ( the order matters! ): gblend create RustEvmTypes.wasm \ --rpc-url https://rpc.testnet.fluent.xyz \ --private-key $PRIVATE_KEY \ --broadcast \ --verify \ --wasm \ --verifier blockscout \ --verifier-url https://testnet.fluentscan.xyz/api/ Be sure to capture the address the contract is deployed to and save it somewhere. Note that you'll need to add your private key as environment variable in a .env file and then run source .env . 🚨 Danger Never use private keys linked to accounts with real funds, always use development wallets! 3.2 Deploy the Solidity Contract ​ Now you can deploy the Solidity contract. As mentioned above, the order matters because you'll need the address of the deployed Rust contract ( RustTypesTest.wasm ). gblend create src/FluentEvmRustTypes.sol:FluentEvmRustTypes \ --constructor-args-path src/solidityConstructor/FluentEvmRustTypes.txt \ --rpc-url https://rpc.testnet.fluent.xyz \ --private-key $PRIVATE_KEY \ --broadcast \ --verify \ --verifier blockscout \ --verifier-url https://testnet.fluentscan.xyz/api/ 3.3 Check with Block Explorer ​ Go to the Fluent testnet block explorer and look for the contract address the contracts were deployed to. Check Verification Status ​ The deployment commands up top, gblend create , included additional arguments to verify the contracts immediately on deployment. To check if the contracts did indeed get verified, find the contract at its address, and navigate to the Contract tab. It should have a green checkmark next to its name if the verification was successful. 🔍 Patience is a virtue Note that it may take up to 3 minutes to verify the contract, this is not out of the ordinary so don't send new requests too frequently. Did the contract verification fail? Try again with these commands: # WASM contract verification gblend verify-contract < RustEvmTypesAddress > RustEvmTypes.wasm \ --wasm \ --verifier blockscout \ --verifier-url https://testnet.fluentscan.xyz/api/ # Solidity contract verification gblend verify-contract < FluentEvmRustTypesAddress > FluentEvmRustTypes \ --verifier blockscout \ --verifier-url https://testnet.fluentscan.xyz/api/ \ --constructor-args < RustEvmTypesAddress > If this still does not solve the issue, check out the troubleshooting guide . Read the Solidity function return values ​ With the Solidity contract verified on Blockscout, we are now able to test the Solidity and Rust contract Blended App. With the verified Solidity contract on Blockscout, go to: Contract > Read/Write contract > Read and click on the different function names. You should see values that match the correct type for that function name, confirming your Blended App is setup between Solidity and Rust. 🎉 Next Up ​ While Fluentscan's web interface is good for quick testing, you'll likely want to interact with your blended application from some client environment. The last step in this guide explains how to integrate it using libraries like ethers.js. Step 3: Deploy Blended Contracts 3.1 Deploy the Rust Contract with gblend 3.2 Deploy the Solidity Contract 3.3 Check with Block Explorer Check Verification Status Read the Solidity function return values Next Up ## /developer-guides/building-a-blended-app/integrate-blended-contracts On this page Step 4: Integrate Blended Contracts ​ This guide is based off of the template blended application in this Github repo . Once a blended application is deployed, you can use popular libraries such as ethers.js to integrate your application into user interfaces such as a frontend website. 🔍 Rust x Ethereum Maxi? If you prefer Rust development, consider using alloy-rs instead of ethers.js for a more native Rust experience when interacting with blended contracts. 4.1 Add ethers.js to the Foundry project ​ Add ethers.js as a dependency to your Foundry project. Note that you'll first have to initialize a npm package (as this is not by default available in Foundry nor gblend projects). mkdir js-client && cd js-client && \ npm init -y && \ npm i ethers@5.7.2 && \ touch rust.js solidity.js && \ cd .. 4.2 Test ethers.js script to call Solidity contract ​ Add the following script to the js-client/solidity.js file that was created in the step above. This script calls the FluentEvmRustTypes.sol contract, which then externally calls the Rust contract functions. Note: update string variable contractAddress with your deployed FluentEvmRustTypes contract address. const ethers = require ( "ethers" ) // npm i ethers@5.7.2 https://github.com/smartcontractkit/full-blockchain-solidity-course-js/discussions/5139#discussioncomment-5444517 const rpcURL = "https://rpc.testnet.fluent.xyz/" // Your RPC URL goes here const provider = new ethers . providers . JsonRpcProvider ( rpcURL ) const contractAddress = "<INPUT_SOLIDITY_CONTRACT_ADDRESS_HERE>" const contractABI = [ { "inputs" : [ { "internalType" : "address" , "name" : "FluentRustAddress" , "type" : "address" } ] , "stateMutability" : "nonpayable" , "type" : "constructor" } , { "inputs" : [ ] , "name" : "rustTypesTest" , "outputs" : [ { "internalType" : "contractIRustTypesTest" , "name" : "" , "type" : "address" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustAddress" , "outputs" : [ { "internalType" : "address" , "name" : "" , "type" : "address" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustBool" , "outputs" : [ { "internalType" : "bool" , "name" : "" , "type" : "bool" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustBytes" , "outputs" : [ { "internalType" : "bytes" , "name" : "" , "type" : "bytes" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustBytes32" , "outputs" : [ { "internalType" : "bytes32" , "name" : "" , "type" : "bytes32" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustInt256" , "outputs" : [ { "internalType" : "int256" , "name" : "" , "type" : "int256" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustString" , "outputs" : [ { "internalType" : "string" , "name" : "" , "type" : "string" } ] , "stateMutability" : "view" , "type" : "function" } , { "inputs" : [ ] , "name" : "getRustUint256" , "outputs" : [ { "internalType" : "uint256" , "name" : "" , "type" : "uint256" } ] , "stateMutability" : "view" , "type" : "function" } ] const contractDeployed = new ethers . Contract ( contractAddress , contractABI , provider ) ; let fluent_sepolia_chain_id = 20994 ; testSolidityContractRead ( ) async function testSolidityContractRead ( ) { const connectedNetworkObject = await provider . getNetwork ( ) ; const chainIdConnected = connectedNetworkObject . chainId ; console . log ( "chainIdConnected: " + chainIdConnected ) if ( chainIdConnected != fluent_sepolia_chain_id ) { console . log ( "RPC endpoint not connected to Fluent Sepolia (chainId: " + fluent_sepolia_chain_id + ")." ) ; console . log ( "Switch to Fluent Sepolia then try again." ) ; return ; } const rustTypesTestContractAddress = await contractDeployed . rustTypesTest ( ) console . log ( "rustTypesTestContractAddress: " + rustTypesTestContractAddress ) const rustString = await contractDeployed . getRustString ( ) console . log ( "rustString: " + rustString ) const rustUint256 = await contractDeployed . getRustUint256 ( ) console . log ( "rustUint256: " + rustUint256 ) const rustInt256 = await contractDeployed . getRustInt256 ( ) console . log ( "rustInt256: " + rustInt256 ) const rustAddress = await contractDeployed . getRustAddress ( ) console . log ( "rustAddress: " + rustAddress ) const rustBytes = await contractDeployed . getRustBytes ( ) console . log ( "rustBytes: " + rustBytes ) const rustBytes32 = await contractDeployed . getRustBytes32 ( ) console . log ( "rustBytes32: " + rustBytes32 ) const rustBool = await contractDeployed . getRustBool ( ) console . log ( "rustBool: " + rustBool ) } This script should return the expected value
프로젝트로 돌아가기