MAINNET:
Loading...
TESTNET:
Loading...
/
onflow.org
Flow Playground

Flow Client Library (FCL) API Reference

Version: 0.76.0

Last Updated: August 13, 2021

Table of contents

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.

import * as fcl from "@onflow/fcl";

fcl
  .config() // returns the config instance
  .put("foo", "bar") // configures "foo" to be "bar"
  .put("baz", "buz"); // configures "baz" to be "buz"

// OR

fcl.config({
  foo: "bar",
  baz: "buz",
});

Getting Configuration Values

The config instance has an asynchronous get method. You can also pass it a fallback value.

import * as fcl from "@onflow/fcl";

fcl.config().put("foo", "bar").put("woot", 5).put("rawr", 7);

const FALLBACK = 1;

async function addStuff() {
  var woot = await fcl.config().get("woot", FALLBACK); // will be 5 -- set in the config before
  var rawr = await fcl.config().get("rawr", FALLBACK); // will be 7 -- set in the config before
  var hmmm = await fcl.config().get("hmmm", FALLBACK); // will be 1 -- uses fallback because this isnt in the config

  return woot + rawr + hmmm;
}

addStuff().then((d) => console.log(d)); // 13 (5 + 7 + 1)

Common Configuration Keys

NameExampleDescription
accessNode.api(required)https://access-testnet.onflow.orgAPI URL for the Flow Blockchain Access Node you want to be communicating with. See all available access node endpoints here.
envtestnetUsed in conjunction with stored interactions. Possible values: local, canarynet, testnet, mainnet
discovery.wallet(required)https://fcl-discovery.onflow.org/testnet/authnPoints FCL at the Wallet or Wallet Discovery mechanism.
discovery.authn.endpointhttps://fcl-discovery.onflow.org/api/testnet/authnEndpoint for alternative configurable Wallet Discovery mechanism. Read more on discovery
app.detail.titleCryptokittiesYour applications title, can be requested by wallets and other services.
app.detail.iconhttps://fcl-discovery.onflow.org/images/blocto.pngUrl for your applications icon, can be requested by wallets and other services.
challenge.handshakeDEPRECATEDUse discovery.wallet instead.

Address replacement in scripts and transactions

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.

import * as fcl from "@onflow/fcl";

fcl
  .config()
  .put("accessNode.api", "https://access-testnet.onflow.org")
  .put("0xFlowToken", "0x7e60df042a9c0868");

async function myScript() {
  return fcl.query({
    cadence: `
        import FlowToken from 0xFlowToken // will be replaced with 0xf233dcee88fe0abe because of the configuration

        pub fun main(): UFix64 { 
          return FlowToken.totalSupply  // arbitrary script that can access FlowToken interface
        }
      `,
  });
}

Example

import * as fcl from "@onflow/fcl";

fcl
  .config()
  .put("env", "testnet")
  .put("accessNode.api", "https://access-testnet.onflow.org")
  .put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn")
  .put("app.detail.title", "Test Harness")
  .put("app.detail.icon", "https://i.imgur.com/r23Zhvu.png")
  .put("0xFlowToken", "0x7e60df042a9c0868");

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.

Methods


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

import * as fcl from "@onflow/fcl";
fcl
  .config()
  .put("accessNode.api", "https://access-testnet.onflow.org")
  .put("discovery.wallet", "https://fcl-discovery.onflow.org/testnet/authn");
// anywhere on the page
fcl.authenticate();

Note

⚠️ authenticate can also take a service returned from discovery with fcl.authenticate({ service }).

Examples


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

import * as fcl from "@onflow/fcl";
fcl.config().put("accessNode.api", "https://access-testnet.onflow.org");
// first authenticate to set current user
fcl.authenticate();
// ... somewhere else & sometime later
fcl.unauthenticate();
// fcl.currentUser.loggedIn === null

Examples


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

import * as fcl from "@onflow/fcl";
// first authenticate to set current user
fcl.authenticate();
// ... somewhere else & sometime later
fcl.reauthenticate();
// logs out user and opens up login/sign-up flow

Examples


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

TypeDescription
AuthorizationObjectAn 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.

import * as fcl from "@onflow/fcl";
// login somewhere before
fcl.authenticate();
// once logged in authz will produce values
console.log(fcl.authz);
// prints {addr, signingFunction, keyId, sequenceNum} from the current authenticated user.

