@onflow/sdk
Low-level JavaScript/TypeScript SDK for interacting with the Flow blockchain.
Overview
The Flow sdk provides a set of tools for developers to build applications on the Flow blockchain.
Installation
You can install the @onflow/sdk package using npm or yarn:
_10npm install @onflow/sdk
Or using yarn:
_10yarn add @onflow/sdk
Requirements
- Node.js 14.x or later
Importing
You can import the entire package:
_10import * as sdk from "@onflow/sdk"
Or import specific functions:
_10import { functionName } from "@onflow/sdk"
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.
Example:
_10import { config } from "@onflow/fcl"_10_10config({_10 "accessNode.api": "https://rest-testnet.onflow.org"_10})
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.
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 below.
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:
_10transaction(greeting: string) {_10 execute {_10 log(greeting.concat(", World!"))_10 }_10}
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 &Account
parameters declared in the prepare statement of the Cadence script.
Example transaction with multiple authorizers:
_10transaction {_10 prepare(authorizer1: &Account, authorizer2: &Account) { }_10}
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.
API Reference
This section contains documentation for all of the functions in the sdk package.
- account - Retrieve any account from Flow network's latest block or from a specified block...
- arg - A utility builder to be used with fcl.args[...] to create FCL supported...
- args - A utility builder to be used with other builders to pass in arguments with a...
- atBlockHeight - A builder function that returns a partial interaction to a block at a specific...
- atBlockId - A builder function that returns a partial interaction to a block at a specific...
- atLatestBlock - A builder function that returns a partial interaction to query the latest block...
- authorization - Creates an authorization function for use in transactions. An authorization...
- authorizations - A utility builder to set the authorizations on a transaction. Authorizations...
- authzDeepResolveMany - Creates a deep test authorization resolver with nested resolution for complex...
- authzFn - Creates a test authorization function for testing transactions.
- authzResolve - Creates a test authorization resolver that can be used for testing account...
- authzResolveMany - Creates a test authorization resolver that handles multiple accounts with...
- Bad - Marks an interaction as failed with a specific reason and returns the...
- block - Query the network for block by id, height or get the latest block. Block ID is...
- build - A builder function that creates an interaction from an array of builder...
- buildPreSignable - Builds a pre-signable object containing interaction data before signing.
- buildSignable - Builds a signable object that can be signed by an authorization function.
- cadence - Creates a template function
- cdc - Creates a template function
- config - Sets the config
- createSignableVoucher - Creates a signable voucher object from an interaction for signing purposes. A...
- decode - Decodes the response from 'fcl.send()' into the appropriate JSON representation...
- decodeResponse - Decodes a response from Flow into JSON
- decodeStream - Pipes a generic stream of data into a granular stream of decoded data. The data...
- destroy - Removes a property from an interaction object using a dot-notation key path.
- encodeMessageFromSignable - Encodes a message from a signable object for a specific signer address. This...
- encodeTransactionEnvelope - Encodes a complete transaction envelope including payload and signatures. This...
- encodeTransactionPayload - Encodes a transaction payload for signing. This function takes a transaction...
- encodeTxIdFromVoucher - Encodes a transaction ID from a voucher by computing its hash. A voucher is an...
- findInsideSigners - Identifies signers for the transaction payload (authorizers + proposer,...
- findOutsideSigners - Identifies signers for the transaction envelope (payer accounts only). This...
- get - Gets a value from an interaction object using a dot-notation key path.
- getAccount - A builder function that returns the interaction to get an account by address....
- getBlock - A builder function that returns the interaction to get the latest block. Use...
- getBlockHeader - A builder function that returns the interaction to get a block header. A block...
- getCollection - A builder function that returns a collection containing a list of transaction...
- getEvents - A builder function that returns the interaction to get events. Events are...
- getEventsAtBlockHeightRange - A builder function that returns all instances of a particular event (by name)...
- getEventsAtBlockIds - A builder function that returns all instances of a particular event (by name)...
- getLatestBlock - A builder function that returns the interaction to get the latest block This...
- getNetworkParameters - A builder function that returns the interaction to get network parameters....
- getNodeVersionInfo - A builder function for the Get Node Version Info interaction. Creates an...
- getTransaction - A builder function that returns the interaction to get a transaction by id....
- getTransactionStatus - A builder function that returns the status of transaction. The transaction id...
- getTransport - Get the SDK transport object, either from the provided override or from the...
- idof - Generates a unique identifier for an account based on its address and key ID.
- initAccount - Creates a new account object with default values.
- initInteraction - Creates a new interaction object with default values.
- interaction - Creates a new interaction object with default values.
- isAccount - Checks if an object is an account resolver.
- isArgument - Checks if an object is an argument resolver.
- isArray - Checks if a value is an array.
- isBad - Checks if an interaction has a failed status.
- isFn - Checks if a value is a function.
- isInteraction - Checks if an object is a valid interaction.
- isNull - Checks if a value is null or undefined.
- isNumber - Checks if a value is a number.
- isObj - Checks if a value is an object (but not null).
- isOk - Checks if an interaction has a successful status.
- limit - A utility builder to set the compute limit on a transaction. The compute limit...
- makeArgument - Creates an argument resolver and adds it to an interaction. This function is...
- nodeVersionInfo - Retrieve version information from the connected Flow Access Node. This function...
- Ok - Marks an interaction as successful and returns the interaction object.
- param - Legacy function for setting a single parameter on an interaction.
- params - Legacy function for setting parameters on an interaction.
- payer - A builder function that adds payer account(s) to a transaction. Every...
- ping - A builder function that creates a ping interaction to test connectivity to the...
- pipe - Async pipe function to compose interactions. The pipe function is the foundation...
- prepAccount - Prepares and configures an account for use in an interaction with a specific...
- proposer - A builder function that adds the proposer to a transaction. The proposer is...
- put - Sets a value in an interaction object using a dot-notation key path.
- ref - A builder function that sets the reference block for a transaction. The...
- resolveAccounts - Resolves account authorization functions and validates account configurations...
- resolveArguments - Resolves transaction arguments by evaluating argument functions and converting...
- resolveCadence - Resolves Cadence code by evaluating functions and replacing contract...
- resolveComputeLimit - Resolves the compute limit for a transaction from configuration or applies...
- resolveFinalNormalization - Normalizes account addresses by removing the "0x" prefix from all account...
- resolveProposerSequenceNumber - Resolves the sequence number for the proposer account by querying the...
- resolveRefBlockId - Resolves the reference block ID for a transaction by querying the latest block...
- resolveSignatures - Resolves signatures for a transaction by coordinating the signing process for...
- resolveValidators - Executes validator functions that have been attached to an interaction to...
- resolveVoucherIntercept - Resolves voucher intercept functions by calling them with the current voucher.
- response - Creates a default response object
- run - Runs a set of functions on an interaction This is a utility function for testing...
- script - A builder function that creates a script interaction. Scripts allow you to write...
- send - Sends arbitrary scripts, transactions, and requests to Flow. This method...
- sig - Generates a test signature string for an account.
- subscribe - Subscribe to real-time data from the Flow blockchain and automatically decode...
- subscribeEvents - Subscribe to events with the given filter and parameters. Creates a subscription...
- subscribeRaw - Subscribe to a topic without decoding the data. This function creates a raw...
- transaction - A template builder to use a Cadence transaction for an interaction. FCL "mutate"...
- update - Updates a value in an interaction object using a transformation function.
- validateSignableTransaction - Validates that a signable transaction is properly formed and contains the...
- validator - A builder function that adds a validator to a transaction. Validators are...
- voucherIntercept - A builder function that intercepts and modifies a voucher. This function is...
- voucherToTxId - Converts a voucher object to a transaction ID. This function computes the...
- why - Returns the reason for an interaction failure.