Flow Client Library (FCL) API Reference
For release updates, see the repo
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. |
app.detail.icon | https://fcl-discovery.onflow.org/images/blocto.png | Url for your applications icon, can be requested by wallets and other services. |
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. Read more on discovery |
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 , canarynet , testnet , mainnet . |
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.
_24import * as fcl from "@onflow/fcl"_24_24fcl.config()_24 .put("0xFungibleToken", "0xf233dcee88fe0abe")_24_24async function myScript () {_24 return fcl.send([_24 fcl.script`_24 import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration_24_24 pub fun main() { /* Rest of the script goes here */ }_24 `_24 ]).then(fcl.decode)_24}_24_24async function myTransaction () {_24 return fcl.send([_24 fcl.transaction`_24 import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration_24_24 transaction { /* Rest of the transaction goes here */ }_24 `_24 ]).then(fcl.decode)_24}
Example
_10import * as fcl from "@onflow/fcl"_10_10fcl.config()_10 .put("flow.network", "testnet")_10 .put("accessNode.api", "https://rest-testnet.onflow.org")_10 .put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn")_10 .put("app.detail.title", "Test Harness")_10 .put("app.detail.icon", "https://i.imgur.com/r23Zhvu.png")_10 .put("service.OpenID.scopes", "email email_verified name zoneinfo")_10 .put("0xFlowToken", "0x7e60df042a9c0868")
Using Flow.json
A simpler way to import contracts in scripts and transactions is to use the config.load
method to ingest your contracts from your flow.json
file. This keeps the import syntax unified across tools and lets FCL figure out which address to use for what network based on the network provided in config. To use config.load
you must first import your flow.json
file and then pass it to config.load
as a parameter.
_10import { config } from '@onflow/fcl'_10import flowJSON from '../flow.json'_10_10config({_10 'flow.network': 'testnet',_10 'accessNode.api': 'https://rest-testnet.onflow.org',_10 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`,_10}).load({ flowJSON })
Let's say your flow.json
file looks like this:
_10{_10 "contracts": {_10 "HelloWorld": "cadence/contracts/HelloWorld.cdc"_10 }_10}
Then in your scripts and transactions, all you have to do is:
_10import "HelloWorld"
FCL will automatically replace the contract name with the address for the network you are using.
Note: never put private keys in your
flow.json
. You should use the key/location syntax to separate your keys into a separate git ignored file.
Wallet Interactions
These methods allows dapps to interact with FCL compatible wallets in order to authenticate the user and authorize transactions on their behalf.
⚠️These methods are async.
authenticate
⚠️This method can only be used in web browsers.
Calling this method will authenticate the current user via any wallet that supports FCL. Once called, FCL will initiate communication with the configured discovery.wallet
endpoint which lets the user select a wallet to authenticate with. Once the wallet provider has authenticated the user, FCL will set the values on the current user object for future use and authorization.
Note
⚠️discovery.wallet
value must be set in the configuration before calling this method. See FCL Configuration.
📣 The default discovery endpoint will open an iframe overlay to let the user choose a supported wallet.
Usage
_10import * as fcl from "@onflow/fcl";_10fcl_10 .config()_10 .put("accessNode.api", "https://rest-testnet.onflow.org")_10 .put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn");_10// anywhere on the page_10fcl.authenticate();
Note
⚠️ authenticate
can also take a service returned from discovery with fcl.authenticate({ service })
.
unauthenticate
⚠️This method can only be used in web browsers.
Logs out the current user and sets the values on the current user object to null.
Note
⚠️The current user must be authenticated first.
Usage
_10import * as fcl from "@onflow/fcl";_10fcl.config().put("accessNode.api", "https://rest-testnet.onflow.org");_10// first authenticate to set current user_10fcl.authenticate();_10// ... somewhere else & sometime later_10fcl.unauthenticate();_10// fcl.currentUser.loggedIn === null
reauthenticate
⚠️This method can only be used in web browsers.
A convenience method that calls fcl.unauthenticate()
and then fcl.authenticate()
for the current user.
Note
⚠️The current user must be authenticated first.
Usage
_10import * as fcl from "@onflow/fcl";_10// first authenticate to set current user_10fcl.authenticate();_10// ... somewhere else & sometime later_10fcl.reauthenticate();_10// logs out user and opens up login/sign-up flow
signUp
⚠️This method can only be used in web browsers.
A convenience method that calls and is equivalent to fcl.authenticate()
.
logIn
⚠️This method can only be used in web browsers.
A convenience method that calls and is equivalent to fcl.authenticate()
.
authz
A convenience method that produces the needed authorization details for the current user to submit transactions to Flow. It defines a signing function that connects to a user's wallet provider to produce signatures to submit transactions.
📣 You can replace this function with your own authorization function if needed.
Returns
Type | Description |
---|---|
AuthorizationObject | An object containing the necessary details from the current user to authorize a transaction in any role. |
Usage
Note: The default values for proposer
, payer
, and authorizations
are already fcl.authz
so there is no need to include these parameters, it is shown only for example purposes. See more on signing roles.
_22import * as fcl from "@onflow/fcl";_22// login somewhere before_22fcl.authenticate();_22// once logged in authz will produce values_22console.log(fcl.authz);_22// prints {addr, signingFunction, keyId, sequenceNum} from the current authenticated user._22_22const txId = await fcl.mutate({_22 cadence: `_22 import Profile from 0xba1132bc08f82fe2_22 _22 transaction(name: String) {_22 prepare(account: AuthAccount) {_22 account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)_22 }_22 }_22 `,_22 args: (arg, t) => [arg("myName", t.String)],_22 proposer: fcl.authz, // optional - default is fcl.authz_22 payer: fcl.authz, // optional - default is fcl.authz_22 authorizations: [fcl.authz], // optional - default is [fcl.authz]_22});
Current User
Holds the current user, if set, and offers a set of functions to manage the authentication and authorization of the user.
⚠️The following methods can only be used in web browsers.
currentUser.subscribe
The callback passed to subscribe will be called when the user authenticates and un-authenticates, making it easy to update the UI accordingly.
Arguments
Name | Type | |
---|---|---|
callback | function | The callback will be called with the current user as the first argument when the current user is set or removed. |
Usage
_24import React, { useState, useEffect } from "react";_24import * as fcl from "@onflow/fcl";_24_24export function AuthCluster() {_24 const [user, setUser] = useState({ loggedIn: null });_24 useEffect(() => fcl.currentUser.subscribe(setUser), []); // sets the callback for FCL to use_24_24 if (user.loggedIn) {_24 return (_24 <div>_24 <span>{user?.addr ?? "No Address"}</span>_24 <button onClick={fcl.unauthenticate}>Log Out</button> {/* once logged out in setUser(user) will be called */}_24 </div>_24 );_24 } else {_24 return (_24 <div>_24 <button onClick={fcl.logIn}>Log In</button>{" "}_24 {/* once logged in setUser(user) will be called */}_24 <button onClick={fcl.signUp}>Sign Up</button> {/* once signed up, setUser(user) will be called */}_24 </div>_24 );_24 }_24}
currentUser.snapshot
Returns the current user object. This is the same object that is set and available on fcl.currentUser.subscribe(callback)
.
Usage
_10// returns the current user object_10const user = fcl.currentUser.snapshot();_10_10// subscribes to the current user object and logs to console on changes_10fcl.currentUser.subscribe(console.log);
currentUser.authenticate
Equivalent to fcl.authenticate
.
currentUser.unauthenticate
Equivalent to fcl.unauthenticate
.
currentUser.authorization
Equivalent to fcl.authz
currentUser.signUserMessage
A method to use allowing the user to personally sign data via FCL Compatible Wallets/Services.
⚠️ This method requires the current user's wallet to support a signing service endpoint. Currently, only Blocto is compatible with this feature by default.
Arguments
Name | Type | Description |
---|---|---|
message | string (required) | A hexadecimal string to be signed |
Returns
Type | Description |
---|---|
Array | An Array of CompositeSignatures: signature |
Usage
_10import * as fcl from "@onflow/fcl"_10_10export const signMessage = async () => {_10 const MSG = Buffer.from("FOO").toString("hex")_10 try {_10 return await currentUser.signUserMessage(MSG)_10 } catch (error) {_10 console.log(error)_10 }_10}
Discovery
discovery
Discovery abstracts away code so that developers don't have to deal with the discovery of Flow compatible wallets, integration, or authentication. Using discovery
from FCL allows dapps to list and authenticate with wallets while having full control over the UI. Common use cases for this are login or registration pages.
(Alternatively, if you don't need control over your UI you can continue to use the discovery.wallet
config value documented in the Quickstart for the simplest configuration.)
⚠️The following methods can only be used in web browsers.
Note
⚠️discovery.authn.endpoint
value must be set in the configuration before calling this method. See FCL Configuration.
Suggested Configuration
Environment | Example |
---|---|
Mainnet | https://fcl-discovery.onflow.org/api/authn |
Testnet | https://fcl-discovery.onflow.org/api/testnet/authn |
If the Discovery endpoint is set in config, then you can iterate through authn services and pass the chosen service to authenticate to authenticate a user.
Usage
_21import "./config"_21import { useState, useEffect } from "react"_21import * as fcl from "@onflow/fcl"_21_21function Component() {_21 const [wallets, setWallets] = useState([])_21 useEffect(() => fcl.discovery.authn.subscribe(res => setWallets(res.results)), [])_21_21 return (_21 <div>_21 {wallets.map((wallet) => (_21 <button_21 key={wallet.provider.address}_21 onClick={() => fcl.authenticate({ service: wallet })}_21 >_21 Login with {wallet.provider.name}_21 </button>_21 ))}_21 </div>_21 )_21}
authn
More Configuration
By default, limited functionality services or services that require developer registration, like Ledger or Dapper Wallet, require apps to opt-in in order to display to users. To enable opt-in services in an application, use the discovery.authn.include
property in your configuration with a value of an array of services you'd like your app to opt-in to displaying for users.
_10_10import { config } from "@onflow/fcl"_10_10config({_10 "discovery.authn.endpoint": "https://fcl-discovery.onflow.org/api/testnet/authn", // Endpoint set to Testnet_10 "discovery.authn.include": ["0x9d2e44203cb13051"] // Ledger wallet address on Testnet set to be included_10})
Opt-In Wallet Addresses on Testnet and Mainnet
Service | Testnet | Mainnet |
---|---|---|
Dapper Wallet | 0x82ec283f88a62e65 | 0xead892083b3e2c6c |
Ledger | 0x9d2e44203cb13051 | 0xe5cd26afebe62781 |
For more details on wallets, view the service list here.
discovery.authn.snapshot()
Return a list of authn
services.
discovery.authn.subscribe(callback)
The callback sent to subscribe
will be called with a list of authn
services.
On-chain Interactions
📣 These methods can be used in browsers and NodeJS.
These methods allows dapps to interact directly with the Flow blockchain via a set of functions that currently use the Access Node API.
Query and Mutate Flow with Cadence
If you want to run arbitrary Cadence scripts on the blockchain, these methods offer a convenient way to do so without having to build, send, and decode interactions.
query
Allows you to submit scripts to query the blockchain.
Options
Pass in the following as a single object with the following keys.All keys are optional unless otherwise stated.
Key | Type | Description |
---|---|---|
cadence | string (required) | A valid cadence script. |
args | ArgumentFunction | Any arguments to the script if needed should be supplied via a function that returns an array of arguments. |
limit | number | Compute (Gas) limit for query. Read the documentation about computation cost for information about how computation cost is calculated on Flow. |
Returns
Type | Description |
---|---|
any | A JSON representation of the response. |
Usage
_16import * as fcl from "@onflow/fcl";_16_16const result = await fcl.query({_16 cadence: `_16 pub fun main(a: Int, b: Int, addr: Address): Int {_16 log(addr)_16 return a + b_16 }_16 `,_16 args: (arg, t) => [_16 arg(7, t.Int), // a: Int_16 arg(6, t.Int), // b: Int_16 arg("0xba1132bc08f82fe2", t.Address), // addr: Address_16 ],_16});_16console.log(result); // 13
Examples
mutate
Allows you to submit transactions to the blockchain to potentially mutate the state.
⚠️When being used in the browser, fcl.mutate
uses the built-in fcl.authz
function to produce the authorization (signatures) for the current user. When calling this method from Node.js, you will need to supply your own custom authorization function.
Options
Pass in the following as a single object with the following keys. All keys are optional unless otherwise stated.
Key | Type | Description |
---|---|---|
cadence | string (required) | A valid cadence transaction. |
args | ArgumentFunction | Any arguments to the script if needed should be supplied via a function that returns an array of arguments. |
limit | number | Compute (Gas) limit for query. Read the documentation about computation cost for information about how computation cost is calculated on Flow. |
proposer | AuthorizationFunction | The authorization function that returns a valid AuthorizationObject for the proposer role. |
Returns
Type | Description |
---|---|
string | The transaction ID. |
Usage
_16import * as fcl from "@onflow/fcl";_16// login somewhere before_16fcl.authenticate();_16_16const txId = await fcl.mutate({_16 cadence: `_16 import Profile from 0xba1132bc08f82fe2_16 _16 transaction(name: String) {_16 prepare(account: AuthAccount) {_16 account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)_16 }_16 }_16 `,_16 args: (arg, t) => [arg("myName", t.String)],_16});
Examples
verifyUserSignatures
(Deprecated)
Use fcl.AppUtils.verifyUserSignatures
AppUtils
AppUtils.verifyUserSignatures
A method allowing applications to cryptographically verify a message was signed by a user's private key/s. This is typically used with the response from currentUser.signUserMessage
.
Note
⚠️ fcl.config.flow.network
or options override is required to use this api. See FCL Configuration.
Arguments
Name | Type | Description |
---|---|---|
message | string (required) | A hexadecimal string |
compositeSignatures | Array (required) | An Array of CompositeSignatures |
opts | Object (optional) | opts.fclCryptoContract can be provided to override FCLCryptoContract address for local development |
Returns
Type | Description |
---|---|
Boolean | true if verified or false |
Usage
_10import * as fcl from "@onflow/fcl"_10_10const isValid = await fcl.AppUtils.verifyUserSignatures(_10 Buffer.from('FOO').toString("hex"),_10 [{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}],_10 {fclCryptoContract}_10)
Examples
AppUtils.verifyAccountProof
A method allowing applications to cryptographically prove that a user controls an on-chain account. During user authentication, some FCL compatible wallets will choose to support the FCL account-proof
service. If a wallet chooses to support this service, and the user approves the signing of message data, they will return account-proof
data and a signature(s) that can be used to prove a user controls an on-chain account.
See proving-authentication documentaion for more details.
⚠️ fcl.config.flow.network
or options override is required to use this api. See FCL Configuration.
Arguments
Name | Type | Description |
---|---|---|
appIdentifier | string (required) | A hexadecimal string |
accountProofData | Object (required) | Object with properties: address : string - A Flow account address. nonce : string - A random string in hexadecimal format (minimum 32 bytes in total, i.e 64 hex characters) signatures : Object[] - An array of composite signatures to verify |
opts | Object (optional) | opts.fclCryptoContract can be provided to overide FCLCryptoContract address for local development |
Returns
Type | Description |
---|---|
Boolean | true if verified or false |
Usage
_13import * as fcl from "@onflow/fcl"_13_13const accountProofData = {_13 address: "0x123",_13 nonce: "F0123"_13 signatures: [{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}],_13}_13_13const isValid = await fcl.AppUtils.verifyAccountProof(_13 "AwesomeAppId",_13 accountProofData,_13 {fclCryptoContract}_13)
Examples
Query and mutate the blockchain with Builders
In some cases, you may want to utilize pre-built interactions or build more complex interactions than what the fcl.query
and fcl.mutate
interface offer. To do this, FCL uses a pattern of building up an interaction with a combination of builders, resolving them, and sending them to the chain.
⚠️Recommendation: Unless you have a specific use case that require usage of these builders, you should be able to achieve most cases with
fcl.query({...options}
orfcl.mutate({...options})
send
Sends arbitrary scripts, transactions, and requests to Flow.
This method consumes an array of builders that are to be resolved and sent. The builders required to be included in the array depend on the interaction that is being built.
Note
⚠️Must be used in conjuction with fcl.decode(response)
to get back correct keys and all values in JSON.
Arguments
Name | Type | Description |
---|---|---|
builders | [Builders] | See builder functions. |
Returns
Type | Description |
---|---|
ResponseObject | An object containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values. |
Usage
_18import * as fcl from "@onflow/fcl";_18_18// a script only needs to resolve the arguments to the script_18const response = await fcl.send([fcl.script`${script}`, fcl.args(args)]);_18// note: response values are encoded, call await fcl.decode(response) to get JSON_18_18// a transaction requires multiple 'builders' that need to be resolved prior to being sent to the chain - such as setting the authorizations._18const response = await fcl.send([_18 fcl.transaction`_18 ${transaction}_18 `,_18 fcl.args(args),_18 fcl.proposer(proposer),_18 fcl.authorizations(authorizations),_18 fcl.payer(payer),_18 fcl.limit(9999),_18]);_18// note: response contains several values (Cad)
decode
Decodes the response from fcl.send()
into the appropriate JSON representation of any values returned from Cadence code.
Note
📣 To define your own decoder, see tutorial
.
Arguments
Name | Type | Description |
---|---|---|
response | ResponseObject | Should be the response returned from fcl.send([...]) |
Returns
Type | Description |
---|---|
any | A JSON representation of the raw string response depending on the cadence code executed. The return value can be a single value and type or an object with multiple types. |
Usage
_19import * as fcl from "@onflow/fcl";_19_19// simple script to add 2 numbers_19const response = await fcl.send([_19 fcl.script`_19 pub fun main(int1: Int, int2: Int): Int {_19 return int1 + int2_19 }_19 `,_19 fcl.args([_19 fcl.arg(1, fcl.t.Int),_19 fcl.arg(2, fcl.t.Int)_19 ]),_19]);_19_19const decoded = await fcl.decode(response);_19_19assert(3 === decoded);_19assert(typeof decoded === "number");
Builders
These methods fill out various portions of a transaction or script template in order to build, resolve, and send it to the blockchain. A valid populated template is referred to as an Interaction.
⚠️These methods must be used with fcl.send([...builders]).then(fcl.decode)
Query Builders
getAccount
A builder function that returns the interaction to get an account by address.
⚠️Consider using the pre-built interaction fcl.account(address)
if you do not need to pair with any other builders.
Arguments
Name | Type | Description |
---|---|---|
address | Address | Address of the user account with or without a prefix (both formats are supported). |
Returns after decoding
Type | Description |
---|---|
AccountObject | A JSON representation of a user account. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10// somewhere in an async function_10// fcl.account is the same as this function_10const getAccount = async (address) => {_10 const account = await fcl.send([fcl.getAccount(address)]).then(fcl.decode);_10 return account;_10};
getBlock
A builder function that returns the interaction to get the latest block.
📣 Use with fcl.atBlockId()
and fcl.atBlockHeight()
when building the interaction to get information for older blocks.
⚠️Consider using the pre-built interaction fcl.getblock(isSealed)
if you do not need to pair with any other builders.
Arguments
Name | Type | Default | Description |
---|---|---|---|
isSealed | boolean | false | If the latest block should be sealed or not. See block states. |
Returns after decoding
Type | Description |
---|---|
BlockObject | The latest block if not used with any other builders. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const latestSealedBlock = await fcl_10 .send([_10 fcl.getBlock(true), // isSealed = true_10 ])_10 .then(fcl.decode);
atBlockHeight
A builder function that returns a partial interaction to a block at a specific height.
⚠️Use with other interactions like fcl.getBlock()
to get a full interaction at the specified block height.
Arguments
Name | Type | Description |
---|---|---|
blockHeight | number | The height of the block to execute the interaction at. |
Returns
Type | Description |
---|---|
Partial Interaction | A partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount() . |
Usage
_10import * as fcl from "@onflow/fcl";_10_10await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode);
atBlockId
A builder function that returns a partial interaction to a block at a specific block ID.
⚠️Use with other interactions like fcl.getBlock()
to get a full interaction at the specified block ID.
Arguments
Name | Type | Description |
---|---|---|
blockId | string | The ID of the block to execute the interaction at. |
Returns
Type | Description |
---|---|
Partial Interaction | A partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount() . |
Usage
_10import * as fcl from "@onflow/fcl";_10_10await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode);
getBlockHeader
A builder function that returns the interaction to get a block header.
📣 Use with fcl.atBlockId()
and fcl.atBlockHeight()
when building the interaction to get information for older blocks.
Returns after decoding
Type | Description |
---|---|
BlockHeaderObject | The latest block header if not used with any other builders. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const latestBlockHeader = await fcl_10 .send([fcl.getBlockHeader()])_10 .then(fcl.decode);
getEventsAtBlockHeightRange
A builder function that returns all instances of a particular event (by name) within a height range.
⚠️The block range provided must be from the current spork.
⚠️The block range provided must be 250 blocks or lower per request.
Arguments
Name | Type | Description |
---|---|---|
eventName | EventName | The name of the event. |
fromBlockHeight | number | The height of the block to start looking for events (inclusive). |
toBlockHeight | number | The height of the block to stop looking for events (inclusive). |
Returns after decoding
Type | Description |
---|---|
[EventObject] | An array of events that matched the eventName. |
Usage
_11import * as fcl from "@onflow/fcl";_11_11const events = await fcl_11 .send([_11 fcl.getEventsAtBlockHeightRange(_11 "A.7e60df042a9c0868.FlowToken.TokensWithdrawn",_11 35580624,_11 35580624_11 ),_11 ])_11 .then(fcl.decode);
getEventsAtBlockIds
A builder function that returns all instances of a particular event (by name) within a set of blocks, specified by block ids.
⚠️The block range provided must be from the current spork.
Arguments
Name | Type | Description |
---|---|---|
eventName | EventName | The name of the event. |
blockIds | number | The ids of the blocks to scan for events. |
Returns after decoding
Type | Description |
---|---|
[EventObject] | An array of events that matched the eventName. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const events = await fcl_10 .send([_10 fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [_10 "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7",_10 "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f",_10 ]),_10 ])_10 .then(fcl.decode);
getCollection
A builder function that returns all a collection containing a list of transaction ids by its collection id.
⚠️The block range provided must be from the current spork. All events emitted during past sporks is current unavailable.
Arguments
Name | Type | Description |
---|---|---|
collectionID | string | The id of the collection. |
Returns after decoding
Type | Description |
---|---|
CollectionObject | An object with the id and a list of transactions within the requested collection. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const collection = await fcl_10 .send([_10 fcl.getCollection(_10 "cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5"_10 ),_10 ])_10 .then(fcl.decode);
getTransactionStatus
A builder function that returns the status of transaction in the form of a TransactionStatusObject.
⚠️The transactionID provided must be from the current spork.
📣 Considering subscribing to the transaction from fcl.tx(id)
instead of calling this method directly.
Arguments
Name | Type | Description |
---|---|---|
transactionId | string | The transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3 |
Returns after decoding
Returns
Type | Description |
---|---|
TransactionStatusObject | Object representing the result/status of a transaction |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const status = await fcl_10 .send([_10 fcl.getTransactionStatus(_10 "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"_10 ),_10 ])_10 .then(fcl.decode);
getTransaction
A builder function that returns a transaction object once decoded.
⚠️The transactionID provided must be from the current spork.
📣 Considering using fcl.tx(id).onceSealed()
instead of calling this method directly.
Arguments
Name | Type | Description |
---|---|---|
transactionId | string | The transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3 |
Returns after decoding
Returns
Type | Description |
---|---|
TransactionObject | An full transaction object containing a payload and signatures |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const tx = await fcl_10 .send([_10 fcl.getTransaction(_10 "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"_10 ),_10 ])_10 .then(fcl.decode);
getEvents
(Deprecated)
Use fcl.getEventsAtBlockHeightRange
or fcl.getEventsAtBlockIds
.
getLatestBlock
(Deprecated)
Use fcl.getBlock
.
getBlockById
(Deprecated)
Use fcl.getBlock
and fcl.atBlockId
.
getBlockByHeight
(Deprecated)
Use fcl.getBlock
and fcl.atBlockHeight
.
Utility Builders
These builders are used to compose interactions with other builders such as scripts and transactions.
⚠️Recommendation: Unless you have a specific use case that require usage of these builders, you should be able to achieve most cases with
fcl.query({...options}
orfcl.mutate({...options})
arg
A utility builder to be used with fcl.args[...]
to create FCL supported arguments for interactions.
Arguments
Name | Type | Description |
---|---|---|
value | any | Any value that you are looking to pass to other builders. |
type | FType | A type supported by Flow. |
Returns
Type | Description |
---|---|
ArgumentObject | Holds the value and type passed in. |
Usage
_15import * as fcl from "@onflow/fcl";_15_15await fcl_15 .send([_15 fcl.script`_15 pub fun main(a: Int, b: Int): Int {_15 return a + b_15 }_15 `,_15 fcl.args([_15 fcl.arg(5, fcl.t.Int), // a_15 fcl.arg(4, fcl.t.Int), // b_15 ]),_15 ])_15 .then(fcl.decode);
args
A utility builder to be used with other builders to pass in arguments with a value and supported type.
Arguments
Name | Type | Description |
---|---|---|
args | [Argument Objects] | An array of arguments that you are looking to pass to other builders. |
Returns
Type | Description |
---|---|
Partial Interaction | An interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. |
Usage
_15import * as fcl from "@onflow/fcl";_15_15await fcl_15 .send([_15 fcl.script`_15 pub fun main(a: Int, b: Int): Int {_15 return a + b_15 }_15 `,_15 fcl.args([_15 fcl.arg(5, fcl.t.Int), // a_15 fcl.arg(4, fcl.t.Int), // b_15 ]),_15 ])_15 .then(fcl.decode); // 9
Template Builders
⚠️Recommended: The following functionality is simplified by
fcl.query({...options}
orfcl.mutate({...options})
and is reccomended to use over the functions below.
script
A template builder to use a Cadence script for an interaction.
📣 Use with fcl.args(...)
to pass in arguments dynamically.
Arguments
Name | Type | Description |
---|---|---|
CODE | string | Should be valid Cadence script. |
Returns
Type | Description |
---|---|
Interaction | An interaction containing the code passed in. |
Usage
_10import * as fcl from "@onflow/fcl";_10_10const code = `_10 pub fun main(): Int {_10 return 5 + 4_10 }_10`;_10const answer = await fcl.send([fcl.script(code)]).then(fcl.decode);_10console.log(answer); // 9
transaction
A template builder to use a Cadence transaction for an interaction.
⚠️Must be used with fcl.payer
, fcl.proposer
, fcl.authorizations
to produce a valid interaction before sending to the chain.
📣 Use with fcl.args[...]
to pass in arguments dynamically.
Arguments
Name | Type | Description |
---|---|---|
CODE | string | Should be valid a Cadence transaction. |