const txId = await fcl.mutate({
  cadence: `
    import Profile from 0xba1132bc08f82fe2
    
    transaction(name: String) {
      prepare(account: AuthAccount) {
        account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)
      }
    }
  `,
  args: (arg, t) => [arg("myName", t.String)],
  proposer: fcl.authz, // optional - default is fcl.authz
  payer: fcl.authz, // optional - default is fcl.authz
  authorizations: [fcl.authz], // optional - default is [fcl.authz]
});

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.

Methods


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

NameType
callbackfunctionThe callback will be called with the current user as the first argument when the current user is set or removed.

Usage

import React, { useState, useEffect } from "react";
import * as fcl from "@onflow/fcl";

export function AuthCluster() {
  const [user, setUser] = useState({ loggedIn: null });
  useEffect(() => fcl.currentUser.subscribe(setUser), []); // sets the callback for FCL to use

  if (user.loggedIn) {
    return (
      <div>
        <span>{user?.addr ?? "No Address"}</span>
        <button onClick={fcl.unauthenticate}>Log Out</button> {/* once logged out in setUser(user) will be called */}
      </div>
    );
  } else {
    return (
      <div>
        <button onClick={fcl.logIn}>Log In</button>{" "}
        {/* once logged in setUser(user) will be called */}
        <button onClick={fcl.signUp}>Sign Up</button> {/* once signed up, setUser(user) will be called */}
      </div>
    );
  }
}

currentUser.snapshot

Returns the current user object. This is the same object that is set and available on fcl.currentUser.subscribe(callback).

Usage

// returns the current user object
const user = fcl.currentUser.snapshot();

// subscribes to the current user object and logs to console on changes
fcl.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

NameTypeDescription
messagestring (required)A hexadecimal string to be signed

Returns

TypeDescription
ArrayAn Array of CompositeSignatures: {addr, keyId, signature}

Usage

import * as fcl from "@onflow/fcl"

export const signMessage = async () => {
  const MSG = Buffer.from("FOO").toString("hex")
  try {
    return await currentUser.signUserMessage(MSG)
  } catch (error) {
    console.log(error)
  }
}

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

EnvironmentExample
Mainnethttps://fcl-discovery.onflow.org/api/authn
Testnethttps://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

import "./config"
import { useState, useEffect } from "react"
import * as fcl from "@onflow/fcl"

function Component() {
  const [wallets, setWallets] = useState([])
  useEffect(() => fcl.discovery.authn.subscribe(res => setWallets(res.results)), [])

  return (
    <div>
      {wallets.map((wallet) => (
        <button
          key={wallet.provider.address}
          onClick={() => fcl.authenticate({ service: wallet })}
        >
          Login with {wallet.provider.name}
        </button>
      ))}
    </div>
  )
}

authn

More Configuration

By default, limited functionality services, like Ledger, require apps to opt-in in order to display to users. This is so users don't authenticate only to later find out certain services cannot complete certain actions. To enable specific limited functionality 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.


import { config } from "@onflow/fcl"

config({
  "discovery.authn.endpoint": "https://fcl-discovery.onflow.org/api/testnet/authn", // Endpoint set to Testnet
  "discovery.authn.include": ["0x9d2e44203cb13051"] // Ledger wallet address on Testnet set to be included
})

Wallet Addresses on Testnet and Mainnet

ServiceTestnetMainnet
Ledger0x9d2e44203cb130510xe5cd26afebe62781

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.

Methods


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.

KeyTypeDescription
cadencestring (required)A valid cadence script.
argsArgumentFunctionAny arguments to the script if needed should be supplied via a function that returns an array of arguments.
limitnumberCompute (Gas) limit for query. Read the documentation about computation cost for information about how computation cost is calculated on Flow.

Returns

TypeDescription
anyA JSON representation of the response.

Usage

import * as fcl from "@onflow/fcl";

const result = await fcl.query({
  cadence: `
    pub fun main(a: Int, b: Int, addr: Address): Int {
      log(addr)
      return a + b
    }
  `,
  args: (arg, t) => [
    arg(7, t.Int), // a: Int
    arg(6, t.Int), // b: Int
    arg("0xba1132bc08f82fe2", t.Address), // addr: Address
  ],
});
console.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.

