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.
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.
1import * as fcl from "@onflow/fcl";23fcl4.config() // returns the config instance5.put("foo", "bar") // configures "foo" to be "bar"6.put("baz", "buz"); // configures "baz" to be "buz"78// OR910fcl.config({11foo: "bar",12baz: "buz",13});
The config
instance has an asynchronous get
method. You can also pass it a fallback value.
1import * as fcl from "@onflow/fcl";23fcl.config().put("foo", "bar").put("woot", 5).put("rawr", 7);45const FALLBACK = 1;67async function addStuff() {8var woot = await fcl.config().get("woot", FALLBACK); // will be 5 -- set in the config before9var rawr = await fcl.config().get("rawr", FALLBACK); // will be 7 -- set in the config before10var hmmm = await fcl.config().get("hmmm", FALLBACK); // will be 1 -- uses fallback because this isnt in the config1112return woot + rawr + hmmm;13}1415addStuff().then((d) => console.log(d)); // 13 (5 + 7 + 1)
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 . |
Configuration keys that start with 0x
will be used to find-and-replace their values in Cadence scripts and transactions input to FCL. Typically this is used to represent account addresses. Account addresses for the same contract will be different depending on the Flow network you're interacting with (eg. Testnet, Mainnet).
This allows you to write your script or transaction once and not have to update code when you point your application at a different Flow network.
1import * as fcl from "@onflow/fcl";23fcl4.config()5.put("accessNode.api", "https://rest-testnet.onflow.org")6.put("0xFlowToken", "0x7e60df042a9c0868");78async function myScript() {9return fcl.query({10cadence: `11import FlowToken from 0xFlowToken // will be replaced with 0xf233dcee88fe0abe because of the configuration1213pub fun main(): UFix64 {14return FlowToken.totalSupply // arbitrary script that can access FlowToken interface15}16`,17});18}
1import * as fcl from "@onflow/fcl";23fcl4.config()5.put("flow.network", "testnet")6.put("accessNode.api", "https://rest-testnet.onflow.org")7.put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn")8.put("app.detail.title", "Test Harness")9.put("app.detail.icon", "https://i.imgur.com/r23Zhvu.png")10.put("0xFlowToken", "0x7e60df042a9c0868");
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.
⚠️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.
⚠️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.
1import * as fcl from "@onflow/fcl";2fcl3.config()4.put("accessNode.api", "https://rest-testnet.onflow.org")5.put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn");6// anywhere on the page7fcl.authenticate();
⚠️ authenticate
can also take a service returned from discovery with fcl.authenticate({ service })
.
⚠️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.
⚠️The current user must be authenticated first.
1import * as fcl from "@onflow/fcl";2fcl.config().put("accessNode.api", "https://rest-testnet.onflow.org");3// first authenticate to set current user4fcl.authenticate();5// ... somewhere else & sometime later6fcl.unauthenticate();7// fcl.currentUser.loggedIn === null
⚠️This method can only be used in web browsers.
A convenience method that calls fcl.unauthenticate()
and then fcl.authenticate()
for the current user.
⚠️The current user must be authenticated first.
1import * as fcl from "@onflow/fcl";2// first authenticate to set current user3fcl.authenticate();4// ... somewhere else & sometime later5fcl.reauthenticate();6// logs out user and opens up login/sign-up flow
⚠️This method can only be used in web browsers.
A convenience method that calls and is equivalent to fcl.authenticate()
.
⚠️This method can only be used in web browsers.
A convenience method that calls and is equivalent to fcl.authenticate()
.
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.
Type | Description |
---|---|
AuthorizationObject | An object containing the necessary details from the current user to authorize a transaction in any role. |
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.
1import * as fcl from "@onflow/fcl";2// login somewhere before3fcl.authenticate();4// once logged in authz will produce values5console.log(fcl.authz);6// prints {addr, signingFunction, keyId, sequenceNum} from the current authenticated user.78const txId = await fcl.mutate({9cadence: `10import Profile from 0xba1132bc08f82fe21112transaction(name: String) {13prepare(account: AuthAccount) {14account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)15}16}17`,18args: (arg, t) => [arg("myName", t.String)],19proposer: fcl.authz, // optional - default is fcl.authz20payer: fcl.authz, // optional - default is fcl.authz21authorizations: [fcl.authz], // optional - default is [fcl.authz]22});
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.
The callback passed to subscribe will be called when the user authenticates and un-authenticates, making it easy to update the UI accordingly.
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. |
1import React, { useState, useEffect } from "react";2import * as fcl from "@onflow/fcl";34export function AuthCluster() {5const [user, setUser] = useState({ loggedIn: null });6useEffect(() => fcl.currentUser.subscribe(setUser), []); // sets the callback for FCL to use78if (user.loggedIn) {9return (10<div>11<span>{user?.addr ?? "No Address"}</span>12<button onClick={fcl.unauthenticate}>Log Out</button> {/* once logged out in setUser(user) will be called */}13</div>14);15} else {16return (17<div>18<button onClick={fcl.logIn}>Log In</button>{" "}19{/* once logged in setUser(user) will be called */}20<button onClick={fcl.signUp}>Sign Up</button> {/* once signed up, setUser(user) will be called */}21</div>22);23}24}
Returns the current user object. This is the same object that is set and available on fcl.currentUser.subscribe(callback)
.
1// returns the current user object2const user = fcl.currentUser.snapshot();34// subscribes to the current user object and logs to console on changes5fcl.currentUser.subscribe(console.log);
Equivalent to fcl.authenticate
.
Equivalent to fcl.unauthenticate
.
Equivalent to fcl.authz
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.
Name | Type | Description |
---|---|---|
message | string (required) | A hexadecimal string to be signed |
Type | Description |
---|---|
Array | An Array of CompositeSignatures: signature |
1import * as fcl from "@onflow/fcl"23export const signMessage = async () => {4const MSG = Buffer.from("FOO").toString("hex")5try {6return await currentUser.signUserMessage(MSG)7} catch (error) {8console.log(error)9}10}
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.
⚠️discovery.authn.endpoint
value must be set in the configuration before calling this method. See FCL 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.
1import "./config"2import { useState, useEffect } from "react"3import * as fcl from "@onflow/fcl"45function Component() {6const [wallets, setWallets] = useState([])7useEffect(() => fcl.discovery.authn.subscribe(res => setWallets(res.results)), [])89return (10<div>11{wallets.map((wallet) => (12<button13key={wallet.provider.address}14onClick={() => fcl.authenticate({ service: wallet })}15>16Login with {wallet.provider.name}17</button>18))}19</div>20)21}
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.
1import { config } from "@onflow/fcl"23config({4"discovery.authn.endpoint": "https://fcl-discovery.onflow.org/api/testnet/authn", // Endpoint set to Testnet5"discovery.authn.include": ["0x9d2e44203cb13051"] // Ledger wallet address on Testnet set to be included6})
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.
Return a list of authn
services.
The callback sent to subscribe
will be called with a list of authn
services.
📣 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.
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.
Allows you to submit scripts to query the blockchain.
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. |
Type | Description |
---|---|
any | A JSON representation of the response. |
1import * as fcl from "@onflow/fcl";23const result = await fcl.query({4cadence: `5pub fun main(a: Int, b: Int, addr: Address): Int {6log(addr)7return a + b8}9`,10args: (arg, t) => [11arg(7, t.Int), // a: Int12arg(6, t.Int), // b: Int13arg("0xba1132bc08f82fe2", t.Address), // addr: Address14],15});16console.log(result); // 13
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.
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. |
Type | Description |
---|---|
string | The transaction ID. |
1import * as fcl from "@onflow/fcl";2// login somewhere before3fcl.authenticate();45const txId = await fcl.mutate({6cadence: `7import Profile from 0xba1132bc08f82fe289transaction(name: String) {10prepare(account: AuthAccount) {11account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)12}13}14`,15args: (arg, t) => [arg("myName", t.String)],16});
Use fcl.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
.
⚠️ fcl.config.flow.network
or options override is required to use this api. See FCL Configuration.
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 |
Type | Description |
---|---|
Boolean | true if verified or false |
1import * as fcl from "@onflow/fcl"23const isValid = await fcl.AppUtils.verifyUserSignatures(4Buffer.from('FOO').toString("hex"),5[{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}],6{fclCryptoContract}7)
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.
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 |
Type | Description |
---|---|
Boolean | true if verified or false |
1import * as fcl from "@onflow/fcl"23const accountProofData = {4address: "0x123",5nonce: "F0123"6signatures: [{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}],7}89const isValid = await fcl.AppUtils.verifyAccountProof(10"AwesomeAppId",11accountProofData,12{fclCryptoContract}13)
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})
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.
⚠️Must be used in conjuction with fcl.decode(response)
to get back correct keys and all values in JSON.
Name | Type | Description |
---|---|---|
builders | [Builders] | See builder functions. |
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. |
1import * as fcl from "@onflow/fcl";23// a script only needs to resolve the arguments to the script4const response = await fcl.send([fcl.script`${script}`, fcl.args(args)]);5// note: response values are encoded, call await fcl.decode(response) to get JSON67// a transaction requires multiple 'builders' that need to be resolved prior to being sent to the chain - such as setting the authorizations.8const response = await fcl.send([9fcl.transaction`10${transaction}11`,12fcl.args(args),13fcl.proposer(proposer),14fcl.authorizations(authorizations),15fcl.payer(payer),16fcl.limit(9999),17]);18// note: response contains several values (Cad)
Decodes the response from fcl.send()
into the appropriate JSON representation of any values returned from Cadence code.
📣 To define your own decoder, see tutorial
.
Name | Type | Description |
---|---|---|
response | ResponseObject | Should be the response returned from fcl.send([...]) |
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. |
1import * as fcl from "@onflow/fcl";23// simple script to add 2 numbers4const response = await fcl.send([5fcl.script`6pub fun main(int1: Int, int2: Int): Int {7return int1 + int28}9`,10fcl.args([11fcl.arg(1, fcl.t.Int),12fcl.arg(2, fcl.t.Int)13]),14]);1516const decoded = await fcl.decode(response);1718assert(3 === decoded);19assert(typeof decoded === "number");
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)
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.
Name | Type | Description |
---|---|---|
address | Address | Address of the user account with or without a prefix (both formats are supported). |
Type | Description |
---|---|
AccountObject | A JSON representation of a user account. |
1import * as fcl from "@onflow/fcl";23// somewhere in an async function4// fcl.account is the same as this function5const getAccount = async (address) => {6const account = await fcl.send([fcl.getAccount(address)]).then(fcl.decode);7return account;8};
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.latestBlock(isSealed)
if you do not need to pair with any other builders.
Name | Type | Default | Description |
---|---|---|---|
isSealed | boolean | false | If the latest block should be sealed or not. See block states. |
Type | Description |
---|---|
BlockObject | The latest block if not used with any other builders. |
1import * as fcl from "@onflow/fcl";23const latestSealedBlock = await fcl4.send([5fcl.getBlock(true), // isSealed = true6])7.then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
blockHeight | number | The height of the block to execute the interaction at. |
Type | Description |
---|---|
Partial Interaction | A partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount() . |
1import * as fcl from "@onflow/fcl";23await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
blockId | string | The ID of the block to execute the interaction at. |
Type | Description |
---|---|
Partial Interaction | A partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount() . |
1import * as fcl from "@onflow/fcl";23await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode);
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.
Type | Description |
---|---|
BlockHeaderObject | The latest block header if not used with any other builders. |
1import * as fcl from "@onflow/fcl";23const latestBlockHeader = await fcl4.send([fcl.getBlockHeader()])5.then(fcl.decode);
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.
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). |
Type | Description |
---|---|
[EventObject] | An array of events that matched the eventName. |
1import * as fcl from "@onflow/fcl";23const events = await fcl4.send([5fcl.getEventsAtBlockHeightRange(6"A.7e60df042a9c0868.FlowToken.TokensWithdrawn",735580624,8355806249),10])11.then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
eventName | EventName | The name of the event. |
blockIds | number | The ids of the blocks to scan for events. |
Type | Description |
---|---|
[EventObject] | An array of events that matched the eventName. |
1import * as fcl from "@onflow/fcl";23const events = await fcl4.send([5fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [6"c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7",7"5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f",8]),9])10.then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
collectionID | string | The id of the collection. |
Type | Description |
---|---|
CollectionObject | An object with the id and a list of transactions within the requested collection. |
1import * as fcl from "@onflow/fcl";23const collection = await fcl4.send([5fcl.getCollection(6"cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5"7),8])9.then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
transactionId | string | The transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3 |
Type | Description |
---|---|
TransactionStatusObject | Object representing the result/status of a transaction |
1import * as fcl from "@onflow/fcl";23const status = await fcl4.send([5fcl.getTransactionStatus(6"9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"7),8])9.then(fcl.decode);
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.
Name | Type | Description |
---|---|---|
transactionId | string | The transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3 |
Type | Description |
---|---|
TransactionObject | An full transaction object containing a payload and signatures |
1import * as fcl from "@onflow/fcl";23const tx = await fcl4.send([5fcl.getTransaction(6"9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"7),8])9.then(fcl.decode);
Use fcl.getEventsAtBlockHeightRange
or fcl.getEventsAtBlockIds
.
Use fcl.getBlock
.
Use fcl.getBlock
and fcl.atBlockId
.
Use fcl.getBlock
and fcl.atBlockHeight
.
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})
A utility builder to be used with fcl.args[...]
to create FCL supported arguments for interactions.
Name | Type | Description |
---|---|---|
value | any | Any value that you are looking to pass to other builders. |
type | FType | A type supported by Flow. |
Type | Description |
---|---|
ArgumentObject | Holds the value and type passed in. |
1import * as fcl from "@onflow/fcl";23await fcl4.send([5fcl.script`6pub fun main(a: Int, b: Int): Int {7return a + b8}9`,10fcl.args([11fcl.arg(5, fcl.t.Int), // a12fcl.arg(4, fcl.t.Int), // b13]),14])15.then(fcl.decode);
A utility builder to be used with other builders to pass in arguments with a value and supported type.
Name | Type | Description |
---|---|---|
args | [Argument Objects] | An array of arguments that you are looking to pass to other builders. |
Type | Description |
---|---|
Partial Interaction | An interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. |
1import * as fcl from "@onflow/fcl";23await fcl4.send([5fcl.script`6pub fun main(a: Int, b: Int): Int {7return a + b8}9`,10fcl.args([11fcl.arg(5, fcl.t.Int), // a12fcl.arg(4, fcl.t.Int), // b13]),14])15.then(fcl.decode); // 9
⚠️Recommended: The following functionality is simplified by
fcl.query({...options}
orfcl.mutate({...options})
and is reccomended to use over the functions below.
A template builder to use a Cadence script for an interaction.
📣 Use with fcl.args(...)
to pass in arguments dynamically.
Name | Type | Description |
---|---|---|
CODE | string | Should be valid Cadence script. |
Type | Description |
---|---|
Interaction | An interaction containing the code passed in. |
1import * as fcl from "@onflow/fcl";23const code = `4pub fun main(): Int {5return 5 + 46}7`;8const answer = await fcl.send([fcl.script(code)]).then(fcl.decode);9console.log(answer); // 9
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.
Name | Type | Description |
---|---|---|
CODE | string | Should be valid a Cadence transaction. |
Type | Description |
---|---|
Partial Interaction | An partial interaction containing the code passed in. Further builders are required to complete the interaction - see warning. |
1import * as fcl from "@onflow/fcl";23const code = `4pub fun main(): Int {5return 5 + 46}7`;8const answer = await fcl.send([fcl.script(code)]).then(fcl.decode);9console.log(answer); // 9
These functions are abstracted short hand ways to skip the send and decode steps of sending an interaction to the chain. More pre-built interactions are coming soon.
A pre-built interaction that returns the details of an account from their public address.
Name | Type | Description |
---|---|---|
address | Address | Address of the user account with or without a prefix (both formats are supported). |
Type | Description |
---|---|
AccountObject | A JSON representation of a user account. |
1import * as fcl from "@onflow/fcl";2const account = await fcl.account("0x1d007d755706c469");
A pre-built interaction that returns the latest block (optionally sealed or not), by id, or by height.
Name | Type | Default | Description |
---|---|---|---|
sealed | boolean | false | If the latest block should be sealed or not. See block states. |
id | string | ID of block to get. | |
height | int | Height of block to get. |
Type | Description |
---|---|
BlockObject | A JSON representation of a block. |
1import * as fcl from "@onflow/fcl";2await fcl.block() // get latest finalized block3await fcl.block({sealed: true}) // get latest sealed block4await fcl.block({id: '0b1bdfa9ddaaf31d53c584f208313557d622d1fedee1586ffc38fb5400979faa'}) // get block by id5await fcl.block({height: 56481953}) // get block by height
A pre-built interaction that returns the latest block (optionally sealed or not).
Name | Type | Default | Description |
---|---|---|---|
isSealed | boolean | false | If the latest block should be sealed or not. See block states. |
Type | Description |
---|---|
BlockObject | A JSON representation of a block. |
1import * as fcl from "@onflow/fcl";2const latestBlock = await fcl.latestBlock();
A utility function that lets you set the transaction to get subsequent status updates (via polling) and the finalized result once available.
⚠️The poll rate is set at 2500ms
and will update at that interval until transaction is sealed.
Name | Type | Description |
---|---|---|
transactionId | string | A valid transaction id. |
Name | Type | Description |
---|---|---|
snapshot() | function | Returns the current state of the transaction. |
subscribe(cb) | function | Calls the cb passed in with the new transaction on a status change. |
onceFinalized() | function | Provides the transaction once status 2 is returned. See Tranasaction Statuses. |
onceExecuted() | function | Provides the transaction once status 3 is returned. See Tranasaction Statuses. |
onceSealed() | function | Provides the transaction once status 4 is returned. See Tranasaction Statuses. |
1import * as fcl from "@onflow/fcl";23const [txStatus, setTxStatus] = useState(null);4useEffect(() => fcl.tx(txId).subscribe(setTxStatus));
A utility function that lets you set the transaction to get subsequent status updates (via polling) and the finalized result once available.
⚠️The poll rate is set at 10000ms
and will update at that interval for getting new events.
Note:
⚠️fcl.eventPollRate
value could be set to change the polling rate of all events subcribers, check FCL Configuration for guide.
Name | Type | Description |
---|---|---|
eventName | string | A valid event name. |
Name | Type | Description |
---|---|---|
subscribe(cb) | function | Calls the cb passed in with the new event. |
1import * as fcl from "@onflow/fcl";2// in some react component3fcl.events(eventName).subscribe((event) => {4console.log(event)5})
Builders are modular functions that can be coupled together with fcl.send([...builders])
to create an Interaction. The builders needed to create an interaction depend on the script or transaction that is being sent.
An interaction is an object containing the information to perform an action on chain.This object is populated through builders and converted into the approriate access node API call. See the interaction object here. A 'partial' interaction is an interaction object that does not have sufficient information to the intended on-chain action. Multiple partial interactions (through builders) can be coupled to create a complete interaction.
Key | Value Type | Default | Description |
---|---|---|---|
addr | Address | null | The public address of the current user |
cid | string | null | Allows wallets to specify a content identifier for user metadata. |
expiresAt | number | null | Allows wallets to specify a time-frame for a valid session. |
f_type | string | 'USER' | A type identifier used internally by FCL. |
f_vsn | string | '1.0.0' | FCL protocol version. |
loggedIn | boolean | null | If the user is logged in. |
services | [ServiceObject] | [] | A list of trusted services that express ways of interacting with the current user's identity, including means to further discovery, authentication, authorization, or other kinds of interactions. |
This type conforms to the interface required for FCL to authorize transaction on behalf o the current user.
Key | Value Type | Description |
---|---|---|
addr | Address | The address of the authorizer |
signingFunction | function | A function that allows FCL to sign using the authorization details and produce a valid signature. |
keyId | number | The index of the key to use during authorization. (Multiple keys on an account is possible). |
sequenceNum | number | A number that is incremented per transaction using they keyId. |
An object that contains all the information needed for FCL to sign a message with the user's signature.
Key | Value Type | Description |
---|---|---|
addr | Address | The address of the authorizer |
keyId | number | The index of the key to use during authorization. (Multiple keys on an account is possible). |
signature | function | A SigningFunction that can produce a valid signature for a user from a message. |
The JSON representation of an account on the Flow blockchain.
Key | Value Type | Description |
---|---|---|
address | Address | The address of the account |
balance | number | The FLOW balance of the account in 10^8. |
code | Code | The code of any Cadence contracts stored in the account. |
contracts | Object: Contract | An object with keys as the contract name deployed and the value as the the cadence string. |
keys | [KeyObject] | Any contracts deployed to this account. |
Value Type | Description |
---|---|
string(formatted) | A valid Flow address should be 16 characters in length. A 0x prefix is optional during inputs. eg. f8d6e0586b0a20c1 |
An argument object created by fcl.arg(value,type)
Key | Value Type | Description |
---|---|---|
value | any | Any value to be used as an argument to a builder. |
xform | FType | Any of the supported types on Flow. |
An function that takes the fcl.arg
function and fcl types t
and returns an array of fcl.arg(value,type)
.
(arg, t) => Array<Arg>
Parameter Name | Value Type | Description |
---|---|---|
arg | function | A function that returns an ArgumentObject - fcl.arg . |
t | FTypes | An object with acccess to all of the supported types on Flow. |
Returns
Value Type | Description |
---|---|
[fcl.args] | Array of fcl.args . |
An authorization function must produce the information of the user that is going to sign and a signing function to use the information to produce a signature.
⚠️This function is always async.
📣 By default FCL exposes fcl.authz
that produces the authorization object for the current user (given they are signed in and only on the browser). Replace this with your own function that conforms to this interface to use it wherever an authorization object is needed.
Parameter Name | Value Type | Description |
---|---|---|
account | AccountObject | The account of the user that is going to sign. |
Returns
Value Type | Description |
---|---|
Promise<[AuthorizationObject](#authorizationobject)> | The object that contains all the information needed by FCL to authorize a user's transaction. |
1const authorizationFunction = async (account) => {2// authorization function need to return an account3const { address, keys } = account4const tempId = `${address}-${keys[process.env.minterAccountIndex]}`;5const keyId = Number(KEY_ID);6let signingFunction = async signable => {7return {8keyId,9addr: fcl.withPrefix(address),10signature: sign(process.env.FLOW_MINTER_PRIVATE_KEY, signable.message), // signing function, read below11}12}13return {14...account,15address,16keyId,17tempId,18signingFunction,19}
Consumes a payload and produces a signature for a transaction.
⚠️This function is always async.
📣 Only write your own signing function if you are writing your own custom authorization function.
Note: These values are destructed from the payload object in the first argument.
Parameter Name | Value Type | Description |
---|---|---|
message | string | The encoded string which needs to be used to produce the signature. |
addr | string | The encoded string which needs to be used to produce the signature. |
keyId | string | The encoded string which needs to be used to produce the signature. |
roles | string | The encoded string which needs to be used to produce the signature. |
voucher | object | The raw transactions information, can be used to create the message for additional safety and lack of trust in the supplied message. |
Returns
Value Type | Description |
---|---|
Promise<[SignableObject](#signableobject)> | The object that contains all the information needed by FCL to authorize a user's transaction. |
1import * as fcl from "@onflow/fcl";2import { ec as EC } from "elliptic";3import { SHA3 } from "sha3";4const ec: EC = new EC("p256");56const produceSignature = (privateKey, msg) => {7const key = ec.keyFromPrivate(Buffer.from(privateKey, "hex"));8const sig = key.sign(this.hashMsg(msg));9const n = 32;10const r = sig.r.toArrayLike(Buffer, "be", n);11const s = sig.s.toArrayLike(Buffer, "be", n);12return Buffer.concat([r, s]).toString("hex");13};1415const signingFunction = ({16message, // The encoded string which needs to be used to produce the signature.17addr, // The address of the Flow Account this signature is to be produced for.18keyId, // The keyId of the key which is to be used to produce the signature.19roles: {20proposer, // A Boolean representing if this signature to be produced for a proposer.21authorizer, // A Boolean representing if this signature to be produced for a authorizer.22payer, // A Boolean representing if this signature to be produced for a payer.23},24voucher, // The raw transactions information, can be used to create the message for additional safety and lack of trust in the supplied message.25}) => {26return {27addr, // The address of the Flow Account this signature was produced for.28keyId, // The keyId for which key was used to produce the signature.29signature: produceSignature(message), // The hex encoded string representing the signature of the message.30};31};
Key | Value Type | Description |
---|---|---|
args | object | A list of encoded Cadence values passed into this transaction. These have not been decoded by the JS-SDK. |
authorizers | [Address] | A list of the accounts that are authorizing this transaction to mutate to their on-chain account state. See more here. |
envelopeSignatures | [SignableObject] | A list of signatures generated by the payer role. See more here. |
gasLimit | number | The maximum number of computational units that can be used to execute this transaction. See more here. |
payer | Address | The account that pays the fee for this transaction. See more here. |
payloadSignatures | [SignableObject] | A list of signatures generated by the proposer and authorizer roles. See more here. |
proposalKey | [ProposalKey] | The account key used to propose this transaction |
referenceBlockId | string | A reference to the block used to calculate the expiry of this transaction. |
script | string | The UTF-8 encoded Cadence source code that defines the execution logic for this transaction |
Key Name | Value Type | Description |
---|---|---|
proposer | boolean | A Boolean representing if this signature to be produced for a proposer. |
authorizer | boolean | A Boolean representing if this signature to be produced for an authorizer. |
payer | boolean | A Boolean representing if this signature to be produced for a payer. |
For more on what each transaction role means, see singing roles.
Key | Value Type | Description |
---|---|---|
blockId | string | ID of the block that contains the transaction. |
events | [EventObject] | An array of events that were emitted during the transaction. |
status | TransactionStatus | The status of the transaction on the blockchain. |
statusString | TransactionStatus | The status as as descriptive text (e.g. "FINALIZED"). |
errorMessage | string | An error message if it exists. Default is an empty string '' . |
statusCode | GRPCStatus | The status from the GRPC response. |
Value Type | Description |
---|---|
string(formatted) | A event name in Flow must follow the format A.{AccountAddress}.{ContractName}.{EventName} eg. A.ba1132bc08f82fe2.Debug.Log |
Value Type | Description |
---|---|
string(formatted) | A formatted string that is a valid cadence contract. |
This is the JSON representation of a key on the Flow blockchain.
Key | Value Type | Description |
---|---|---|
index | number | The address of the account |
publicKey | string | The public portion of a public/private key pair |
signAlgo | number | An index referring to one of ECDSA_P256 or ECDSA_secp256k1 |
hashAlgo | number | An index referring to one of SHA2_256 or SHA3_256 |
weight | number | A number between 1 and 1000 indicating the relative weight to other keys on the account. |
sequenceNumber | number | This number is incremented for every transaction signed using this key. |
revoked | boolean | If this key has been disabled for use. |
ProposalKey is the account key used to propose this transaction.
A proposal key references a specific key on an account, along with an up-to-date sequence number for that key. This sequence number is used to prevent replay attacks.
You can find more information about sequence numbers here: https://docs.onflow.org/concepts/transaction-signing/#sequence-numbers
Key | Value Type | Description |
---|---|---|
address | Address | The address of the account |
keyIndex | number | The index of the account key being referenced |
sequenceNumber | number | The sequence number associated with this account key for this transaction |
The JSON representation of a key on the Flow blockchain.
Key | Value Type | Description |
---|---|---|
id | string | The id of the block. |
parentId | string | The id of the parent block. |
height | number | The height of the block. |
timestamp | object | Contains time related fields. |
collectionGuarantees | [CollectionGuaranteeObject] | Contains the ids of collections included in the block. |
blockSeals | [SealedBlockObject] | The details of which nodes executed and sealed the blocks. |
signatures | Uint8Array([numbers]) | All signatures. |
The subset of the BlockObject containing only the header values of a block.
Key | Value Type | Description |
---|---|---|
id | string | The id of the block. |
parentId | string | The id of the parent block. |
height | number | The height of the block. |
timestamp | object | Contains time related fields. |
A collection that has been included in a block.
Key | Value Type | Description |
---|---|---|
collectionId | string | The id of the block. |
signatures | [SignatureObject] | All signatures. |
A collection is a list of transactions that are contained in the same block.
Key | Value Type | Description |
---|---|---|
id | string | The id of the collection. |
transactionIds | [string] | The ids of the transactions included in the collection. |
The format of all responses in FCL returned from fcl.send(...)
. For full details on the values and descriptions of the keys, view here.
Key |
---|
tag |
transaction |
transactionStatus |
transactionId |
encodedData |
events |
account |
block |
blockHeader |
latestBlock |
collection |
Key | Value Type | Description |
---|---|---|
blockId | string | ID of the block that contains the event. |
blockHeight | number | Height of the block that contains the event. |
blockTimestamp | string | The timestamp of when the block was sealed in a DateString format. eg. '2021-06-25T13:42:04.227Z' |
type | EventName | A string containing the event name. |
transactionId | string | Can be used to query transaction information, eg. via a Flow block explorer. |
transactionIndex | number | Used to prevent replay attacks. |
eventIndex | number | Used to prevent replay attacks. |
data | any | The data emitted from the event. |
The status of a transaction will depend on the Flow blockchain network and which phase it is in as it completes and is finalized.
Status Code | Description |
---|---|
0 | Unknown |
1 | Transaction Pending - Awaiting Finalization |
2 | Transaction Finalized - Awaiting Execution |
3 | Transaction Executed - Awaiting Sealing |
4 | Transaction Sealed - Transaction Complete. At this point the transaction result has been committed to the blockchain. |
5 | Transaction Expired |
The access node GRPC implementation follows the standard GRPC Core status code spec. View here.
FCL arguments must specify one of the following support types for each value passed in.
Type | Example |
---|---|
UInt | fcl.arg(1, t.UInt) |
UInt8 | fcl.arg(8, t.UInt8) |
UInt16 | fcl.arg(16, t.UInt16) |
UInt32 | fcl.arg(32, t.UInt32) |
UInt64 | fcl.arg(64, t.UInt64) |
UInt128 | fcl.arg(128, t.UInt128) |
UInt256 | fcl.arg(256, t.UInt256) |
Int | fcl.arg(1, t.Int) |
Int8 | fcl.arg(8, t.Int8) |
Int16 | fcl.arg(16, t.Int16) |
Int32 | fcl.arg(32, t.Int32) |
Int64 | fcl.arg(64, t.Int64) |
Int128 | fcl.arg(128, t.Int128) |
Int256 | fcl.arg(256, t.Int256) |
Word8 | fcl.arg(8, t.Word8) |
Word16 | fcl.arg(16, t.Word16) |
Word32 | fcl.arg(32, t.Word32) |
Word64 | fcl.arg(64, t.Word64) |
UFix64 | fcl.arg("64.123", t.UFix64) |
Fix64 | fcl.arg("64.123", t.Fix64) |
String | fcl.arg("Flow", t.String) |
Character | fcl.arg("c", t.String) |
Bool | fcl.arg(true, t.String) |
Address | fcl.arg("0xABC123DEF456", t.Address) |
Optional | fcl.arg("Flow", t.Optional(t.String)) |
Array | fcl.args([ fcl.arg(["First", "Second"], t.Array(t.String)) ]) |
Dictionary | fcl.args([fcl.arg([{key: 1, value: "one"}, {key: 2, value: "two"}], t.Dictionary({key: t.Int, value: t.String}))]) |
Path | fcl.arg({ domain: "public", identifier: "flowTokenVault" }, t.Path) |