Overview

This reference documents methods available in the SDK that can be accessed via FCL, and explains in detail how these methods work. FCL/SDKs are open source, and you can use them according to the licence.

The library client specifications can be found here:

Getting Started

Installing

NPM:

1
npm install --save @onflow/fcl @onflow/types

Yarn:

1
yarn add @onflow/fcl @onflow/types

Importing the Library

1
import * as fcl from "@onflow/fcl"
2
import * as types from "@onflow/types"

Connect

By default, the library uses HTTP to communicate with the access nodes and it must be configured with the correct access node API URL. An error will be returned if the host is unreachable.

๐Ÿ“–The HTTP/REST API information can be found here. The public Flow HTTP/REST access nodes are accessible at:

  • Testnet https://rest-testnet.onflow.org
  • Mainnet https://rest-mainnet.onflow.org
  • Local Emulator 127.0.0.1:8888

Example:

1
import { config } from "@onflow/fcl"
2
3
config({
4
"accessNode.api": "https://rest-testnet.onflow.org"
5
})

๐Ÿ“– gRPC Access API URLs can be found here. sdk.transport must be specified if you wish to use the gRPC API. The public Flow gRPC access nodes are accessible at:

  • Testnet https://access-testnet.onflow.org
  • Mainnet https://access-mainnet.onflow.org
  • Local Emulator 127.0.0.1:3569

For local development, use the flow emulator which once started provides an HTTP access endpoint at 127.0.0.1:8888 and a gRPC access endpoint at 127.0.0.1:3569.

If using the gRPC Access API, the sdk.transport configuration key must be populated as this value defaults to the HTTP API transport. The SDK can be configured to use the gRPC API transport as follows:

1
import { config } from "@onflow/fcl"
2
import { send as transportGRPC } from "@onflow/transport-grpc"
3
4
config({
5
"accessNode.api": "https://access-testnet.onflow.org",
6
"sdk.transport": transportGRPC
7
})

Querying the Flow Network

After you have established a connection with an access node, you can query the Flow network to retrieve data about blocks, accounts, events and transactions. We will explore how to retrieve each of these entities in the sections below.

Get Blocks

Query the network for block by id, height or get the latest block.

๐Ÿ“– Block ID is SHA3-256 hash of the entire block payload. This hash is stored as an ID field on any block response object (ie. response from GetLatestBlock).

๐Ÿ“– Block height expresses the height of the block on the chain. The latest block height increases by one for every valid block produced.

Examples

This example depicts ways to get the latest block as well as any other block by height or ID:

1
import * as fcl from "@onflow/fcl";
2
3
// Get latest block
4
const latestBlock = await fcl.latestBlock(true); // If true, get the latest sealed block
5
6
// Get block by ID (uses builder function)
7
await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode);
8
9
// Get block at height (uses builder function)
10
await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode)

Result output: BlockObject

Get Account

Retrieve any account from Flow network's latest block or from a specified block height.

๐Ÿ“– Account address is a unique account identifier. Be mindful about the 0x prefix, you should use the prefix as a default representation but be careful and safely handle user inputs without the prefix.

An account includes the following data:

  • Address: the account address.
  • Balance: balance of the account.
  • Contracts: list of contracts deployed to the account.
  • Keys: list of keys associated with the account.

Examples

Example depicts ways to get an account at the latest block and at a specific block height:

1
import * as fcl from "@onflow/fcl";
2
3
// Get account from latest block height
4
const account = await fcl.account("0x1d007d755706c469");
5
6
// Get account at a specific block height
7
fcl.send([
8
fcl.getAccount("0x1d007d755706c469"),
9
fcl.atBlockHeight(123)
10
]);

Result output: AccountObject

Get Transactions

Retrieve transactions from the network by providing a transaction ID. After a transaction has been submitted, you can also get the transaction result to check the status.

๐Ÿ“– Transaction ID is a hash of the encoded transaction payload and can be calculated before submitting the transaction to the network.

โš ๏ธ The transaction ID provided must be from the current spork.

๐Ÿ“– Transaction status represents the state of a transaction in the blockchain. Status can change until it is finalized.

StatusFinalDescription
UNKNOWNโŒThe transaction has not yet been seen by the network
PENDINGโŒThe transaction has not yet been included in a block
FINALIZEDโŒThe transaction has been included in a block
EXECUTEDโŒThe transaction has been executed but the result has not yet been sealed
SEALEDโœ…The transaction has been executed and the result is sealed in a block
EXPIREDโœ…The transaction reference block is outdated before being executed
1
import * as fcl from "@onflow/fcl";
2
3
// Snapshot the transaction at a point in time
4
fcl.tx(transactionId).snapshot();
5
6
// Subscribe to a transaction's updates
7
fcl.tx(transactionId).subscribe(callback);
8
9
// Provides the transaction once the status is finalized
10
fcl.tx(transactionId).onceFinalized();
11
12
// Provides the transaction once the status is executed
13
fcl.tx(transactionId).onceExecuted();
14
15
// Provides the transaction once the status is sealed
16
fcl.tx(transactionId).onceSealed();

Result output: TransactionStatusObject

Get Events

Retrieve events by a given type in a specified block height range or through a list of block IDs.

๐Ÿ“– Event type is a string that follow a standard format:

1
A.{contract address}.{contract name}.{event name}

Please read more about events in the documentation. The exception to this standard are core events, and you should read more about them in this document.

๐Ÿ“– Block height range expresses the height of the start and end block in the chain.

Examples

Example depicts ways to get events within block range or by block IDs:

1
import * as fcl from "@onflow/fcl";
2
3
// Get events at block height range
4
await fcl
5
.send([
6
fcl.getEventsAtBlockHeightRange(
7
"A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name
8
35580624, // block to start looking for events at
9
35580624 // block to stop looking for events at
10
),
11
])
12
.then(fcl.decode);
13
14
// Get events from list of block ids
15
await fcl
16
.send([
17
fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [
18
"c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7",
19
"5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f",
20
]),
21
])
22
.then(fcl.decode);

Result output: EventObject

Get Collections

Retrieve a batch of transactions that have been included in the same block, known as collections. Collections are used to improve consensus throughput by increasing the number of transactions per block and they act as a link between a block and a transaction.

๐Ÿ“– Collection ID is SHA3-256 hash of the collection payload.

Example retrieving a collection:

1
import * as fcl from "@onflow/fcl";
2
3
const collection = await fcl
4
.send([
5
fcl.getCollection(
6
"cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5"
7
),
8
])
9
.then(fcl.decode);

Result output: CollectionObject

Execute Scripts

Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. You can learn more about Cadence here and scripts here, but we are now only interested in executing the script code and getting back the data.

We can execute a script using the latest state of the Flow blockchain or we can choose to execute the script at a specific time in history defined by a block height or block ID.

๐Ÿ“– Block ID is SHA3-256 hash of the entire block payload, but you can get that value from the block response properties.

๐Ÿ“– Block height expresses the height of the block in the chain.

1
import * as fcl from "@onflow/fcl";
2
3
const result = await fcl.query({
4
cadence: `
5
pub fun main(a: Int, b: Int, addr: Address): Int {
6
log(addr)
7
return a + b
8
}
9
`,
10
args: (arg, t) => [
11
arg(7, t.Int), // a: Int
12
arg(6, t.Int), // b: Int
13
arg("0xba1132bc08f82fe2", t.Address), // addr: Address
14
],
15
});

Example output:

1
console.log(result); // 13

Mutate Flow Network

Flow, like most blockchains, allows anybody to submit a transaction that mutates the shared global chain state. A transaction is an object that holds a payload, which describes the state mutation, and one or more authorizations that permit the transaction to mutate the state owned by specific accounts.

Transaction data is composed and signed with help of the SDK. The signed payload of transaction then gets submitted to the access node API. If a transaction is invalid or the correct number of authorizing signatures are not provided, it gets rejected.

Transactions

A transaction is nothing more than a signed set of data that includes script code which are instructions on how to mutate the network state and properties that define and limit it's execution. All these properties are explained bellow.

๐Ÿ“– Script field is the portion of the transaction that describes the state mutation logic. On Flow, transaction logic is written in Cadence. Here is an example transaction script:

1
transaction(greeting: String) {
2
execute {
3
log(greeting.concat(", World!"))
4
}
5
}

๐Ÿ“– Arguments. A transaction can accept zero or more arguments that are passed into the Cadence script. The arguments on the transaction must match the number and order declared in the Cadence script. Sample script from above accepts a single String argument.

๐Ÿ“– Proposal key must be provided to act as a sequence number and prevent replay and other potential attacks.

Each account key maintains a separate transaction sequence counter; the key that lends its sequence number to a transaction is called the proposal key.

A proposal key contains three fields:

  • Account address
  • Key index
  • Sequence number

A transaction is only valid if its declared sequence number matches the current on-chain sequence number for that key. The sequence number increments by one after the transaction is executed.

๐Ÿ“– Payer is the account that pays the fees for the transaction. A transaction must specify exactly one payer. The payer is only responsible for paying the network and gas fees; the transaction is not authorized to access resources or code stored in the payer account.

๐Ÿ“– Authorizers are accounts that authorize a transaction to read and mutate their resources. A transaction can specify zero or more authorizers, depending on how many accounts the transaction needs to access.

The number of authorizers on the transaction must match the number of AuthAccount parameters declared in the prepare statement of the Cadence script.

Example transaction with multiple authorizers:

1
transaction {
2
prepare(authorizer1: AuthAccount, authorizer2: AuthAccount) { }
3
}

๐Ÿ“– Gas limit is the limit on the amount of computation a transaction requires, and it will abort if it exceeds its gas limit. Cadence uses metering to measure the number of operations per transaction. You can read more about it in the Cadence documentation.

The gas limit depends on the complexity of the transaction script. Until dedicated gas estimation tooling exists, it's best to use the emulator to test complex transactions and determine a safe limit.

๐Ÿ“– Reference block specifies an expiration window (measured in blocks) during which a transaction is considered valid by the network. A transaction will be rejected if it is submitted past its expiry block. Flow calculates transaction expiry using the reference block field on a transaction. A transaction expires after 600 blocks are committed on top of the reference block, which takes about 10 minutes at average Mainnet block rates.

Mutate

FCL "mutate" does the work of building, signing, and sending a transaction behind the scenes. In order to mutate the blockchain state using FCL, you need to do the following:

1
import * as fcl from "@onflow/fcl"
2
3
await fcl.mutate({
4
cadence: `
5
transaction(a: Int) {
6
prepare(acct: AuthAccount) {
7
log(acct)
8
log(a)
9
}
10
}
11
`,
12
args: (arg, t) => [
13
arg(6, t.Int)
14
],
15
limit: 50
16
})

Flow supports great flexibility when it comes to transaction signing, we can define multiple authorizers (multi-sig transactions) and have different payer account than proposer. We will explore advanced signing scenarios bellow.

  • Proposer, payer and authorizer are the same account (0x01).
  • Only the envelope must be signed.
  • Proposal key must have full signing weight.
AccountKey IDWeight
0x0111000
1
// There are multiple ways to acheive this
2
import * as fcl from "@onflow/fcl"
3
4
// FCL provides currentUser as an authorization function
5
await fcl.mutate({
6
cadence: `
7
transaction {
8
prepare(acct: AuthAccount) {}
9
}
10
`,
11
proposer: currentUser,
12
payer: currentUser,
13
authorizations: [currentUser],
14
limit: 50,
15
})
16
17
// Or, simplified
18
19
mutate({
20
cadence: `
21
transaction {
22
prepare(acct: AuthAccount) {}
23
}
24
`,
25
authz: currentUser, // Optional. Will default to currentUser if not provided.
26
limit: 50,
27
})
28
29
30
// Or, create a custom authorization function
31
const authzFn = async (txAccount) => {
32
return {
33
...txAccount,
34
addr: "0x01",
35
keyId: 0,
36
signingFunction: async(signable) => {
37
return {
38
addr: "0x01",
39
keyId: 0,
40
signature
41
}
42
}
43
}
44
}
45
46
mutate({
47
cadence: `
48
transaction {
49
prepare(acct: AuthAccount) {}
50
}
51
`,
52
proposer: authzFn,
53
payer: authzFn,
54
authorizations: [authzFn],
55
limit: 50,
56
})

  • Proposer, payer and authorizer are the same account (0x01).
  • Only the envelope must be signed.
  • Each key has weight 500, so two signatures are required.
AccountKey IDWeight
0x011500
0x012500

1
import * as fcl from "@onflow/fcl"
2
3
const authzFn = async (txAccount) => {
4
return [
5
{
6
...txAccount,
7
addr: "0x01",
8
keyId: 0,
9
signingFunction: async(signable) => {
10
return {
11
addr: "0x01",
12
keyId: 0,
13
signature
14
}
15
}
16
},
17
{
18
...txAccount,
19
addr: "0x01",
20
keyId: 1,
21
signingFunction: async(signable) => {
22
return {
23
addr: "0x01",
24
keyId: 1,
25
signature
26
}
27
}
28
}
29
]
30
}
31
32
mutate({
33
cadence: `
34
transaction {
35
prepare(acct: AuthAccount) {}
36
}
37
`,
38
proposer: authzFn,
39
payer: authzFn,
40
authorizations: [authzFn],
41
limit: 50,
42
})

  • Proposer and authorizer are the same account (0x01).
  • Payer is a separate account (0x02).
  • Account 0x01 signs the payload.
  • Account 0x02 signs the envelope.
    • Account 0x02 must sign last since it is the payer.
AccountKey IDWeight
0x0111000
0x0231000

1
import * as fcl from "@onflow/fcl"
2
3
const authzFn = async (txAccount) => {
4
return {
5
...txAccount,
6
addr: "0x01",
7
keyId: 0,
8
signingFunction: async(signable) => {
9
return {
10
addr: "0x01",
11
keyId: 0,
12
signature
13
}
14
}
15
}
16
}
17
18
const authzTwoFn = async (txAccount) => {
19
return {
20
...txAccount,
21
addr: "0x02",
22
keyId: 0,
23
signingFunction: async(signable) => {
24
return {
25
addr: "0x02",
26
keyId: 0,
27
signature
28
}
29
}
30
}
31
}
32
33
mutate({
34
cadence: `
35
transaction {
36
prepare(acct: AuthAccount) {}
37
}
38
`,
39
proposer: authzFn,
40
payer: authzTwoFn,
41
authorizations: [authzFn],
42
limit: 50,
43
})

  • Proposer and authorizer are the same account (0x01).
  • Payer is a separate account (0x02).
  • Account 0x01 signs the payload.
  • Account 0x02 signs the envelope.
    • Account 0x02 must sign last since it is the payer.
  • Account 0x02 is also an authorizer to show how to include two AuthAccounts into an transaction
AccountKey IDWeight
0x0111000
0x0231000

1
import * as fcl from "@onflow/fcl"
2
3
const authzFn = async (txAccount) => {
4
return {
5
...txAccount,
6
addr: "0x01",
7
keyId: 0,
8
signingFunction: async(signable) => {
9
return {
10
addr: "0x01",
11
keyId: 0,
12
signature
13
}
14
}
15
}
16
}
17
18
const authzTwoFn = async (txAccount) => {
19
return {
20
...txAccount,
21
addr: "0x02",
22
keyId: 0,
23
signingFunction: async(signable) => {
24
return {
25
addr: "0x02",
26
keyId: 0,
27
signature
28
}
29
}
30
}
31
}
32
33
mutate({
34
cadence: `
35
transaction {
36
prepare(acct: AuthAccount, acct2: AuthAccount) {}
37
}
38
`,
39
proposer: authzFn,
40
payer: authzTwoFn,
41
authorizations: [authzFn, authzTwoFn],
42
limit: 50,
43
})

  • Proposer and authorizer are the same account (0x01).
  • Payer is a separate account (0x02).
  • Account 0x01 signs the payload.
  • Account 0x02 signs the envelope.
    • Account 0x02 must sign last since it is the payer.
  • Both accounts must sign twice (once with each of their keys).
AccountKey IDWeight
0x011500
0x012500
0x023500
0x024500

// TODO example link

1
import * as fcl from "@onflow/fcl"
2
3
const authzFn = async (txAccount) => {
4
return [
5
{
6
...txAccount,
7
addr: "0x01",
8
keyId: 0,
9
signingFunction: async(signable) => {
10
return {
11
addr: "0x01",
12
keyId: 0,
13
signature
14
}
15
}
16
},
17
{
18
...txAccount,
19
addr: "0x01",
20
keyId: 1,
21
signingFunction: async(signable) => {
22
return {
23
addr: "0x01",
24
keyId: 1,
25
signature
26
}
27
}
28
}
29
]
30
}
31
32
const authzTwoFn = async (txAccount) => {
33
return [
34
{
35
...txAccount,
36
addr: "0x02",
37
keyId: 0,
38
signingFunction: async(signable) => {
39
return {
40
addr: "0x02",
41
keyId: 0,
42
signature
43
}
44
}
45
},
46
{
47
...txAccount,
48
addr: "0x02",
49
keyId: 1,
50
signingFunction: async(signable) => {
51
return {
52
addr: "0x02",
53
keyId: 1,
54
signature
55
}
56
}
57
}
58
]
59
}
60
61
mutate({
62
cadence: `
63
transaction {
64
prepare(acct: AuthAccount) {}
65
}
66
`,
67
proposer: authzFn,
68
payer: authzTwoFn,
69
authorizations: [authzFn],
70
limit: 50,
71
})

After a transaction has been built and signed, it can be sent to the Flow blockchain where it will be executed. If sending was successful you can then retrieve the transaction result.