KeyTypeDescription
cadencestring (required)A valid cadence transaction.
argsArgumentFunctionAny arguments to the script if needed should be supplied via a function that returns an array of arguments.
limitnumberCompute (Gas) limit for query. Read the documentation about computation cost for information about how computation cost is calculated on Flow.
proposerAuthorizationFunctionThe authorization function that returns a valid AuthorizationObject for the proposer role.

Returns

TypeDescription
stringThe transaction ID.

Usage

import * as fcl from "@onflow/fcl";
// login somewhere before
fcl.authenticate();

const txId = await fcl.mutate({
  cadence: `
    import Profile from 0xba1132bc08f82fe2
    
    transaction(name: String) {
      prepare(account: AuthAccount) {
        account.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name)
      }
    }
  `,
  args: (arg, t) => [arg("myName", t.String)],
});

Examples


verifyUserSignatures (Deprecated)

Use fcl.AppUtils.verifyUserSignatures

A method allowing applications to cryptographically verify the ownership of a Flow account by verifying a message was signed by a user's private key/s. This is typically used with the response from currentUser.signUserMessage.

Arguments

NameTypeDescription
messagestring (required)A hexadecimal string
compositeSignaturesArray (required)An Array of CompositeSignatures

Returns

TypeDescription
Booleantrue if verifed or false

Usage

import * as fcl from "@onflow/fcl"

const verifySignatures = async (message, compositeSignatures) => {
  try {
    return await fcl.AppUtils.verifyUserSignatures(message, compositeSignatures)
  } catch (error) {
    console.log(error)
  }
}

Examples

Use cases include cryptographic login, message validation, verifiable credentials, and others.


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} or fcl.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

NameTypeDescription
builders[Builders]See builder functions.

Returns

TypeDescription
ResponseObjectAn object containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values.

Usage

import * as fcl from "@onflow/fcl";

// a script only needs to resolve the arguments to the script
const response = await fcl.send([fcl.script`${script}`, fcl.args(args)]);
// note: response values are encoded, call await fcl.decode(response) to get JSON

// a transaction requires multiple 'builders' that need to be resolved prior to being sent to the chain - such as setting the authorizations.
const response = await fcl.send([
  fcl.transaction`
    ${transaction}
    `,
  fcl.args(args),
  fcl.proposer(proposer),
  fcl.authorizations(authorizations),
  fcl.payer(payer),
  fcl.limit(9999),
]);
// note: response contains several values (Cad)

Examples


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

NameTypeDescription
responseResponseObjectShould be the response returned from fcl.send([...])

Returns

TypeDescription
anyA 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

import * as fcl from "@onflow/fcl";

// simple script to add 2 numbers
const response = await fcl.send([
  fcl.script`
        pub fun main(int1: Int, int2: Int): Int {
            return int1 + int2
        }
    `,
  fcl.args([
    fcl.arg(1, fcl.t.Int),
    fcl.arg(2, fcl.t.Int)
  ]),
]);

const decoded = await fcl.decode(response);

assert(3 === decoded);
assert(typeof decoded === "number");

Examples


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

NameTypeDescription
addressAddressAddress of the user account with or without a prefix (both formats are supported).

Returns after decoding

TypeDescription
AccountObjectA JSON representation of a user account.

Usage

import * as fcl from "@onflow/fcl";

// somewhere in an async function
// fcl.account is the same as this function
const getAccount = async (address) => {
  const account = await fcl.send([fcl.getAccount(address)]).then(fcl.decode);
  return account;
};

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.latestBlock(isSealed) if you do not need to pair with any other builders.

Arguments

NameTypeDefaultDescription
isSealedbooleanfalseIf the latest block should be sealed or not. See block states.

Returns after decoding

TypeDescription
BlockObjectThe latest block if not used with any other builders.

Usage

import * as fcl from "@onflow/fcl";

const latestSealedBlock = await fcl
  .send([
    fcl.getBlock(true), // isSealed = true
  ])
  .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

NameTypeDescription
blockHeightnumberThe height of the block to execute the interaction at.

Returns

TypeDescription
Partial InteractionA partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount().

Usage

import * as fcl from "@onflow/fcl";

await 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

NameTypeDescription
blockIdstringThe ID of the block to execute the interaction at.

Returns

TypeDescription
Partial InteractionA partial interaction to be paired with another interaction such as fcl.getBlock() or fcl.getAccount().

Usage

import * as fcl from "@onflow/fcl";

await 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

TypeDescription
BlockHeaderObjectThe latest block header if not used with any other builders.

Usage

import * as fcl from "@onflow/fcl";

const latestBlockHeader = await fcl
  .send([fcl.getBlockHeader()])
  .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

NameTypeDescription
eventNameEventNameThe name of the event.
fromBlockHeightnumberThe height of the block to start looking for events (inclusive).
toBlockHeightnumberThe height of the block to stop looking for events (inclusive).

Returns after decoding

TypeDescription
[EventObject]An array of events that matched the eventName.

Usage

import * as fcl from "@onflow/fcl";

const events = await fcl
  .send([
    fcl.getEventsAtBlockHeightRange(
      "A.7e60df042a9c0868.FlowToken.TokensWithdrawn",
      35580624,
      35580624
    ),
  ])
  .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

NameTypeDescription
eventNameEventNameThe name of the event.
blockIdsnumberThe ids of the blocks to scan for events.

Returns after decoding

TypeDescription
[EventObject]An array of events that matched the eventName.

Usage

import * as fcl from "@onflow/fcl";

const events = await fcl
  .send([
    fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [
      "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7",
      "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f",
    ]),
  ])
  .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

NameTypeDescription
collectionIDstringThe id of the collection.

Returns after decoding

TypeDescription
CollectionObjectAn object with the id and a list of transactions within the requested collection.

Usage

import * as fcl from "@onflow/fcl";

const collection = await fcl
  .send([
    fcl.getCollection(
      "cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5"
    ),
  ])
  .then(fcl.decode);

getTransactionStatus

A builder function that returns the status of transaction.

⚠️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

NameTypeDescription
transactionIdstringThe transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3

Returns after decoding

NameTypeDescription
events[EventObject]An array of events that were emitted during the transaction.
statusTransactionStatusThe status of the transaction on the blockchain.
statusStringalphaTransactionStatusThe status as as descriptive text (e.g. "FINALIZED").
errorMessagestringAn error message if it exists. Default is an empty string ''.
statusCodeGRPCStatusThe status from the GRPC response.

Usage

import * as fcl from "@onflow/fcl";

const status = await fcl
  .send([
    fcl.getTransactionStatus(
      "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"
    ),
  ])
  .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

NameTypeDescription
transactionIdstringThe transactionID returned when submitting a transaction. Example: 9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3

Returns after decoding

NameTypeDescription
events[EventObject]An array of events that matched the eventName.
statusTransactionStatusThe status of the transaction on the blockchain.
errorMessagestringAn error message if it exists. Default is an empty string ''.
statusCodeGRPCStatusThe status from the GRPC response.

Usage

import * as fcl from "@onflow/fcl";

const tx = await fcl
  .send([
    fcl.getTransaction(
      "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3"
    ),
  ])
  .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} or fcl.mutate({...options})

arg

A utility builder to be used with fcl.args[...] to create FCL supported arguments for interactions.

Arguments

NameTypeDescription
valueanyAny value that you are looking to pass to other builders.
typeFTypeA type supported by Flow.

Returns

TypeDescription
ArgumentObjectHolds the value and type passed in.

Usage

import * as fcl from "@onflow/fcl";

await fcl
  .send([
    fcl.script`
      pub fun main(a: Int, b: Int): Int {
        return a + b
      }
    `,
    fcl.args([
      fcl.arg(5, fcl.t.Int), // a
      fcl.arg(4, fcl.t.Int), // b
    ]),
  ])
  .then(fcl.decode);

args

A utility builder to be used with other builders to pass in arguments with a value and supported type.

Arguments

NameTypeDescription
args[Argument Objects]An array of arguments that you are looking to pass to other builders.

Returns

TypeDescription
Partial InteractionAn interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction.

Usage

import * as fcl from "@onflow/fcl";

await fcl
  .send([
    fcl.script`
      pub fun main(a: Int, b: Int): Int {
        return a + b
      }
    `,
    fcl.args([
      fcl.arg(5, fcl.t.Int), // a
      fcl.arg(4, fcl.t.Int), // b
    ]),
  ])
  .then(fcl.decode); // 9

Template Builders

⚠️**Recommended:** The following functionality is simplified by fcl.query({...options} or fcl.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

NameTypeDescription
CODEstringShould be valid Cadence script.

Returns

TypeDescription
InteractionAn interaction containing the code passed in.

Usage

import * as fcl from "@onflow/fcl";

const code = `
  pub fun main(): Int {
    return 5 + 4
  }
`;
const answer = await fcl.send([fcl.script(code)]).then(fcl.decode);
console.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

NameTypeDescription
CODEstringShould be valid a Cadence transaction.

Returns

TypeDescription
Partial InteractionAn partial interaction containing the code passed in. Further builders are required to complete the interaction - see warning.

Usage

import * as fcl from "@onflow/fcl";

const code = `
  pub fun main(): Int {
    return 5 + 4
  }
`;
const answer = await fcl.send([fcl.script(code)]).then(fcl.decode);
console.log(answer); // 9

Pre-built Interactions

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.

account

A pre-built interaction that returns the details of an account from their public address.

Arguments

NameTypeDescription
addressAddressAddress of the user account with or without a prefix (both formats are supported).

Returns

TypeDescription
AccountObjectA JSON representation of a user account.

Usage

import * as fcl from "@onflow/fcl";
const account = await fcl.account("0x1d007d755706c469");

block

A pre-built interaction that returns the latest block (optionally sealed or not), by id, or by height.

Arguments

NameTypeDefaultDescription
sealedbooleanfalseIf the latest block should be sealed or not. See block states.
idstringID of block to get.
heightintHeight of block to get.

Returns

TypeDescription
BlockObjectA JSON representation of a block.

Usage

import * as fcl from "@onflow/fcl";
await fcl.block() // get latest finalized block
await fcl.block({sealed: true}) // get latest sealed block
await fcl.block({id: '0b1bdfa9ddaaf31d53c584f208313557d622d1fedee1586ffc38fb5400979faa'}) // get block by id
await fcl.block({height: 56481953}) // get block by height

latestBlock (Deprecated)

A pre-built interaction that returns the latest block (optionally sealed or not).

Arguments

NameTypeDefaultDescription
isSealedbooleanfalseIf the latest block should be sealed or not. See block states.

Returns

TypeDescription
BlockObjectA JSON representation of a block.

Usage

import * as fcl from "@onflow/fcl";
const latestBlock = await fcl.latestBlock();

Transaction Status Utility

tx

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.

Arguments

NameTypeDescription
transactionIdstringA valid transaction id.

Returns

NameTypeDescription
snapshot()functionReturns the current state of the transaction.
subscribe(cb)functionCalls the cb passed in with the new transaction on a status change.
onceFinalized()functionProvides the transaction once status 2 is returned. See Tranasaction Statuses.
onceExecuted()functionProvides the transaction once status 3 is returned. See Tranasaction Statuses.
onceSealed()functionProvides the transaction once status 4 is returned. See Tranasaction Statuses.

Usage

import * as fcl from "@onflow/fcl";

const [txStatus, setTxStatus] = useState(null);
useEffect(() => fcl.tx(txId).subscribe(setTxStatus));

Examples


Event Polling Utility

events

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.

Arguments

NameTypeDescription
eventNamestringA valid event name.

Returns

NameTypeDescription
subscribe(cb)functionCalls the cb passed in with the new event.

Usage

import * as fcl from "@onflow/fcl";
// in some react component
fcl.events(eventName).subscribe((event) => {
  console.log(event)
})

Examples


Types, Interfaces, and Definitions


Builders

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.


Interaction

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.


CurrentUserObject

KeyValue TypeDefaultDescription
addrAddressnullThe public address of the current user
cidstringnullAllows wallets to specify a content identifier for user metadata.
expiresAtnumbernullAllows wallets to specify a time-frame for a valid session.
f_typestring'USER'A type identifier used internally by FCL.
f_vsnstring'1.0.0'FCL protocol version.
loggedInbooleannullIf 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.

AuthorizationObject

This type conforms to the interface required for FCL to authorize transaction on behalf o the current user.

KeyValue TypeDescription
addrAddressThe address of the authorizer
signingFunctionfunctionA function that allows FCL to sign using the authorization details and produce a valid signature.
keyIdnumberThe index of the key to use during authorization. (Multiple keys on an account is possible).
sequenceNumnumberA number that is incremented per transaction using they keyId.

SignableObject

An object that contains all the information needed for FCL to sign a message with the user's signature.

KeyValue TypeDescription
addrAddressThe address of the authorizer
keyIdnumberThe index of the key to use during authorization. (Multiple keys on an account is possible).
signaturefunctionA SigningFunction that can produce a valid signature for a user from a message.

AccountObject

The JSON representation of an account on the Flow blockchain.

KeyValue TypeDescription
addressAddressThe address of the account
balancenumberThe FLOW balance of the account in 10*6.
codeCodeThe code of any Cadence contracts stored in the account.
contractsObject: ContractAn object with keys as the contract name deployed and the value as the the cadence string.
keys[KeyObject]Any contracts deployed to this account.

Address

Value TypeDescription
string(formatted)A valid Flow address should be 16 characters in length.
A 0x prefix is optional during inputs.
eg. f8d6e0586b0a20c1

ArgumentObject

An argument object created by fcl.arg(value,type)

KeyValue TypeDescription
valueanyAny value to be used as an argument to a builder.
xformFTypeAny of the supported types on Flow.

ArgumentFunction

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 NameValue TypeDescription
argfunctionA function that returns an ArgumentObject - fcl.arg.
tFTypesAn object with acccess to all of the supported types on Flow.

Returns

Value TypeDescription
[fcl.args]Array of fcl.args.

Authorization Function

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 NameValue TypeDescription
accountAccountObjectThe account of the user that is going to sign.

Returns

Value TypeDescription
Promise<AuthorizationObject>The object that contains all the information needed by FCL to authorize a user's transaction.

Usage


const authorizationFunction = async (account) => {
    // authorization function need to return an account
    const { address, keys } = account
    const tempId = `${address}-${keys[process.env.minterAccountIndex]}`;
    const keyId = Number(KEY_ID);
    let signingFunction = async signable => {
      return {
        keyId,
        addr: fcl.withPrefix(address),
        signature: sign(process.env.FLOW_MINTER_PRIVATE_KEY, signable.message), // signing function, read below
      }
    }
    return {
    ...account,
    address,
    keyId,
    tempId,
    signingFunction,
  }

Examples:


Signing Function

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.

Payload

Note: These values are destructed from the payload object in the first argument.

Parameter NameValue TypeDescription
messagestringThe encoded string which needs to be used to produce the signature.
addrstringThe encoded string which needs to be used to produce the signature.
keyIdstringThe encoded string which needs to be used to produce the signature.
rolesstringThe encoded string which needs to be used to produce the signature.
voucherobjectThe raw transactions information, can be used to create the message for additional safety and lack of trust in the supplied message.

Returns

Value TypeDescription
Promise<SignableObject>The object that contains all the information needed by FCL to authorize a user's transaction.

Usage

import * as fcl from "@onflow/fcl";
import { ec as EC } from "elliptic";
import { SHA3 } from "sha3";
const ec: EC = new EC("p256");

const produceSignature = (privateKey, msg) => {
  const key = ec.keyFromPrivate(Buffer.from(privateKey, "hex"));
  const sig = key.sign(this.hashMsg(msg));
  const n = 32;
  const r = sig.r.toArrayLike(Buffer, "be", n);
  const s = sig.s.toArrayLike(Buffer, "be", n);
  return Buffer.concat([r, s]).toString("hex");
};

const signingFunction = ({
  message, // The encoded string which needs to be used to produce the signature.
  addr, // The address of the Flow Account this signature is to be produced for.
  keyId, // The keyId of the key which is to be used to produce the signature.
  roles: {
    proposer, // A Boolean representing if this signature to be produced for a proposer.
    authorizer, // A Boolean representing if this signature to be produced for a authorizer.
    payer, // A Boolean representing if this signature to be produced for a payer.
  },
  voucher, // The raw transactions information, can be used to create the message for additional safety and lack of trust in the supplied message.
}) => {
  return {
    addr, // The address of the Flow Account this signature was produced for.
    keyId, // The keyId for which key was used to produce the signature.
    signature: produceSignature(message), // The hex encoded string representing the signature of the message.
  };
};

Examples:


TransactionRolesObject

Key NameValue TypeDescription
proposerbooleanA Boolean representing if this signature to be produced for a proposer.
authorizerbooleanA Boolean representing if this signature to be produced for an authorizer.
payerbooleanA Boolean representing if this signature to be produced for a payer.

For more on what each transaction role means, see singing roles.

EventName

Value TypeDescription
string(formatted)A event name in Flow must follow the format A.{AccountAddress}.{ContractName}.{EventName}
eg. A.ba1132bc08f82fe2.Debug.Log

Contract

Value TypeDescription
string(formatted)A formatted string that is a valid cadence contract.

KeyObject

This is the JSON representation of a key on the Flow blockchain.

KeyValue TypeDescription
indexnumberThe address of the account
publicKeystringThe FLOW balance of the account in 10*6.
signAlgonumberAn index referring to one of ECDSA_P256 or ECDSA_secp256k1
hashAlgonumberAn index referring to one of SHA2_256 or SHA3_256
weightnumberA number between 1 and 1000 indicating the relative weight to other keys on the account.
sequenceNumbernumberThis number is incremented for every transaction signed using this key.
revokedbooleanIf this key has been disabled for use.

BlockObject

The JSON representation of a key on the Flow blockchain.

KeyValue TypeDescription
idstringThe id of the block.
parentIdstringThe id of the parent block.
heightnumberThe height of the block.
timestampobjectContains 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.
signaturesUint8Array([numbers])All signatures.

BlockHeaderObject

The subset of the BlockObject containing only the header values of a block.

KeyValue TypeDescription
idstringThe id of the block.
parentIdstringThe id of the parent block.
heightnumberThe height of the block.
timestampobjectContains time related fields.

CollectionGuaranteeObject

A collection that has been included in a block.

KeyValue TypeDescription
collectionIdstringThe id of the block.
signatures[SignatureObject]All signatures.

CollectionObject

A collection is a list of transactions that are contained in the same block.

KeyValue TypeDescription
idstringThe id of the collection.
transactionIds[string]The ids of the transactions included in the collection.

ResponseObject

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

Event Object

KeyValue TypeDescription
blockIdstringID of the block that contains the event.
blockHeightnumberHeight of the block that contains the event.
blockTimestampstringThe timestamp of when the block was sealed in a DateString format. eg. '2021-06-25T13:42:04.227Z'
typeEventNameA string containing the event name.
transactionIdstringCan be used to query transaction information, eg. via a Flow block explorer.
transactionIndexnumberUsed to prevent replay attacks.
eventIndexnumberUsed to prevent replay attacks.
dataanyThe data emitted from the event.

Transaction Statuses

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 CodeDescription
0Unknown
1Transaction Pending - Awaiting Finalization
2Transaction Finalized - Awaiting Execution
3Transaction Executed - Awaiting Sealing
4Transaction Sealed - Transaction Complete. At this point the transaction result has been committed to the blockchain.
5Transaction Expired

GRPC Statuses

The access node GRPC implementation follows the standard GRPC Core status code spec. View here.

FType

FCL arguments must specify one of the following support types for each value passed in.

TypeExample
UIntfcl.arg(1, t.UInt)
UInt8fcl.arg(8, t.UInt8)
UInt16fcl.arg(16, t.UInt16)
UInt32fcl.arg(32, t.UInt32)
UInt64fcl.arg(64, t.UInt64)
UInt128fcl.arg(128, t.UInt128)
UInt256fcl.arg(256, t.UInt256)
Intfcl.arg(1, t.Int)
Int8fcl.arg(8, t.Int8)
Int16fcl.arg(16, t.Int16)
Int32fcl.arg(32, t.Int32)
Int64fcl.arg(64, t.Int64)
Int128fcl.arg(128, t.Int128)
Int256fcl.arg(256, t.Int256)
Word8fcl.arg(8, t.Word8)
Word16fcl.arg(16, t.Word16)
Word32fcl.arg(32, t.Word32)
Word64fcl.arg(64, t.Word64)
UFix64fcl.arg("64.123", t.UFix64)
Fix64fcl.arg("64.123", t.Fix64)
Stringfcl.arg("Flow", t.String)
Characterfcl.arg("c", t.String)
Boolfcl.arg(true, t.String)
Addressfcl.arg("0xABC123DEF456", t.Address)
Optionalfcl.arg("Flow", t.Optional(t.String))
Arrayfcl.args([ fcl.arg(["First", "Second"], t.Array(t.String)) ])
Dictionaryfcl.args([fcl.arg([{key: 1, value: "one"}, {key: 2, value: "two"}], t.Dictionary({key: t.Int, value: t.String}))])
Pathfcl.arg({ domain: "public", identifier: "flowTokenVault" }, t.Path)