@onflow/fcl-react-native
Overview
The Flow fcl-react-native library provides a set of tools for developers to build applications on the Flow blockchain.
Installation
You can install the @onflow/fcl-react-native package using npm or yarn:
_10npm install @onflow/fcl-react-native
Or using yarn:
_10yarn add @onflow/fcl-react-native
Requirements
- Node.js 14.x or later
Importing
You can import the entire package:
_10import * as fcl from "@onflow/fcl-react-native"
Or import specific functions:
_10import { functionName } from "@onflow/fcl-react-native"
Configuration
FCL has a mechanism that lets you configure various aspects of FCL. When you move from one instance of the Flow Blockchain to another (Local Emulator to Testnet to Mainnet) the only thing you should need to change for your FCL implementation is your configuration.
Setting Configuration Values
Values only need to be set once. We recommend doing this once and as early in the life cycle as possible. To set a configuration value, the put
method on the config
instance needs to be called, the put
method returns the config
instance so they can be chained.
Alternatively, you can set the config by passing a JSON object directly.
_13import * as fcl from '@onflow/fcl';_13_13fcl_13 .config() // returns the config instance_13 .put('foo', 'bar') // configures "foo" to be "bar"_13 .put('baz', 'buz'); // configures "baz" to be "buz"_13_13// OR_13_13fcl.config({_13 foo: 'bar',_13 baz: 'buz',_13});
Getting Configuration Values
The config
instance has an asynchronous get
method. You can also pass it a fallback value.
_15import * as fcl from '@onflow/fcl';_15_15fcl.config().put('foo', 'bar').put('woot', 5).put('rawr', 7);_15_15const FALLBACK = 1;_15_15async function addStuff() {_15 var woot = await fcl.config().get('woot', FALLBACK); // will be 5 -- set in the config before_15 var rawr = await fcl.config().get('rawr', FALLBACK); // will be 7 -- set in the config before_15 var hmmm = await fcl.config().get('hmmm', FALLBACK); // will be 1 -- uses fallback because this isnt in the config_15_15 return woot + rawr + hmmm;_15}_15_15addStuff().then((d) => console.log(d)); // 13 (5 + 7 + 1)
Common Configuration Keys
Name | Example | Description |
---|---|---|
accessNode.api (required) | https://rest-testnet.onflow.org | API URL for the Flow Blockchain Access Node you want to be communicating with. See all available access node endpoints here. |
app.detail.title | Cryptokitties | Your applications title, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. |
app.detail.icon | https://fcl-discovery.onflow.org/images/blocto.png | Url for your applications icon, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. |
app.detail.description | Cryptokitties is a blockchain game | Your applications description, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. |
app.detail.url | https://cryptokitties.co | Your applications url, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. |
challenge.handshake | DEPRECATED | Use discovery.wallet instead. |
discovery.authn.endpoint | https://fcl-discovery.onflow.org/api/testnet/authn | Endpoint for alternative configurable Wallet Discovery mechanism. |
discovery.wallet (required) | https://fcl-discovery.onflow.org/testnet/authn | Points FCL at the Wallet or Wallet Discovery mechanism. |
discovery.wallet.method | IFRAME/RPC , POP/RPC , TAB/RPC , HTTP/POST , or EXT/RPC | Describes which service strategy a wallet should use. |
fcl.limit | 100 | Specifies fallback compute limit if not provided in transaction. Provided as integer. |
flow.network (recommended) | testnet | Used in conjunction with stored interactions and provides FCLCryptoContract address for testnet and mainnet . Possible values: local , testnet , mainnet . |
walletconnect.projectId | YOUR_PROJECT_ID | Your app's WalletConnect project ID. See WalletConnect Cloud to obtain a project ID for your application. |
walletconnect.disableNotifications | false | Optional flag to disable pending WalletConnect request notifications within the application's UI. |
Using Contracts in Scripts and Transactions
Address Replacement
Configuration keys that start with 0x
will be replaced in FCL scripts and transactions, this allows you to write your script or transaction Cadence code once and not have to change it when you point your application at a difference instance of the Flow Blockchain.
_27import * as fcl from '@onflow/fcl';_27_27fcl.config().put('0xFungibleToken', '0xf233dcee88fe0abe');_27_27async function myScript() {_27 return fcl_27 .send([_27 fcl.script`_27 import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration_27_27 access(all) fun main() { /* Rest of the script goes here */ }_27 `,_27 ])_27 .then(fcl.decode);_27}_27_27async function myTransaction() {_27 return fcl_27 .send([_27 fcl.transaction`_27 import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration_27_27 transaction { /* Rest of the transaction goes here */ }_27 `,_27 ])_27 .then(fcl.decode);_27}
Example
_14import * as fcl from '@onflow/fcl';_14_14fcl_14 .config()_14 .put('flow.network', 'testnet')_14 .put('walletconnect.projectId', 'YOUR_PROJECT_ID')_14 .put('accessNode.api', 'https://rest-testnet.onflow.org')_14 .put('discovery.wallet', 'https://fcl-discovery.onflow.org/testnet/authn')_14 .put('app.detail.title', 'Test Harness')_14 .put('app.detail.icon', 'https://i.imgur.com/r23Zhvu.png')_14 .put('app.detail.description', 'A test harness for FCL')_14 .put('app.detail.url', 'https://myapp.com')_14 .put('service.OpenID.scopes', 'email email_verified name zoneinfo')_14 .put('0xFlowToken', '0x7e60df042a9c0868');
Using flow.json
for Contract Imports
A simpler and more flexible way to manage contract imports in scripts and transactions is by using the config.load
method in FCL. This lets you load contract configurations from a flow.json
file, keeping your import syntax clean and allowing FCL to pick the correct contract addresses based on the network you're using.
1. Define Your Contracts in flow.json
Here’s an example of a flow.json
file with aliases for multiple networks:
_11{_11 "contracts": {_11 "HelloWorld": {_11 "source": "./cadence/contracts/HelloWorld.cdc",_11 "aliases": {_11 "testnet": "0x1cf0e2f2f715450",_11 "mainnet": "0xf8d6e0586b0a20c7"_11 }_11 }_11 }_11}
source
: Points to the contract file in your project.aliases
: Maps each network to the correct contract address.
2. Configure FCL
Load the flow.json
file and set up FCL to use it:
_10import { config } from '@onflow/fcl';_10import flowJSON from '../flow.json';_10_10config({_10 'flow.network': 'testnet', // Choose your network, e.g., testnet or mainnet_10 'accessNode.api': 'https://rest-testnet.onflow.org', // Access node for the network_10 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`, // Wallet discovery_10}).load({ flowJSON });
With this setup, FCL will automatically use the correct contract address based on the selected network (e.g., testnet
or mainnet
).
3. Use Contract Names in Scripts and Transactions
After setting up flow.json
, you can import contracts by name in your Cadence scripts or transactions:
_10import "HelloWorld"_10_10access(all) fun main(): String {_10 return HelloWorld.sayHello()_10}
FCL replaces "HelloWorld"
with the correct address from the flow.json
configuration.
Note: Don’t store private keys in your
flow.json
. Instead, keep sensitive keys in a separate,.gitignore
-protected file.
API Reference
This section contains documentation for all of the functions and namespaces in the fcl-react-native package.
- account - Retrieve any account from Flow network's latest block or from a specified block...
- arg - A utility builder to be used with fcl.args[...] to create FCL supported...
- args - A utility builder to be used with other builders to pass in arguments with a...
- atBlockHeight - A builder function that returns a partial interaction to a block at a specific...
- atBlockId - A builder function that returns a partial interaction to a block at a specific...
- authenticate
- authorization - Creates an authorization function for use in transactions. An authorization...
- authorizations - A utility builder to set the authorizations on a transaction. Authorizations...
- block - Query the network for block by id, height or get the latest block. Block ID is...
- build - A builder function that creates an interaction from an array of builder...
- cadence - Creates a template function
- cdc - Creates a template function
- config - Sets the config
- createSignableVoucher - Creates a signable voucher object from an interaction for signing purposes. A...
- decode - Decodes the response from 'fcl.send()' into the appropriate JSON representation...
- display - Adds 0x to address if not already present
- events - Subscribes to Flow blockchain events in real-time. This function provides a way...
- getAccount - A builder function that returns the interaction to get an account by address....
- getBlock - A builder function that returns the interaction to get the latest block. Use...
- getBlockHeader - A builder function that returns the interaction to get a block header. A block...
- getChainId - Gets the chain ID if its set, otherwise gets the chain ID from the access node
- getCollection - A builder function that returns a collection containing a list of transaction...
- getEvents - A builder function that returns the interaction to get events. Events are...
- getEventsAtBlockHeightRange - A builder function that returns all instances of a particular event (by name)...
- getEventsAtBlockIds - A builder function that returns all instances of a particular event (by name)...
- getNetworkParameters - A builder function that returns the interaction to get network parameters....
- getNodeVersionInfo - A builder function for the Get Node Version Info interaction. Creates an...
- getTransaction - A builder function that returns the interaction to get a transaction by id....
- getTransactionStatus - A builder function that returns the status of transaction. The transaction id...
- invariant
- isBad - Checks if an interaction has a failed status.
- isOk - Checks if an interaction has a successful status.
- limit - A utility builder to set the compute limit on a transaction. The compute limit...
- logIn
- nodeVersionInfo - Retrieve version information from the connected Flow Access Node. This function...
- param - Legacy function for setting a single parameter on an interaction.
- params - Legacy function for setting parameters on an interaction.
- payer - A builder function that adds payer account(s) to a transaction. Every...
- ping - A builder function that creates a ping interaction to test connectivity to the...
- pipe - Async pipe function to compose interactions. The pipe function is the foundation...
- pluginRegistry - Global plugin registry instance for managing FCL plugins. This registry handles...
- proposer - A builder function that adds the proposer to a transaction. The proposer is...
- query - Allows you to submit scripts to query the blockchain.
- reauthenticate
- ref - A builder function that sets the reference block for a transaction. The...
- sansPrefix - Removes 0x from address if present
- script - A builder function that creates a script interaction. Scripts allow you to write...
- send - Sends arbitrary scripts, transactions, and requests to Flow. This method...
- serialize - Serializes a Flow transaction or script to a JSON-formatted signable voucher...
- ServiceDiscovery (namespace) - Namespace containing ServiceDiscovery utilities
- signUp
- subscribe - Subscribe to real-time data from the Flow blockchain and automatically decode...
- subscribeEvents - Subscribe to events with the given filter and parameters. Creates a subscription...
- subscribeRaw - Subscribe to a topic without decoding the data. This function creates a raw...
- transaction - A template builder to use a Cadence transaction for an interaction. FCL "mutate"...
- tx - Creates a transaction monitor that provides methods for tracking and subscribing...
- unauthenticate
- useServiceDiscovery (namespace) - Namespace containing useServiceDiscovery utilities
- useServiceDiscovery.getAsyncStorage
- validator - A builder function that adds a validator to a transaction. Validators are...
- verifyUserSignatures - Verify a valid signature/s for an account on Flow.
- voucherIntercept - A builder function that intercepts and modifies a voucher. This function is...
- voucherToTxId - Converts a voucher object to a transaction ID. This function computes the...
- why - Returns the reason for an interaction failure.
- withPrefix - Adds 0x to address if not already present