- Basic knowledge of Dart/Flutter
- An API Key from the Console
Step 1: Set Up Your Project
Create a new project folder and initialize it using Flutter:Step 2: Hello, World!
Open your Flutter project and update the defaultmain.dart file in your app’s lib dir.
Step 3: Set Up Dependencies:
Install the FuseBox Wallet SDK by running the command with Flutter:pubspec.yaml (and run an implicit dart pub get):
main.dart file.
Step 4: SWAP Implementation
The app’s basic functionality is to swap from one token to another, in this first example, from FUSE to USDC. The method is:swapTokens method takes in three parameters: inputToken, outputToken and inputAmount. It then performs the conversion and, if successful, returns the UserOperation Hash.
Copy the code below where the SWAP functionality is hardcoded and paste it into the main.dart file.
WALLET_PRIVATE_KEY and the YOUR_PUBLIC_API_KEY with your EOA Keys and API Keys.
Code Breakdown
_TokenSwapScreenState Class
_TokenSwapScreenState is a state class associated with TokenSwapScreen. It contains two member variables: _isLoading to track the loading state and _swapStatus to display the status of the token swap operation.
_swapTokens Method
_swapTokens is an asynchronous method for performing the token swap operation. We set _isLoading to true to indicate that the operation is in progress. We initialize credentials and Fuse SDK using provided private and public API keys. nativeTokenAddress and usdcTokenAddress represent the native and USDC token addresses, respectively.
Perform Token Swap
try block using fuseSDK.swapTokens(). We set the _swapStatus based on the result of the operation. The result contains userOpHash, which is printed to the console. If an error occurs during the operation, we update _swapStatus with the error message. Finally, we set _isLoading to false to indicate that the operation is complete.
UI Build Method
build method, we return a Scaffold widget, which provides the basic structure for the screen. The AppBar contains the title ‘Token Swap’. The body consists of a Center widget containing a Column with a CircularProgressIndicator or an ElevatedButton based on the _isLoading state. Below the button, we display the _swapStatus using a Text widget.
Save the file. Run the application using the command
BONUS SECTION
The next step is a bonus step to improve the User Experience, and we will update the code to include a Dropdown for selecting currencies and an input field to specify a particular amount. Update theTokenSwapScreenState by adding a _formKey for handling Form events, and a controller _amountController and update the _swapTokens:
InputAmount to take the value from amount
body component to include the Dropdown: