bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 13쪽 중 11쪽
shold
)
;
// Create a new proposal
let
proposal_id
=
gov_client
.
propose
(
gov_contract
,
U256
::
zero
(
)
,
150000
,
// Higher gas for complex operation
"Increase Treasury"
.
to_string
(
)
,
"Proposal to increase treasury allocation by 10%"
.
to_string
(
)
,
vec!
[
Address
::
ZERO
]
,
// Target contracts
vec!
[
U256
::
from
(
1000000
)
]
,
// Values
)
;
proposal_id
}
}
Batch Operations
Create wrapper methods for common patterns:
impl
<
SDK
:
SharedAPI
>
TokenInterfaceClient
<
SDK
>
{
// Custom convenience method
pub
fn
safe_transfer_with_allowance_check
(
&
mut
self
,
token
:
Address
,
from
:
Address
,
to
:
Address
,
amount
:
U256
,
gas_limit
:
u64
,
)
->
Result
<
bool
,
String
>
{
// Check allowance first
let
allowance
=
self
.
allowance
(
token
,
U256
::
zero
(
)
,
gas_limit
,
from
,
self
.
sdk
.
context
(
)
.
contract_address
(
)
,
)
;
if
allowance
<
amount
{
return
Err
(
"Insufficient allowance"
.
to_string
(
)
)
;
}
// Perform transfer
let
success
=
self
.
transfer_from
(
token
,
U256
::
zero
(
)
,
gas_limit
,
from
,
to
,
amount
,
)
;
Ok
(
success
)
}
}
Multi-Contract Interactions
Combine multiple clients for complex DeFi operations:
#[client(mode =
"solidity"
)]
trait
UniswapV2Router
{
#[function_id(
"swapExactTokensForTokens(uint256,uint256,address[],address,uint256)"
)]
fn
swap_exact_tokens_for_tokens
(
&
mut
self
,
amount_in
:
U256
,
amount_out_min
:
U256
,
path
:
Vec
<
Address
>
,
to
:
Address
,
deadline
:
U256
,
)
->
Vec
<
U256
>
;
}
impl
<
SDK
:
SharedAPI
>
DeFiAggregator
<
SDK
>
{
pub
fn
execute_swap
(
&
mut
self
,
router
:
Address
,
token_in
:
Address
,
token_out
:
Address
,
amount
:
U256
,
)
->
bool
{
let
mut
token_client
=
TokenInterfaceClient
::
new
(
self
.
sdk
.
clone
(
)
)
;
let
mut
router_client
=
UniswapV2RouterClient
::
new
(
self
.
sdk
.
clone
(
)
)
;
// Approve router to spend tokens
let
approved
=
token_client
.
approve
(
token_in
,
U256
::
zero
(
)
,
50000
,
router
,
amount
,
)
;
if
!
approved
{
return
false
;
}
// Execute swap
let
path
=
vec!
[
token_in
,
token_out
]
;
let
amounts
=
router_client
.
swap_exact_tokens_for_tokens
(
router
,
U256
::
zero
(
)
,
200000
,
// Higher gas for complex operation
amount
,
U256
::
one
(
)
,
// Minimum output
path
,
self
.
sdk
.
context
(
)
.
contract_address
(
)
,
U256
::
from
(
u64
::
MAX
)
,
// Deadline
)
;
!
amounts
.
is_empty
(
)
}
}
Encoding Modes
Solidity Mode (Default)
Full EVM compatibility with standard ABI encoding, matching the encoding used in
router Solidity mode
:
#[client(mode =
"solidity"
)]
trait
StandardInterface
{
// Compatible with web3.js, ethers.js, and Solidity contracts
}
Fluent Mode
Optimized for WASM environments:
#[client(mode =
"fluent"
)]
trait
OptimizedInterface
{
// Smaller payloads, faster processing
// Not compatible with standard EVM tools
}
🏆
Best Practice
Match Interface Exactly
: Ensure your trait matches the target contract's interface precisely
Use Appropriate Gas Limits
: Different operations require different amounts of gas
Handle Failures
: Always check return values for state-changing operations
Reuse Clients
: Create once and reuse for multiple calls to the same contract type
Type Safety
: Leverage Rust's type system - incorrect parameters won't compile
Documentation
: Document expected behavior and gas requirements
Error Handling
Implement proper error handling for production code:
enum
SwapError
{
InsufficientBalance
,
ApprovalFailed
,
SwapFailed
,
}
impl
<
SDK
:
SharedAPI
>
SafeDeFi
<
SDK
>
{
pub
fn
safe_swap
(
&
mut
self
,
params
:
SwapParams
)
->
Result
<
U256
,
SwapError
>
{
let
client
=
TokenInterfaceClient
::
new
(
self
.
sdk
.
clone
(
)
)
;
// Check balance
let
balance
=
client
.
balance_of
(
/* params */
)
;
if
balance
<
params
.
amount
{
return
Err
(
SwapError
::
InsufficientBalance
)
;
}
// Continue with swap...
Ok
(
U256
::
zero
(
)
)
}
}
Gas Optimization
Batch multiple reads when possible:
impl
<
SDK
:
SharedAPI
>
PortfolioManager
<
SDK
>
{
pub
fn
get_portfolio_value
(
&
self
,
tokens
:
Vec
<
Address
>
,
user
:
Address
)
->
U256
{
let
client
=
TokenInterfaceClient
::
new
(
self
.
sdk
.
clone
(
)
)
;
let
mut
total
=
U256
::
zero
(
)
;
for
token
in
tokens
{
let
balance
=
client
.
balance_of
(
token
,
U256
::
zero
(
)
,
30000
,
// Lower gas for view function
user
,
)
;
total
+=
balance
;
}
total
}
}
Client Reuse
Store clients as fields for contracts that frequently interact with the same protocols:
#[derive(Contract)]
struct
YieldOptimizer
<
SDK
>
{
sdk
:
SDK
,
// Can't store clients as fields due to SDK ownership
// Instead, create helper methods
}
impl
<
SDK
:
SharedAPI
>
YieldOptimizer
<
SDK
>
{
fn
token_client
(
&
self
)
->
TokenInterfaceClient
<
SDK
>
{
TokenInterfaceClient
::
new
(
self
.
sdk
.
clone
(
)
)
}
pub
fn
compound_rewards
(
&
mut
self
,
token
:
Address
,
amount
:
U256
)
->
bool
{
// Reuse the same client instance within the method
let
mut
client
=
self
.
token_client
(
)
;
let
balance
=
client
.
balance_of
(
token
,
U256
::
zero
(
)
,
30000
,
self
.
sdk
.
context
(
)
.
contract_address
(
)
)
;
if
balance
>=
amount
{
client
.
transfer
(
token
,
U256
::
zero
(
)
,
50000
,
Address
::
ZERO
,
amount
)
}
else
{
false
}
}
}
Testing Clients
Test client interactions using the testing framework:
#[cfg(test)]
mod
tests
{
use
super
::
*
;
use
fluentbase_sdk_testing
::
HostTestingContext
;
#[test]
fn
test_client_interaction
(
)
{
let
sdk
=
HostTestingContext
::
default
(
)
;
let
client
=
TokenInterfaceClient
::
new
(
sdk
.
clone
(
)
)
;
// Mock the token contract behavior
// Test client calls
// Verify results
}
}
🎨
Summary
The client generation system provides:
Type-safe contract interactions
with automatic encoding/decoding
Seamless integration
with the router and storage systems
Support for complex data types
through the codec system
Multiple encoding modes
for different compatibility requirements
Direct Solidity integration
for easy migration and interoperability
Use clients to build sophisticated DeFi protocols, governance systems, and multi-contract applications while maintaining type safety and code clarity.
See Also
Router System
: Understand how to build contracts that clients can interact with
Storage System
: Learn about accessing storage from client calls
Codec System
: Deep dive into encoding/decoding mechanisms
Overview
: Return to the main SDK documentation
Client Generation
Basic Usage
Defining a Client Interface
Using the Generated Client
Generated Client Methods
Advanced Usage Patterns
Complex Data Types
Batch Operations
Multi-Contract Interactions
Encoding Modes
Solidity Mode (Default)
Fluent Mode
Error Handling
Gas Optimization
Client Reuse
Testing Clients
See Also
## /developer-guides/smart-contracts
On this page
Get started building on Fluent
Fluent allows developers to write smart contracts in Rust (using
Fluentbase SDK
that compile down to WASM) or Solidity. Each language has its unique advantages and syntax, enabling developers to choose the best fit for their projects.
This guide will walk you through creating a
HelloWorld
contract in each of these languages and deploying it to Fluent.
Get Started
To simplify the setup process, your project can be bootstrapped using Fluent’s scaffold tooling
gblend
, which is a Foundry forge wrapper. This tool automates the creation of the project structure and necessary directories for smart contract development.
🔍
Install gblend
Ensure you've got
gblend
installed by following the
installation instructions
. Check by running:
gblend
--version
And see if you get an output.
Smart Contracts on Fluent Guides
Building on Fluent is supported in these languages as of today (or build
blended applications
):
Smart Contracts on
Solidity
Smart Contracts on
Rust
Smart Contracts on
Solidity
Smart Contracts on
Rust
Get started building on Fluent
Get Started
Smart Contracts on Fluent Guides
## /developer-guides/smart-contracts/rust
On this page
Building in Rust
To benefit maximally from the efficiency of WASM based smart contracts, you can use the
Fluentbase SDK
to build your Rust contracts.
For Rust smart contracts, any
no_std
compatible crate (e.g.,
rand
,
alloc
) can be used. Standard library crates are not supported. Verified libraries can be found on
crates.io
.
🧱
Prerequisite
Before getting started, make sure to install either of the following:
Clang and CMake
: Install these if they are not already on your system.
For macOS users, LLVM can be installed via Homebrew:
brew
install
llvm
gblend
: find the installation instructions
here
Start a new Project
To create a project, run the following in your terminal:
gblend init my-project
This will install a simple template that expands Foundry's
counter
default example. The project when using the command above, has the following structure:
my-project/
├── src/
│ ├── BlendedCounter.sol # Solidity contract
│ └── power-calculator/ # Rust/WASM module
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
├── test/ # Forge tests
├── script/ # Deployment scripts
└── foundry.toml # Configuration
In this guide, you'll only be focusing on Rust contracts so you can remove:
rm
src/BlendedCounter.sol
rm
script/BlendedCounter.s.sol
rm
test/BlendedCounter.t.sol
and rename
power-calculator/
to something more appropriate in this case,
greeting/
.
Also rename the package name in
Cargo.toml
to
greeting
.
The Main Contract File:
lib.rs
Replace the
lib.rs
file located in the
src/greeting/src
folder with the following (representative of the structure for any Rust smart contract):
lib.rs
// 1. Set the target to wasm32 and enable no_std for compatibility.
// no_std is required since WebAssembly's minimal runtime lacks support for Rust’s standard library.
#![cfg_attr(target_arch =
"wasm32"
, no_std)]
// 2. Import FluentBase SDK
extern
crate
fluentbase_sdk
;
use
fluentbase_sdk
::
{
basic_entrypoint
,
derive
::
Contract
,
SharedAPI
}
;
// 3. Define Contract Struct with SDK: Acts as the core of the contract’s logic.
#[derive(Contract)]
struct
GREETING
<
SDK
>
{
sdk
:
SDK
,
}
impl
<
SDK
:
SharedAPI
>
GREETING
<
SDK
>
{
// 4. Deployment Logic: Placeholder for setup during deployment.
fn
deploy
(
&
mut
self
)
{
// Add any custom deployment logic here
}
// 5. Core Contract Logic: writes "Hello, World" message to output.
fn
main
(
&
mut
self
)
{
self
.
sdk
.
write
(
"Hello, World"
.
as_bytes
(
)
)
;
}
}
// 6. Set Entry Point: Connects GREETING struct to the WASM runtime.
basic_entrypoint!
(
GREETING
)
;
This snippet shows how simple it is to interact with the Fluent VM: just call the SDK, initialize your contract, add the functions, and, if needed, define a custom deployment process.
Compiling the Rust Smart Contract
Understanding the deployment process starts with comprehending the role of
gblend
, which compiles Rust code into rWasm and generates the necessary binaries that will be embedded in a tx for deployment.
gblend build
⚠️
Warning
Note: the first build might take a few minutes and should take a few seconds after the first run.
Executing this command compiles the code and generates build artifacts in the
out
directory.
⚠️
Warning
Update Rust crate
fluentbase-sdk
in the contract package if there are issues:
# from src/greeting/
cargo
clean
cargo
update
-p
fluentbase-sdk
Deploying the Contract
To deploy contract, use gblend cli:
Testnet
Devnet
gblend create Greeting.wasm
\
--rpc-url https://rpc.testnet.fluent.xyz
\
--private-key
$PRIVATE_KEY
\
--broadcast
\
--verify
\
--wasm
\
--verifier
blockscout
\
--verifier-url https://testnet.fluentscan.xyz/api/
gblend create Greeting.wasm
\
--rpc-url https://rpc.devnet.fluent.xyz
\
--private-key
$PRIVATE_KEY
\
--broadcast
\
--verify
\
--wasm
\
--verifier
blockscout
\
--verifier-url https://devnet.fluentscan.xyz/api/
Upon successful deployment, the receipt of your deployment transaction will be displayed, confirming the smart contract deployment on Fluent using the Fluentbasse SDK.
To view your deployed Fluent contract, navigate to the Fluent block explorer. From there, you can input your contract address to explore your deployed contract.
🎨
Summary
When building Rust contracts with Fluentbase SDK, you can use the
gblend
CLI to build, deploy and verify your contracts.
Building in Rust
Start a new Project
The Main Contract File:
lib.rs
Compiling the Rust Smart Contract
Deploying the Contract
## /developer-guides/smart-contracts/solidity
On this page
Building in Solidity
Fluent is an EVM-compatible L2 that allows developers to deploy familiar applications written in Solidity. Note however that many of the unique technical value proposition lies in so called
blended execution
, but nevertheless migration of existing Solidity based code bases is possible on Fluent.
🧱
Prerequisite
Before getting started, make sure to install either of the following:
gblend
: find the installation instructions
here
Foundry
: find the installation instructions
in the official Foundry docs
If you're starting a new project on Fluent Network, we recommend using
gblend
over regular Foundry forge, even if you have no immediate plans of making your application
blended
by adding Fluentbase Rust contracts. Your application might still interact with another application that
is
blended which may lead to issues relying on regular forge.
Nevertheless, as the instructions to build Solidity contracts with
gblend
can be found in
the
gblend
usage docs
, this guide will use regular forge for demonstration purposes.
Start Foundry Project
Generate Foundry file in your current directory
forge init
In the
src
folder, create a new file called
SimpleStorage.sol
and copy the simple contract below:
// SPDX-License-Identifier: MIT
pragma
solidity
0.8
.28
;
contract
SimpleStorage
{
uint256
public
storedData
;
//Do not set 0 manually it wastes gas!
event
setEvent
(
)
;
function
set
(
uint256
x
)
public
{
storedData
=
x
;
emit
setEvent
(
)
;
}
}
Deploy and Verify
Testnet
Devnet
forge create SimpleStorage
\
--private-key
$PRIVATE_KEY
\
--rpc-url https://rpc.testnet.fluent.xyz/
\
--broadcast
\
--verify
\
--verifier
blockscout
\
--verifier-url https://testnet.fluentscan.xyz/api/
forge create SimpleStorage
\
--private-key
$PRIVATE_KEY
\
--rpc-url https://rpc.devnet.fluent.xyz/
\
--broadcast
\
--verify
\
--verifier
blockscout
\
--verifier-url https://devnet.fluentscan.xyz/api/
💡
Tip
Blockscout verification might fail during deployment.
If this happens, verify the contract after it is deployed.
Make sure to capture the contract address from the output of the deployment step above.
Verify Contract Already Deployed
Replace variable
<contract_address>
in the commands below with the actual contract address from the deployment step above and run:
Testnet
Devnet
forge verify-contract
\
--rpc-url https://rpc.testnet.fluent.xyz/
\
<
contract_address
>
\
SimpleStorage
\
--verifier
blockscout
\
--verifier-url https://testnet.fluentscan.xyz/api/
forge verify-contract
\
--rpc-url https://rpc.devnet.fluent.xyz/
\
<
contract_address
>
\
SimpleStorage
\
--verifier
blockscout
\
--verifier-url https://devnet.fluentscan.xyz/api/
🎨
Summary
Even though Fluent Network has an innovative
blended execution
engine, it is still an EVM-compatible L2. This means that Solidity contracts can be deployed and verified on Fluent Network just like on any other EVM-compatible network using Foundry and other familiar tools.
Building in Solidity
Start Foundry Project
Deploy and Verify
Verify Contract Already Deployed
## /developer-guides/building-a-blended-app/quickstart
On this page
Quickstart
The guide here goes step by step to explain in detail each part of a template blended application:
the Solidity contract
the Fluentbase Rust Contract
an ethers.js client to interact with those
and gives the instruction to build and deploy the contracts using Fluent's
gblend
tooling
.
💡
Prefer the quickest of starts?
If you don't want the explanation and simply want to deploy as soon as possible, you can follow the reduced instructions in the
Github repo
.
Quickstart
## /developer-guides/building-a-blended-app/start-rust-contract
On this page
Step 1: Start Rust Contract
This guide is based off of the template blended application in this
Github repo
.
🧱
Prerequisite
Make sure the
gblend
tool is installed
to continue. Check with:
gblend
--version
1.1 Project Initialisation
To start the project, you'll follow similar steps as in the
Rust contract dev guide
(only with different names).
# Create a project called my-blended-template
gblend init my-blended-template
You can do some housekeeping by removing default files:
rm
src/BlendedCounter.sol
rm
script/BlendedCounter.s.sol
rm
test/BlendedCounter.t.sol
In this step of the guide we'll focus on the Rust contract, which can be found at
src/power-calculator
.
Rename the Rust contract folder and package:
rename
src/power-calculator
folder to
src/rust-evm-test
mv
src/power-calculator src/rust-evm-test
rename package name in
src/rust-evm-test/Cargo.toml
to "rust-evm-test"
awk
'
BEGIN { in_package = 0 }
/^\[package\]/ { in_package = 1; print; next }
/^\[.*\]/ { in_package = 0 }
in_package && /^name *= *".*"/ { print "name = \"rust-evm-test\""; next }
{ print }
'
src/rust-evm-test/Cargo.toml
>
tmp.toml
&&
mv
tmp.toml src/rust-evm-test/Cargo.toml
1.2 Write the Rust Smart Contract with Fluentbase SDK
Now you'll move on to writing a Rust smart contract with Fluentbase SDK. Find the contract source file in
src/rust-evm-test/src/lib.rs
. This is the file you'll edit...
🎨
What you'll be doing
This contract demonstrates how to use Fluentbase SDK to enable interoperability between Solidity and Rust (WASM) contracts, allowing Solidity contracts to call Rust functions with compatible data types.
Effectively, we provide router functionality. Please also refer to the
Fluentbase router macro documentation
for more detailed educational materials.
In the new contract, you'll define a struct for the contract which will derive the Contract trait:
#[derive(Contract)]
struct
ROUTER
<
SDK
>
{
sdk
:
SDK
,
}
and define a
RouterAPI
trait to define Solidity interfaces. The contract then needs to implement the trait and define the Solidity function implementations.
pub
trait
RouterAPI
{
// Define function signatures that correspond to Solidity interface you'll call from.
...
}
...
impl
<
SDK
:
SharedAPI
>
RouterAPI
for
ROUTER
<
SDK
>
{
// Here you'll implement the methods defined in the trait
...
}
Full Contract Source Code
Paste the following source code in
lib.rs
and examine it closely (there a collapsible compenent with detailed explanation below the code block).
#![cfg_attr(target_arch =
"wasm32"
, no_std)]
extern
crate
alloc
;
use
alloc
::
string
::
{
String
,
ToString
}
;
use
fluentbase_sdk
::
{
basic_entrypoint
,
derive
::
{
router
,
Contract
}
,
SharedAPI
,
U256
,
// alloy Solidity type for uint256
I256
,
// alloy Solidity type for int256
Address
,
// alloy Solidity type for address
address
,
// alloy Solidity marco to define values for type Address
Bytes
,
// alloy Solidity type for bytes
B256
,
// alloy Solidity type for bytes32
b256
// alloy Solidity marco to define values for type B256
}
;
#[derive(Contract)]
struct
ROUTER
<
SDK
>
{
sdk
:
SDK
,
}
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_uin프로젝트로 돌아가기