diff --git a/docs/build/guides/mobile/react-native-quickstart.md b/docs/build/guides/mobile/react-native-quickstart.md index b3334dca51..07c11c75e2 100644 --- a/docs/build/guides/mobile/react-native-quickstart.md +++ b/docs/build/guides/mobile/react-native-quickstart.md @@ -89,7 +89,7 @@ config({ - The `accessNode.api` key specifies the address of a Flow access node. Flow provides these, but in the future access to Flow may be provided by other 3rd parties, through their own access nodes. - `discovery.wallet` and `discovery.authn.endpoint` are addresses that point to a service that lists FCL compatible wallets. Flow's FCL Discovery service is a service that FCL wallet providers can be added to, and be made 'discoverable' to any application that uses the `discovery.wallet` and `discovery.authn.endpoint`. -> Learn more about [configuring Discovery](../../../tools/clients/fcl-js/discovery.md) or [setting configuration values](../../../tools/clients/fcl-js/api.md#setting-configuration-values). +> Learn more about [configuring Discovery](../../../tools/clients/fcl-js/discovery.md) or [setting configuration values](../../../tools/clients/fcl-js/packages-docs/fcl/index.md#setting-configuration-values). > If you are running a Wallet Discovery locally and want to use it in the React Native app, change `https://fcl-discovery.onflow.org/` to `http://:/` > For Example: @@ -140,7 +140,7 @@ Now we're ready to start talking to Flow! To authenticate a user, you'll need to render a `ServiceDiscovery` component provided by `fcl-react-native`. Alternatively you can build your own component using `useServiceDiscovery`. -Unauthenticate is as simple as calling `fcl.unauthenticate()`. Once authenticated, FCL sets an object called `fcl.currentUser` which exposes methods for watching changes in user data, signing transactions, and more. For more information on the `currentUser`, read more [here](../../../tools/clients/fcl-js/api.md#current-user). +Unauthenticate is as simple as calling `fcl.unauthenticate()`. Once authenticated, FCL sets an object called `fcl.currentUser` which exposes methods for watching changes in user data, signing transactions, and more. Let's add in a few components and buttons buttons for sign up/login and also subscribe to changes on the `currentUser`. When the user is updated (which it will be after authentication), we'll set the user state in our component to reflect this. To demonstrate user authenticated sessions, we'll conditionally render a component based on if the user is or is not logged in. @@ -313,7 +313,7 @@ await fcl.query({ Inside the query you'll see we set two things: `cadence` and `args`. Cadence is Flow's smart contract language we mentioned. For this tutorial, when you look at it you just need to notice that it's importing the `Profile` contract from the account we named `0xProfile` earlier in our config file, then also taking an account address, and reading it. That's it until you're ready to [learn more Cadence](https://cadence-lang.org/docs). -In the `args` section, we are simply passing it our user's account address from the user we set in state after authentication and giving it a type of `Address`. For more possible types, [see this reference](../../../tools/clients/fcl-js/api.md#ftype). +In the `args` section, we are simply passing it our user's account address from the user we set in state after authentication and giving it a type of `Address`. For more possible types, [see this reference](../../../tools/clients/fcl-js/packages-docs/types/index.md). Go ahead and click the "Send Query" button. You should see "No Profile." That's because we haven't initialized the account yet. @@ -638,7 +638,7 @@ const styles = StyleSheet.create({ }); ``` -Now if you click the "Execute Transaction" button you'll see the statuses update next to "Transaction Status." When you see "4" that means it's sealed! Status code meanings [can be found here](../../../tools/clients/fcl-js/api.md#transaction-statuses). +Now if you click the "Execute Transaction" button you'll see the statuses update next to "Transaction Status." When you see "4" that means it's sealed! Status code meanings [can be found here](../../../tools/clients/fcl-js/packages-docs/types/index.md). If you query the account profile again, "Profile Name:" should now display "Flow Developer". That's it! You now have a shippable Flow dapp that can auth, query, init accounts, and mutate the chain. This is just the beginning. There is so much more to know. We have a lot more resources to help you build. To dive deeper, here are a few good places for taking the next steps: @@ -655,7 +655,7 @@ That's it! You now have a shippable Flow dapp that can auth, query, init account **More FCL** -- [FCL API Quick Reference](../../../tools/clients/fcl-js/api) +- [FCL API Quick Reference](../../../tools/clients/fcl-js/packages-docs/fcl-react-native/index.md) - [More on Scripts](../../../tools/clients/fcl-js/scripts.md) - [More on Transactions](../../../tools/clients/fcl-js/transactions.md) - [User Signatures](../../../tools/clients/fcl-js/user-signatures.md) diff --git a/docs/tools/clients/fcl-js/api.md b/docs/tools/clients/fcl-js/api.md deleted file mode 100644 index 3b8a2fb407..0000000000 --- a/docs/tools/clients/fcl-js/api.md +++ /dev/null @@ -1,2655 +0,0 @@ ---- -sidebar_label: FCL Reference -sidebar_position: 2 ---- - -# Flow Client Library (FCL) API Reference - -> For release updates, [see the repo](https://github.com/onflow/fcl-js/releases) - -## 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. - -```javascript -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. - -```javascript -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 - -| 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](https://developers.onflow.org/http-api/). | -| `app.detail.title` | `Cryptokitties` | Your applications title, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | -| `app.detail.icon` | `https://fcl-discovery.onflow.org/images/blocto.png` | Url for your applications icon, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | -| `app.detail.description` | `Cryptokitties is a blockchain game` | Your applications description, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | -| `app.detail.url` | `https://cryptokitties.co` | Your applications url, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | -| `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) | -| `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`, `testnet`, `mainnet`. | -| `walletconnect.projectId` | `YOUR_PROJECT_ID` | Your app's WalletConnect project ID. See [WalletConnect Cloud](https://cloud.walletconnect.com/sign-in) to obtain a project ID for your application. | -| `walletconnect.disableNotifications` | `false` | Optional flag to disable pending WalletConnect request notifications within the application's UI. | - -## Using Contracts in Scripts and Transactions - -### Address Replacement - -Configuration keys that start with `0x` will be replaced in FCL scripts and transactions, this allows you to write your script or transaction Cadence code once and not have to change it when you point your application at a difference instance of the Flow Blockchain. - -```javascript -import * as fcl from '@onflow/fcl'; - -fcl.config().put('0xFungibleToken', '0xf233dcee88fe0abe'); - -async function myScript() { - return fcl - .send([ - fcl.script` - import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration - - access(all) fun main() { /* Rest of the script goes here */ } - `, - ]) - .then(fcl.decode); -} - -async function myTransaction() { - return fcl - .send([ - fcl.transaction` - import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration - - transaction { /* Rest of the transaction goes here */ } - `, - ]) - .then(fcl.decode); -} -``` - -#### Example - -```javascript -import * as fcl from '@onflow/fcl'; - -fcl - .config() - .put('flow.network', 'testnet') - .put('walletconnect.projectId', 'YOUR_PROJECT_ID') - .put('accessNode.api', 'https://rest-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('app.detail.description', 'A test harness for FCL') - .put('app.detail.url', 'https://myapp.com') - .put('service.OpenID.scopes', 'email email_verified name zoneinfo') - .put('0xFlowToken', '0x7e60df042a9c0868'); -``` - -### Using `flow.json` for Contract Imports - -A simpler and more flexible way to manage contract imports in scripts and transactions is by using the `config.load` method in FCL. This lets you load contract configurations from a `flow.json` file, keeping your import syntax clean and allowing FCL to pick the correct contract addresses based on the network you're using. - -### Setting Up - -#### 1. Define Your Contracts in `flow.json` - -Here’s an example of a `flow.json` file with aliases for multiple networks: - -```json -{ - "contracts": { - "HelloWorld": { - "source": "./cadence/contracts/HelloWorld.cdc", - "aliases": { - "testnet": "0x1cf0e2f2f715450", - "mainnet": "0xf8d6e0586b0a20c7" - } - } - } -} -``` - -- **`source`**: Points to the contract file in your project. -- **`aliases`**: Maps each network to the correct contract address. - -#### 2. Configure FCL - -Load the `flow.json` file and set up FCL to use it: - -```javascript -import { config } from '@onflow/fcl'; -import flowJSON from '../flow.json'; - -config({ - 'flow.network': 'testnet', // Choose your network, e.g., testnet or mainnet - 'accessNode.api': 'https://rest-testnet.onflow.org', // Access node for the network - 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`, // Wallet discovery -}).load({ flowJSON }); -``` - -With this setup, FCL will automatically use the correct contract address based on the selected network (e.g., `testnet` or `mainnet`). - -#### 3. Use Contract Names in Scripts and Transactions - -After setting up `flow.json`, you can import contracts by name in your Cadence scripts or transactions: - -```cadence -import "HelloWorld" - -access(all) fun main(): String { - return HelloWorld.sayHello() -} -``` - -FCL replaces `"HelloWorld"` with the correct address from the `flow.json` configuration. - -> **Note**: Don’t store private keys in your `flow.json`. Instead, use the [key/location syntax](../../../tools/flow-cli/flow.json/security.md) to keep sensitive keys in a separate, `.gitignore`-protected file. - -## Wallet Interactions - -These methods allows dapps to interact with FCL compatible wallets in order to authenticate the user and authorize transactions on their behalf. - -> ⚠️These methods are **async**. - ---- - -### `authenticate` - -> ⚠️**This method can only be used in web browsers.** - -Calling this method will authenticate the current user via any wallet that supports FCL. Once called, FCL will initiate communication with the configured `discovery.wallet` endpoint which lets the user select a wallet to authenticate with. Once the wallet provider has authenticated the user, FCL will set the values on the [current user](#currentuserobject) object for future use and authorization. - -#### Note - -⚠️`discovery.wallet` value **must** be set in the configuration before calling this method. See [FCL Configuration](#configuration). - -📣 The default discovery endpoint will open an iframe overlay to let the user choose a supported wallet. - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -fcl - .config() - .put('accessNode.api', 'https://rest-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](#discovery) with `fcl.authenticate({ service })`. - ---- - -### `unauthenticate` - -> ⚠️**This method can only be used in web browsers.** - -Logs out the current user and sets the values on the [current user](#currentuserobject) object to null. - -#### Note - -⚠️The current user must be authenticated first. - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -fcl.config().put('accessNode.api', 'https://rest-testnet.onflow.org'); -// first authenticate to set current user -fcl.authenticate(); -// ... somewhere else & sometime later -fcl.unauthenticate(); -// fcl.currentUser.loggedIn === null -``` - ---- - -### `reauthenticate` - -> ⚠️**This method can only be used in web browsers.** - -A **convenience method** that calls [`fcl.unauthenticate()`](#unauthenticate) and then [`fcl.authenticate()`](#authenticate) for the current user. - -#### Note - -⚠️The current user must be authenticated first. - -#### Usage - -```javascript -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 -``` - ---- - -### `signUp` - -> ⚠️**This method can only be used in web browsers.** - -A **convenience method** that calls and is equivalent to [`fcl.authenticate()`](#authenticate). - ---- - -### `logIn` - -> ⚠️**This method can only be used in web browsers.** - -A **convenience method** that calls and is equivalent to [`fcl.authenticate()`](#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](#authorization-function) if needed. - -#### Returns - -| Type | Description | -| ------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| [AuthorizationObject](#authorizationobject) | An object containing the necessary details from the current user to authorize a transaction in any role. | - -#### Usage - -**Note:** The default values for `proposer`, `payer`, and `authorizations` are already `fcl.authz` so there is no need to include these parameters, it is shown only for example purposes. See more on [signing roles](../../../build/basics/transactions.md). - -```javascript -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: auth(BorrowValue) &Account) { - account.storage.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](#currentuserobject), if set, and offers a set of functions to manage the authentication and authorization of the user. - -> ⚠️**The following methods can only be used in web browsers.** - ---- - -### `currentUser.subscribe` - -The callback passed to subscribe will be called when the user authenticates and un-authenticates, making it easy to update the UI accordingly. - -#### Arguments - -| Name | Type | | -| ---------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | -| `callback` | function | The callback will be called with the [current user](#currentuserobject) as the first argument when the current user is set or removed. | - -#### Usage - -```javascript -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 ( -
- {user?.addr ?? 'No Address'} - {/* once logged out in setUser(user) will be called */} -
- ); - } else { - return ( -
- {' '} - {/* once logged in setUser(user) will be called */} - {/* once signed up, setUser(user) will be called */} -
- ); - } -} -``` - ---- - -### `currentUser.snapshot` - -Returns the [current user](#currentuserobject) object. This is the same object that is set and available on [`fcl.currentUser.subscribe(callback)`](#currentusersubscribe). - -#### Usage - -```javascript -// 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 - -| Name | Type | Description | -| --------- | --------------------- | --------------------------------- | -| `message` | string **(required)** | A hexadecimal string to be signed | - -#### Returns - -| Type | Description | -| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Array` | An Array of [CompositeSignatures](https://github.com/onflow/fcl-js/blob/master/packages/fcl-core/src/wallet-provider-spec/draft-v2.md#compositesignature): {`addr`, `keyId`, `signature`} | - -#### Usage - -```javascript -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](../../../build/getting-started/fcl-quickstart.md) 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](#configuration). - -### Suggested Configuration - -| Environment | Example | -| ----------- | ---------------------------------------------------- | -| Mainnet | `https://fcl-discovery.onflow.org/api/authn` | -| Testnet | `https://fcl-discovery.onflow.org/api/testnet/authn` | - -If the Discovery endpoint is set in config, then you can iterate through authn services and pass the chosen service to [authenticate](#authenticate) to authenticate a user. - -#### Usage - -```javascript -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 ( -
- {wallets.map((wallet) => ( - - ))} -
- ); -} -``` - -### authn - -#### More Configuration - -By default, limited functionality services or services that require developer registration, like Ledger or Dapper Wallet, require apps to opt-in in order to display to users. To enable opt-in services in an application, use the `discovery.authn.include` property in your configuration with a value of an array of services you'd like your app to opt-in to displaying for users. - -Additionally, you can use the `discovery.authn.exclude` property to exclude any services from being displayed to users. - -```javascript -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 - 'discovery.authn.exclude': ['0x123456789abcdef01'], // Example of excluding a wallet by address -}); -``` - -**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](https://github.com/onflow/fcl-discovery/blob/87e172db85d185882d9fde007c95f08bc2a1cccb/data/services.json). - ---- - -### `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](../../../networks/access-onchain-data/index.md). - ---- - -### Query and Mutate Flow with Cadence - -If you want to run arbitrary Cadence scripts on the blockchain, these methods offer a convenient way to do so **without having to build, send, and decode interactions**. - -### `query` - -Allows you to submit scripts to query the blockchain. - -#### Options - -_Pass in the following as a single object with the following keys.All keys are optional unless otherwise stated._ - -| Key | Type | Description | -| --------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cadence` | string **(required)** | A valid cadence script. | -| `args` | [ArgumentFunction](#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](../../../build/basics/fees.md) for information about how computation cost is calculated on Flow. | - -#### Returns - -| Type | Description | -| ---- | -------------------------------------- | -| any | A JSON representation of the response. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const result = await fcl.query({ - cadence: ` - access(all) 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 - -- [Additional Explanation](https://gist.github.com/orodio/3bf977a0bd45b990d16fdc1459b129a2) - ---- - -### `mutate` - -Allows you to submit transactions to the blockchain to potentially mutate the state. - -⚠️When being used in the browser, `fcl.mutate` uses the built-in `fcl.authz` function to produce the authorization (signatures) for the current user. When calling this method from Node.js, you will need to supply your own custom authorization function. - -#### Options - -_Pass in the following as a single object with the following keys. All keys are optional unless otherwise stated._ - -| Key | Type | Description | -| ---------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cadence` | string **(required)** | A valid cadence transaction. | -| `args` | [ArgumentFunction](#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](../flow-go-sdk/index.md#gas-limit) for information about how computation cost is calculated on Flow. | -| `proposer` | [AuthorizationFunction](#authorization-function) | The authorization function that returns a valid [AuthorizationObject](#authorizationobject) for the [proposer role](#transactionrolesobject). | - -#### Returns - -| Type | Description | -| ------ | ------------------- | -| string | The transaction ID. | - -#### Usage - -```javascript -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: auth(BorrowValue) &Account) { - account.storage.borrow<&{Profile.Owner}>(from: Profile.privatePath)!.setName(name) - } - } - `, - args: (arg, t) => [arg('myName', t.String)], -}); -``` - -#### Examples - -- [Additional explanation](https://gist.github.com/orodio/3bf977a0bd45b990d16fdc1459b129a2) -- [Custom authorization function](#authorization-function) - ---- - -### `verifyUserSignatures` (Deprecated) - -Use `fcl.AppUtils.verifyUserSignatures` - -## AppUtils - -### `AppUtils.verifyUserSignatures` - -A method allowing applications to cryptographically verify a message was signed by a user's private key/s. This is typically used with the response from `currentUser.signUserMessage`. - -#### Note - -⚠️ `fcl.config.flow.network` or options override is required to use this api. See [FCL Configuration](#configuration). - -#### Arguments - -| Name | Type | Description | -| --------------------- | --------------------- | ---------------------------------------------------------------------------------------------------- | -| `message` | string **(required)** | A hexadecimal string | -| `compositeSignatures` | Array **(required)** | An Array of `CompositeSignatures` | -| `opts` | Object **(optional)** | `opts.fclCryptoContract` can be provided to override FCLCryptoContract address for local development | - -#### Returns - -| Type | Description | -| ------- | ----------------------------- | -| Boolean | `true` if verified or `false` | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const isValid = await fcl.AppUtils.verifyUserSignatures( - Buffer.from('FOO').toString('hex'), - [ - { - f_type: 'CompositeSignature', - f_vsn: '1.0.0', - addr: '0x123', - keyId: 0, - signature: 'abc123', - }, - ], - { fclCryptoContract }, -); -``` - -#### Examples - -- [fcl-next-harness](https://github.com/onflow/fcl-next-harness) - ---- - -### `AppUtils.verifyAccountProof` - -A method allowing applications to cryptographically prove that a user controls an on-chain account. During user authentication, some FCL compatible wallets will choose to support the FCL `account-proof` service. If a wallet chooses to support this service, and the user approves the signing of message data, they will return `account-proof` data and a signature(s) that can be used to prove a user controls an on-chain account. -See [proving-authentication](https://github.com/onflow/fcl-js/blob/master/docs/reference/proving-authentication.mdx) documentation for more details. - -⚠️ `fcl.config.flow.network` or options override is required to use this api. See [FCL Configuration](#configuration). - -#### Arguments - -| Name | Type | Description | -| ------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `appIdentifier` | string **(required)** | A hexadecimal string | -| `accountProofData` | Object **(required)** | Object with properties:
`address`: `string` - A Flow account address.
`nonce`: `string` - A random string in hexadecimal format (minimum 32 bytes in total, i.e 64 hex characters)
`signatures`: `Object[]` - An array of composite signatures to verify | -| `opts` | Object **(optional)** | `opts.fclCryptoContract` can be provided to overide FCLCryptoContract address for local development | - -#### Returns - -| Type | Description | -| ------- | ----------------------------- | -| Boolean | `true` if verified or `false` | - -#### Usage - -```javascript -import * as fcl from "@onflow/fcl" - -const accountProofData = { - address: "0x123", - nonce: "F0123" - signatures: [{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}], -} - -const isValid = await fcl.AppUtils.verifyAccountProof( - "AwesomeAppId", - accountProofData, - {fclCryptoContract} -) - -``` - -#### Examples - -- [fcl-next-harness](https://github.com/onflow/fcl-next-harness) - ---- - -### 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](#builders) that are to be resolved and sent. The builders required to be included in the array depend on the [interaction](#interaction) that is being built. - -#### Note - -⚠️Must be used in conjuction with [`fcl.decode(response)`](#decode) to get back correct keys and all values in JSON. - -#### Arguments - -| Name | Type | Description | -| ---------- | ----------------------- | ---------------------- | -| `builders` | [[Builders](#builders)] | See builder functions. | - -#### Returns - -| Type | Description | -| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| [ResponseObject](#responseobject) | An object containing the data returned from the chain. Should always be decoded with `fcl.decode()` to get back appropriate JSON keys and values. | - -#### Usage - -```javascript -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) -``` - ---- - -### `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`](https://github.com/onflow/fcl-js/tree/master/packages/sdk/src/decode). - -#### Arguments - -| Name | Type | Description | -| ---------- | --------------------------------- | ------------------------------------------------------ | -| `response` | [ResponseObject](#responseobject) | Should be the response returned from `fcl.send([...])` | - -#### Returns - -| Type | Description | -| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| any | A JSON representation of the raw string response depending on the cadence code executed.
The return value can be a single value and type or an object with multiple types. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -// simple script to add 2 numbers -const response = await fcl.send([ - fcl.script` - access(all) 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'); -``` - ---- - -## 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](#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)`](#account) if you do not need to pair with any other builders. - -#### Arguments - -| Name | Type | Description | -| --------- | ------------------- | ---------------------------------------------------------------------------------- | -| `address` | [Address](#address) | Address of the user account with or without a prefix (both formats are supported). | - -#### Returns after decoding - -| Type | Description | -| ------------------------- | ---------------------------------------- | -| [AccountObject](#account) | A JSON representation of a user account. | - -#### Usage - -```javascript -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.getblock(isSealed)`](#getblock) if you do not need to pair with any other builders. - -#### Arguments - -| Name | Type | Default | Description | -| ---------- | ------- | ------- | ------------------------------------------------------------------------------ | -| `isSealed` | boolean | false | If the latest block should be sealed or not. See [block states](#interaction). | - -#### Returns after decoding - -| Type | Description | -| --------------------------- | ----------------------------------------------------- | -| [BlockObject](#blockobject) | The latest block if not used with any other builders. | - -#### Usage - -```javascript -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()`](#getblock) to get a full interaction at the specified block height. - -#### Arguments - -| Name | Type | Description | -| ------------- | ------ | ------------------------------------------------------ | -| `blockHeight` | number | The height of the block to execute the interaction at. | - -#### Returns - -| Type | Description | -| ----------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| [Partial Interaction](#interaction) | A partial interaction to be paired with another interaction such as `fcl.getBlock()` or `fcl.getAccount()`. | - -#### Usage - -```javascript -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()`](#getblock) to get a full interaction at the specified block ID. - -#### Arguments - -| Name | Type | Description | -| --------- | ------ | -------------------------------------------------- | -| `blockId` | string | The ID of the block to execute the interaction at. | - -#### Returns - -| Type | Description | -| ----------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| [Partial Interaction](#interaction) | A partial interaction to be paired with another interaction such as `fcl.getBlock()` or `fcl.getAccount()`. | - -#### Usage - -```javascript -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 - -| Type | Description | -| --------------------------------------- | ------------------------------------------------------------ | -| [BlockHeaderObject](#blockheaderobject) | The latest block header if not used with any other builders. | - -#### Usage - -```javascript -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 - -| Name | Type | Description | -| ----------------- | ----------------------- | ---------------------------------------------------------------- | -| `eventName` | [EventName](#eventname) | The name of the event. | -| `fromBlockHeight` | number | The height of the block to start looking for events (inclusive). | -| `toBlockHeight` | number | The height of the block to stop looking for events (inclusive). | - -#### Returns after decoding - -| Type | Description | -| ------------------------------ | ---------------------------------------------- | -| [[EventObject]](#event-object) | An array of events that matched the eventName. | - -#### Usage - -```javascript -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 - -| Name | Type | Description | -| ----------- | ----------------------- | ----------------------------------------- | -| `eventName` | [EventName](#eventname) | The name of the event. | -| `blockIds` | number | The ids of the blocks to scan for events. | - -#### Returns after decoding - -| Type | Description | -| ------------------------------ | ---------------------------------------------- | -| [[EventObject]](#event-object) | An array of events that matched the eventName. | - -#### Usage - -```javascript -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 - -| Name | Type | Description | -| -------------- | ------ | ------------------------- | -| `collectionID` | string | The id of the collection. | - -#### Returns after decoding - -| Type | Description | -| ------------------------------------- | --------------------------------------------------------------------------------- | -| [CollectionObject](#collectionobject) | An object with the id and a list of transactions within the requested collection. | - -#### Usage - -```javascript -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 in the form of a [TransactionStatusObject](#transactionstatusobject). - -⚠️The transactionID provided must be from the current spork. - -📣 Considering [subscribing to the transaction from `fcl.tx(id)`](#tx) instead of calling this method directly. - -#### Arguments - -| Name | Type | Description | -| --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------- | -| `transactionId` | string | The transactionID returned when submitting a transaction. Example: `9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3` | - -#### Returns after decoding - -#### Returns - -| Type | Description | -| --------------------------------------------------- | ------------------------------------------------------ | -| [TransactionStatusObject](#transactionstatusobject) | Object representing the result/status of a transaction | - -#### Usage - -```javascript -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](#transactionobject) once decoded. - -⚠️The transactionID provided must be from the current spork. - -📣 Considering using [`fcl.tx(id).onceExecuted()`](#tx) instead of calling this method directly. - -#### Arguments - -| Name | Type | Description | -| --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------- | -| `transactionId` | string | The transactionID returned when submitting a transaction. Example: `9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3` | - -#### Returns after decoding - -#### Returns - -| Type | Description | -| --------------------------------------- | -------------------------------------------------------------- | -| [TransactionObject](#transactionobject) | An full transaction object containing a payload and signatures | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const tx = await fcl - .send([ - fcl.getTransaction( - '9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3', - ), - ]) - .then(fcl.decode); -``` - ---- - -### `subscribeEvents` - - -The subscribeEvents SDK builder is for more advanced use cases where you wish to directly specify a starting block to listen for events. For most use cases, consider using the pre-built interaction [`fcl.events(eventTypes)`](#events). - - -A build that returns a [event stream connection](#eventstream) once decoded. It will establish a WebSocket connection to the Access Node and subscribe to events with the given parameters. - -#### Arguments - -| Name | Type | Description | -| ------------- | --------------------------- | --------------------------------- | -| `eventFilter` | [EventFilter](#eventfilter) | The event filter to subscribe to. | - -#### Returns after decoding - -#### Returns - -| Type | Description | -| ------------------------------------- | -------------------------------- | -| [EventStreamConnection](#eventstream) | A connection to the event stream | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const eventStream = await fcl - .send([ - fcl.subscribeEvents({ - eventTypes: 'A.7e60df042a9c0868.FlowToken.TokensWithdrawn', - }), - ]) - .then(fcl.decode); - -eventStream.on('heartbeat', (heartbeat) => { - console.log(heartbeat); -}); - -eventStream.on('events', (event) => { - console.log(event); -}); - -eventStream.on('error', (error) => { - console.log(error); -}); - -eventStream.on('end', () => { - console.log('Connection closed'); -}); - -eventStream.close(); -``` - ---- - -### `getEvents` (Deprecated) - -Use [`fcl.getEventsAtBlockHeightRange`](#geteventsatblockheightrange) or [`fcl.getEventsAtBlockIds`](#geteventsatblockids). - ---- - -### `getLatestBlock` (Deprecated) - -Use [`fcl.getBlock`](#getblock). - ---- - -### `getBlockById` (Deprecated) - -Use [`fcl.getBlock`](#getblock) and [`fcl.atBlockId`](#atblockid). - ---- - -### `getBlockByHeight` (Deprecated) - -Use [`fcl.getBlock`](#getblock) and [`fcl.atBlockHeight`](#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 - -| Name | Type | Description | -| ------- | --------------- | --------------------------------------------------------- | -| `value` | any | Any value that you are looking to pass to other builders. | -| `type` | [FType](#ftype) | A type supported by Flow. | - -#### Returns - -| Type | Description | -| --------------------------------- | ----------------------------------- | -| [ArgumentObject](#argumentobject) | Holds the value and type passed in. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -await fcl - .send([ - fcl.script` - access(all) 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 - -| Name | Type | Description | -| ------ | ------------------------------------- | --------------------------------------------------------------------- | -| `args` | [[Argument Objects]](#argumentobject) | An array of arguments that you are looking to pass to other builders. | - -#### Returns - -| Type | Description | -| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| [Partial Interaction](#interaction) | An interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -await fcl - .send([ - fcl.script` - access(all) 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}`](#query) or [`fcl.mutate({...options})`](#mutate) and is reccomended to use over the functions below. - -### `script` - -A template builder to use a Cadence script for an interaction. - -📣 Use with `fcl.args(...)` to pass in arguments dynamically. - -#### Arguments - -| Name | Type | Description | -| ------ | ------ | ------------------------------- | -| `CODE` | string | Should be valid Cadence script. | - -#### Returns - -| Type | Description | -| --------------------------- | --------------------------------------------- | -| [Interaction](#interaction) | An interaction containing the code passed in. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const code = ` - access(all) 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 - -| Name | Type | Description | -| ------ | ------ | -------------------------------------- | -| `CODE` | string | Should be valid a Cadence transaction. | - -#### Returns - -| Type | Description | -| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| [Partial Interaction](#interaction) | An partial interaction containing the code passed in. Further builders are required to complete the interaction - see warning. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const code = ` - access(all) 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 - -| Name | Type | Description | -| --------- | ------------------- | ---------------------------------------------------------------------------------- | -| `address` | [Address](#address) | Address of the user account with or without a prefix (both formats are supported). | - -#### Returns - -| Type | Description | -| ------------------------------- | ---------------------------------------- | -| [AccountObject](#accountobject) | A JSON representation of a user account. | - -#### Usage - -```javascript -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 - -| Name | Type | Default | Description | -| -------- | ------- | ------- | ------------------------------------------------------------------------------ | -| `sealed` | boolean | false | If the latest block should be sealed or not. See [block states](#interaction). | -| `id` | string | | ID of block to get. | -| `height` | int | | Height of block to get. | - -#### Returns - -| Type | Description | -| --------------------------- | --------------------------------- | -| [BlockObject](#blockobject) | A JSON representation of a block. | - -#### Usage - -```javascript -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 - -| Name | Type | Default | Description | -| ---------- | ------- | ------- | ------------------------------------------------------------------------------ | -| `isSealed` | boolean | false | If the latest block should be sealed or not. See [block states](#interaction). | - -#### Returns - -| Type | Description | -| --------------------------- | --------------------------------- | -| [BlockObject](#blockobject) | A JSON representation of a block. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -const latestBlock = await fcl.latestBlock(); -``` - ---- - -## Real-Time Data - -Streaming data is available through the WebSocket Streaming API provided by the HTTP Access API. It allows developers to subscribe to specific topics and receive real-time updates as they occur on the Flow blockchain. - -The following topics can be subscribed to: - -- `events`: Subscribe to events emitted by contracts. -- `blocks`: Subscribe to new blocks added to the chain. -- `block_headers`: Subscribe to new block headers added to the chain. -- `block_digests`: Subscribe to block digests added to the chain. -- `transaction_statuses`: Subscribe to transaction statuses. -- `account_statuses`: Subscribe to account statuses. - -### `tx` - -A utility function that lets you set the transaction to get subsequent status updates and the finalized result once available. - -#### Arguments - -| Name | Type | Description | -| --------------- | ------ | ----------------------- | -| `transactionId` | string | A valid transaction id. | - -#### Returns - -| 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](#transaction-statuses). | -| `onceExecuted()` | function | Provides the transaction once status `3` is returned. See [Tranasaction Statuses](#transaction-statuses). | -| `onceSealed()` | function | Provides the transaction once status `4` is returned. See [Tranasaction Statuses](#transaction-statuses). | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; - -const [txStatus, setTxStatus] = useState(null); -useEffect(() => fcl.tx(txId).subscribe(setTxStatus)); -``` - ---- - -### `events` - -A utility function that lets you set the transaction to get subsequent status updates and the finalized result once available. - -#### Arguments - -| Name | Type | Description | -| ------------------- | ----------------------------------------- | ------------------------------------------------ | -| `eventNameOrFilter` | string | [EventFilter](#eventfilter) | The name of the event or an event filter object. | - -#### Returns - -| Name | Type | Description | -| --------------- | -------- | -------------------------------------------- | -| `subscribe(cb)` | function | Calls the `cb` passed in with the new event. | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -// in some react component -fcl.events(eventName).subscribe((event) => { - console.log(event); -}); -``` - ---- - -### `subscribe` - -A utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the [`decode`](#decode) function. - -#### Arguments - -| Name | Type | Description | -| -------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `params` | [`SubscriptionParams`](#subscriptionparams) | An object containing the subscription topic, arguments, and callbacks. See below for more details. | -| `opts` | object | _(Optional)_ Additional options for the subscription. See below for more details. | - -`params` (first parameter): - -See [`SubscriptionParams`](#subscriptionparams) for more details. - -Additional Options (second parameter): - -| Name | Type | Description | -| ----------- | ------ | ------------------------------------------------------------------------- | -| `node` | string | _(Optional)_ Custom node endpoint to be used for the subscription. | -| `transport` | object | _(Optional)_ Custom transport implementation for handling the connection. | - -#### Returns - -| Type | Description | -| ------------------------- | ---------------------------------------------------------------------------------------------- | -| SdkTransport.Subscription | A subscription object that allows you to manage the subscription (e.g., to unsubscribe later). | - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -import { SubscriptionTopic } from '@onflow/sdk'; - -const subscription = fcl.subscribe({ - topic: SubscriptionTopic.EVENTS, - args: { - type: 'A.7e60df042a9c0868.FlowToken.TokensWithdrawn', - }, - onData: (data) => console.log('Received event data:', data), - onError: (error) => console.error('Subscription error:', error), -}); - -// Later, to unsubscribe: -subscription.unsubscribe(); -``` - ---- - -### `subscribeRaw` - -A utility function used for subscribing to raw data from the WebSocket Streaming API. Data returned will not be decoded via `fcl.decode` and developers are responsible for handling the raw data returned. - -#### Arguments - -| Name | Type | Description | -| --------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | -| `topic` | `SubscriptionTopic` | The subscription topic. Valid values include: `events`, `blocks`, `transactions`, and `collections`. | -| `args` | `RawSubscriptionArgs` | An array or object of parameters specific to the topic. For example, when subscribing to events, these might be event identifiers. | -| `onData` | `(data: RawSubscriptionData) => void` | A callback function that is called with the decoded data whenever a new message is received. | -| `onError` | (error: Error) => void | A callback function that is called if an error occurs during the subscription. | - -Additional Options (second parameter): - -| Name | Type | Description | -| ----------- | ------ | ------------------------------------------------------------------------- | -| `node` | string | _(Optional)_ Custom node endpoint to be used for the subscription. | -| `transport` | object | _(Optional)_ Custom transport implementation for handling the connection. | - -#### Returns - -#### Usage - -```javascript -import * as fcl from '@onflow/fcl'; -import { SubscriptionTopic } from '@onflow/sdk'; - -const subscription = fcl.subscribeRaw({ - topic: SubscriptionTopic.EVENTS, - args: { - type: 'A.7e60df042a9c0868.FlowToken.TokensWithdrawn', - }, - onData: (data) => console.log('Received event data:', data), - onError: (error) => console.error('Subscription error:', error), -}); - -// Later, to unsubscribe: -subscription.unsubscribe(); -``` - ---- - -#### Examples - -- [Flow-view-source example](https://github.com/orodio/flow-view-source/blob/master/src/pages/event.comp.js) - ---- - -## Types, Interfaces, and Definitions - ---- - -### `Builders` - -Builders are modular functions that can be coupled together with `fcl.send([...builders])` to create an [Interaction](#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](https://github.com/onflow/fcl-js/blob/master/packages/sdk/src/interaction/interaction.ts). 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` - -| Key | Value Type | Default | Description | -| ----------- | ------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addr` | [Address](#address) | `null` | The public address of the current user | -| `cid` | string | `null` | Allows wallets to specify a [content identifier](https://docs.ipfs.io/concepts/content-addressing/) 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](https://gist.github.com/orodio/a74293f65e83145ec8b968294808cf35#you-know-who-the-user-is), or other kinds of interactions. | - ---- - -### `AuthorizationObject` - -This type conforms to the interface required for FCL to authorize transaction on behalf o the current user. - -| Key | Value Type | Description | -| ----------------- | ------------------- | ------------------------------------------------------------------------------------------------- | -| `addr` | [Address](#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. | - ---- - -### `SignableObject` - -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](#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](#signing-function) that can produce a valid signature for a user from a message. | - ---- - -### `AccountObject` - -The JSON representation of an account on the Flow blockchain. - -| Key | Value Type | Description | -| ----------- | ----------------------------- | ------------------------------------------------------------------------------------------ | -| `address` | [Address](#address) | The address of the account | -| `balance` | number | The FLOW balance of the account in 10^8. | -| `code` | [Code](#code) | The code of any Cadence contracts stored in the account. | -| `contracts` | Object: [Contract](#contract) | An object with keys as the contract name deployed and the value as the the cadence string. | -| `keys` | [[KeyObject]](#keyobject) | Any contracts deployed to this account. | - ---- - -### `Address` - -| Value Type | Description | -| ----------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| 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)` - -| Key | Value Type | Description | -| ------- | --------------- | ------------------------------------------------- | -| `value` | any | Any value to be used as an argument to a builder. | -| `xform` | [FType](#ftype) | Any 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` - -| Parameter Name | Value Type | Description | -| -------------- | ---------------- | ------------------------------------------------------------------------- | -| `arg` | function | A function that returns an [ArgumentObject](#argumentobject) - `fcl.arg`. | -| `t` | [FTypes](#ftype) | An object with acccess to all of the supported types on Flow. | - -**Returns** - -| Value Type | Description | -| ------------ | -------------------- | -| `[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 Name | Value Type | Description | -| -------------- | ------------------------------- | ---------------------------------------------- | -| `account` | [AccountObject](#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. | - -#### Usage - ---- - -```javascript -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, - } -``` - -- [Detailed explanation](https://github.com/onflow/fcl-js/blob/master/packages/fcl-core/src/wallet-provider-spec/authorization-function.md) - ---- - -### `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 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. | - -#### Usage - -```javascript -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: - -- [Detailed explanation](https://github.com/onflow/fcl-js/blob/master/packages/fcl-core/src/wallet-provider-spec/authorization-function.md) - ---- - -### `TransactionObject` - -| 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\]](#address) | A list of the accounts that are authorizing this transaction to mutate to their on-chain account state. [See more here](../../../build/basics/transactions.md#signer-roles). | -| `envelopeSignatures` | [\[SignableObject\]](#signableobject) | A list of signatures generated by the payer role. [See more here](../../../build/basics/transactions.md#signing-a-transaction). | -| `gasLimit` | number | The maximum number of computational units that can be used to execute this transaction. [See more here](../../../build/basics/fees.md). | -| `payer` | [Address](#address) | The account that pays the fee for this transaction. [See more here](../../../build/basics/transactions.md#signer-roles). | -| `payloadSignatures` | [\[SignableObject\]](#signableobject) | A list of signatures generated by the proposer and authorizer roles. [See more here](../../../build/basics/transactions.md#signing-a-transaction). | -| `proposalKey` | [\[ProposalKey\]](#proposalkeyobject) | 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 | - -### `TransactionRolesObject` - -| 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](../../../build/basics/transactions.md#signer-roles). - -### `TransactionStatusObject` - -| Key | Value Type | Description | -| -------------- | ------------------------------------------ | ----------------------------------------------------------------------------------- | -| `blockId` | string | ID of the block that contains the transaction. | -| `events` | [[EventObject]](#event-object) | An array of events that were emitted during the transaction. | -| `status` | [TransactionStatus](#transaction-statuses) | The status of the transaction on the blockchain. | -| `statusString` | [TransactionStatus](#transaction-statuses) | The `status` as as descriptive text (e.g. "FINALIZED"). | -| `errorMessage` | string | An error message if it exists. Default is an empty string `''`. | -| `statusCode` | number | The pass/fail status. 0 indicates the transaction succeeded, 1 indicates it failed. | - -### `EventName` - -| Value Type | Description | -| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| string(formatted) | A event name in Flow must follow the format `A.{AccountAddress}.{ContractName}.{EventName}`
eg. `A.ba1132bc08f82fe2.Debug.Log` | - -### `Contract` - -| Value Type | Description | -| ----------------- | ---------------------------------------------------- | -| string(formatted) | A formatted string that is a valid cadence contract. | - -### `KeyObject` - -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. | - -### `ProposalKeyObject` - -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](../../../build/basics/transactions.md#sequence-numbers) - -| Key | Value Type | Description | -| ---------------- | ------------------- | ------------------------------------------------------------------------- | -| `address` | [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 | - -### `BlockObject` - -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](#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. | - -### `BlockHeaderObject` - -The subset of the [BlockObject](#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. | - -### `BlockDigestObject` - -A lightweight subset of the [BlockObject](#blockobject) containing only the id, height, and timestamp of a block. - -| Key | Value Type | Description | -| ----------- | ---------- | --------------------------- | -| `id` | string | The id of the block. | -| `height` | number | The height of the block. | -| `timestamp` | string | The timestamp of the block. | - -### `CollectionGuaranteeObject` - -A collection that has been included in a block. - -| Key | Value Type | Description | -| -------------- | ----------------------------------- | -------------------- | -| `collectionId` | string | The id of the block. | -| `signatures` | [SignatureObject](#SignatureObject) | All signatures. | - -### `CollectionObject` - -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. | - -### `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](https://github.com/onflow/fcl-js/tree/master/packages/sdk/src/response). - -| Key | -| ------------------- | -| `tag` | -| `transaction` | -| `transactionStatus` | -| `transactionId` | -| `encodedData` | -| `events` | -| `account` | -| `block` | -| `blockHeader` | -| `latestBlock` | -| `collection` | - -### `Event Object` - -| 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](#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. | - -### `Account Status Event Object` - -| 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](#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. | -| `accountAddress` | [Address](#address) | The address of the account where the status change occurred. | - -### `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 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 | - -### `GRPC Statuses` - -The access node GRPC implementation follows the standard GRPC Core status code spec. View [here](https://grpc.github.io/grpc/core/md_doc_statuscodes.html). - -### `FType` - -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)` | - ---- - -### `EventFilter` - -An object that contains the parameters to filter events, used for event streaming in the [`fcl.events`](#events) function. - -| Name | Value Type | Description | -| ------------------------ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -| `startBlockId` | string | undefined | The block ID to start listening for events. Example: `9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3` | -| `startHeight` | number | undefined | The block height to start listening for events. Example: `123` | -| `eventTypes` | string[] | undefined | The event types to listen for. Example: `A.7e60df042a9c0868.FlowToken.TokensWithdrawn` | -| `addresses` | string[] | undefined | The addresses to listen for. Example: `0x7e60df042a9c0868` | -| `contracts` | string[] | undefined | The contracts to listen for. Example: `0x7e60df042a9c0868` | -| `opts.heartbeatInterval` | number | undefined | The interval in milliseconds to send a heartbeat to the Access Node. Example: `10000` | - -### `StreamConnection` - -A stream connection is an object for subscribing to generic data from any WebSocket data stream. This is the base type for all stream connections. Two channels, `close` and `error`, are always available, as they are used to signal the end of the stream and any errors that occur. - -```ts -interface StreamConnection { - // Subscribe to a channel - on( - channel: C, - listener: (data: ChannelMap[C]) => void, - ): this; - on(event: 'close', listener: () => void): this; - on(event: 'error', listener: (err: any) => void): this; - - // Unsubscribe from a channel - off( - event: C, - listener: (data: ChannelMap[C]) => void, - ): this; - off(event: 'close', listener: () => void): this; - off(event: 'error', listener: (err: any) => void): this; - - // Close the connection - close(): void; -} -``` - -#### Usage - -```ts -import { StreamConnection } from "@onflow/typedefs" - -const stream: StreamConnection = ... - -stream.on("close", () => { - // Handle close -}) - -stream.on("error", (err) => { - // Handle error -}) - -stream.close() -``` - -### `EventStream` - -An event stream is a stream connection that emits events and block heartbeats. Based on the connection parameters, heartbeats will be emitted at least as often as some fixed block height interval. It is a specific variant of a [StreamConnection](#streamconnection). - -```ts -type EventStream = StreamConnection<{ - events: Event[]; - heartbeat: BlockHeartbeat; -}>; -``` - -#### Usage - -```ts -import { EventStream } from "@onflow/typedefs" - -const stream: EventStream = ... - -stream.on("events", (events) => { - // Handle events -}) - -stream.on("heartbeat", (heartbeat) => { - // Handle heartbeat -}) - -// Close the stream -stream.close() -``` - -### `BlockHeartbeat` - -```ts -export interface BlockHeartbeat { - blockId: string; - blockHeight: number; - timestamp: string; -} -``` - -#### Usage - -```ts -import { BlockHeartbeat } from "@onflow/typedefs" - -const heartbeat: BlockHeartbeat = ... -``` - -### `SignatureObject` - -Signature objects are used to represent a signature for a particular message as well as the account and keyId which signed for this message. - -| Key | Value Type | Description | -| ----------- | ------------------- | -------------------------------------------------------------------------------------------- | -| `addr` | [Address](#address) | the address of the account which this signature has been generated for | -| `keyId` | number | The index of the key to use during authorization. (Multiple keys on an account is possible). | -| `signature` | string | a hexidecimal-encoded string representation of the generated signature | - -### `SubscriptionParams` - -```ts -import { SubscriptionParams } from '@onflow/typedefs'; -``` - -An object containing the subscription topic, arguments, and callbacks. The `SubscriptionParams` type is a generic type that takes a `SubscriptionTopic` as a parameter. - -```ts -interface SubscriptionParams { - topic: T; - args: SubscriptionArgs; - onData: (data: SubscriptionData) => void; - onError: (error: Error) => void; -} -``` - -| Key | Value Type | Description | -| --------- | ----------------------------------------- | ------------------------------------------------------------------------------------- | -| `topic` | [`SubscriptionTopic`](#subscriptiontopic) | The topic to subscribe to. This determines the type of data that will be received. | -| `args` | [`SubscriptionArgs`](#subscriptionargs) | The arguments specific to the topic. This may include filters or other parameters. | -| `onData` | function | A callback function that will be called with the data received from the subscription. | -| `onError` | function | A callback function that will be called if an error occurs during the subscription. | - -### `SubscriptionTopic` - -Import: - -```ts -import { SubscriptionTopic } from '@onflow/typedefs'; -``` - -The `SubscriptionTopic` is an enum that defines the different topics that can be subscribed to. Each topic corresponds to a specific type of data that can be received from the subscription. - -The available topics are: - -```ts -enum SubscriptionTopic { - BLOCKS = 'blocks', - BLOCK_HEADERS = 'block_headers', - BLOCK_DIGESTS = 'block_digests', - ACCOUNT_STATUSES = 'account_statuses', - TRANSACTION_STATUSES = 'transaction_statuses', - EVENTS = 'events', -} -``` - -### `SubscriptionArgs` - -```ts -import { type SubscriptionArgs } from '@onflow/typedefs'; -``` - -Type definition: - -```ts -type SubscriptionArgs = { - [K in T]: K extends 'blocks' | 'block_headers' | 'block_digests' - ? - | BlockSubscriptionAtLatestArgs - | BlockSubscriptionAtIdArgs - | BlockSubscriptionAtHeightArgs - : K extends 'account_statuses' - ? AccountStatusSubscriptionArgs - : K extends 'transaction_statuses' - ? TransactionStatusSubscriptionArgs - : K extends 'events' - ? EventSubscriptionArgs - : never; -}[T]; -``` - -An array or object of parameters specific to the topic. For example, when subscribing to events, these might be event identifiers. - -Usage: - -```ts -const args: SubscriptionArgs = { - eventTypes: ['A.7e60df042a9c0868.FlowToken.TokensWithdrawn'], - addresses: ['0x7e60df042a9c0868'], -}; -``` - -#### Blocks, Block Headers, Block Digests - -_Applies to topics: `SubscriptionTopic.BLOCKS`, `SubscriptionTopic.BLOCK_HEADERS`, `SubscriptionTopic.BLOCK_DIGESTS`_ - -Start at the latest block: - -```ts -// Internal type, not exported -type BlockSubscriptionAtLatestArgs = { - blockStatus: 'finalized' | 'sealed'; -}; -``` - -Start at a specific block ID: - -```ts -// Internal type, not exported -type BlockSubscriptionAtIdArgs = { - blockStatus: 'finalized' | 'sealed'; - startBlockId: string; -}; -``` - -Start at a specific block height: - -```ts -// Internal type, not exported -type BlockSubscriptionAtHeightArgs = { - blockStatus: 'finalized' | 'sealed'; - startBlockHeight: number; -}; -``` - -#### Account Statuses - -_Applies to topic: `SubscriptionTopic.ACCOUNT_STATUSES`_ - -```ts -// Internal type, not exported -type AccountStatusSubscriptionArgs = { - startBlockId?: string; - startBlockHeight?: number; - eventTypes?: string[]; - addresses?: string[]; - accountAddresses?: string[]; -}; -``` - -#### Transaction Statuses - -_Applies to topic: `SubscriptionTopic.TRANSACTION_STATUSES`_ - -```ts -// Internal type, not exported -type TransactionStatusSubscriptionArgs = { - transactionId: string; -}; -``` - -#### Events - -_Applies to topic: `SubscriptionTopic.EVENTS`_ - -Type definition: - -```ts -// Internal type, not exported -type EventSubscriptionArgs = { - startBlockId?: string; - startBlockHeight?: number; - eventTypes?: string[]; - addresses?: string[]; - contracts?: string[]; -}; -``` - -### `SubscriptionData` - -**Import:** - -```ts -import { type SubscriptionData } from '@onflow/typedefs'; -``` - -The data returned by the subscription. This will vary depending on the topic. - -This is a generic type that takes a `SubscriptionTopic` as a parameter. - -```ts -type SubscriptionData = { - [K in T]: K extends 'blocks' - ? Block - : K extends 'block_headers' - ? BlockHeader - : K extends 'block_digests' - ? BlockDigest - : K extends 'account_statuses' - ? AccountStatus - : K extends 'transaction_statuses' - ? TransactionStatus - : K extends 'events' - ? Event - : never; -}[T]; -``` - -#### Blocks - -_Applies to topic: `SubscriptionTopic.BLOCKS`_ - -See [BlockObject](#blockobject). - -#### Block Headers - -_Applies to topic: `SubscriptionTopic.BLOCK_HEADERS`_ - -See [BlockHeaderObject](#blockheaderobject). - -#### Block Digests - -_Applies to topic: `SubscriptionTopic.BLOCK_DIGESTS`_ - -See BlockDigestObject. - -#### Account Statuses - -_Applies to topic: `SubscriptionTopic.ACCOUNT_STATUSES`_ - -See AccountStatusObject. - -#### Transaction Statuses - -_Applies to topic: `SubscriptionTopic.TRANSACTION_STATUSES`_ - -See [TransactionStatusObject](#transactionstatusobject). - -#### Events - -_Applies to topic: `SubscriptionTopic.EVENTS`_ - -See [EventObject](#event-object). - -### `RawSubscriptionData` - -```ts -import { type RawSubscriptionData } from '@onflow/typedefs'; -``` - -A raw data returned by the subscription. This will vary depending on the topic. - -This is a generic type that takes a `SubscriptionTopic` as a parameter. - -```ts -type RawSubscriptionData = { - [K in T]: K extends 'blocks' - ? RawBlock - : K extends 'block_headers' - ? RawBlockHeader - : K extends 'block_digests' - ? RawBlockDigest - : K extends 'account_statuses' - ? RawAccountStatus - : K extends 'transaction_statuses' - ? RawTransactionStatus - : K extends 'events' - ? RawEvent - : never; -}[T]; -``` - -#### Blocks - -_Applies to topic: `SubscriptionTopic.BLOCKS`_ - -Type definition: - -```ts -// Internal type, not exported -type RawBlock = { - block: { - id: string; - parentId: string; - height: number; - timestamp: string; - collectionGuarantees: { - collectionId: string; - signatures: { - addr: string; - keyId: number; - signature: string; - }[]; - }[]; - blockSeals: { - addr: string; - keyId: number; - signature: string; - }[]; - signatures: { - addr: string; - keyId: number; - signature: string; - }[]; - }; -}; -``` - -#### Block Headers - -_Applies to topic: `SubscriptionTopic.BLOCK_HEADERS`_ - -Type definition: - -```ts -// Internal type, not exported -type RawBlockHeader = { - blockHeader: { - id: string; - parentId: string; - height: number; - timestamp: string; - parentVoterSignature: string; - }; -}; -``` - -#### Block Digests - -_Applies to topic: `SubscriptionTopic.BLOCK_DIGESTS`_ - -Type definition: - -```ts -// Internal type, not exported -type RawBlockDigest = { - blockDigest: { - id: string; - parentId: string; - height: number; - timestamp: string; - }; -}; -``` - -#### Account Statuses - -_Applies to topic: `SubscriptionTopic.ACCOUNT_STATUSES`_ - -Type definition: - -```ts -// Internal type, not exported -type RawAccountStatus = { - accountStatus: { - accountAddress: string; - blockId: string; - blockHeight: number; - type: string; - transactionId: string; - transactionIndex: number; - eventIndex: number; - payload: { - type: string; - value: any; - }; - }; -}; -``` - -#### Transaction Statuses - -_Applies to topic: `SubscriptionTopic.TRANSACTION_STATUSES`_ - -Type definition: - -```ts -// Internal type, not exported -type RawTransactionStatus = { - transactionStatus: { - blockId: string; - status: TransactionExecutionStatus; - statusString: string; - statusCode: 0 | 1; - errorMessage: string; - events: { - type: string; - transactionId: string; - transactionIndex: number; - eventIndex: number; - payload: { - type: string; - value: any; - }; - }[]; - }; -}; -``` - -#### Events - -_Applies to topic: `SubscriptionTopic.EVENTS`_ - -Type definition: - -```ts -// Internal type, not exported -type RawEvent = { - event: { - blockId: string; - blockHeight: number; - blockTimestamp: string; - type: string; - transactionId: string; - transactionIndex: number; - eventIndex: number; - payload: { - type: string; - value: any; - }; - }; -}; -``` diff --git a/docs/tools/clients/fcl-js/discovery.md b/docs/tools/clients/fcl-js/discovery.md index 59e993b268..d8bcce8ee4 100644 --- a/docs/tools/clients/fcl-js/discovery.md +++ b/docs/tools/clients/fcl-js/discovery.md @@ -19,7 +19,7 @@ When authenticating via FCL using Discovery UI, a user is shown a list of servic This method is the simplest way to integrate Discovery and its wallets and services into your app. All you have to do is configure `discovery.wallet` with the host endpoint for testnet or mainnet. -> **Note**: Opt-in wallets, like Ledger and Dapper Wallet, require you to explicitly state you'd like to use them. For more information on including opt-in wallets, [see these docs](./api.md#more-configuration). +> **Note**: Opt-in wallets, like Ledger and Dapper Wallet, require you to explicitly state you'd like to use them. For more information on including opt-in wallets, [see these docs](./packages-docs/fcl/index.md#configuration). > > A [Dapper Wallet](https://meetdapper.com/developers) developer account is required. To enable Dapper Wallet inside FCL, you need to [follow this guide](https://docs.meetdapper.com/quickstart). @@ -81,7 +81,7 @@ fcl.discovery.authn.subscribe(callback); fcl.discovery.authn.snapshot(); ``` -In order to authenticate with a service (for example, when a user click's "login"), pass the selected service to the `fcl.authenticate` method described here [in the API reference](./api.md#authenticate): +In order to authenticate with a service (for example, when a user click's "login"), pass the selected service to the `fcl.authenticate` method described here [in the API reference](./packages-docs/fcl/authenticate.md): ```jsx fcl.authenticate({ service }); @@ -183,10 +183,7 @@ fcl.config({ | `Dapper Wallet` | 0x82ec283f88a62e65 | 0xead892083b3e2c6c | | `Ledger` | 0x9d2e44203cb13051 | 0xe5cd26afebe62781 | -To learn more about other possible configurations, check out the following links: - -- [Discovery API Docs](./api.md#discovery-1) -- [Discovery Github Repo](https://github.com/onflow/fcl-discovery) +To learn more about other possible configurations, check out the [Discovery Github Repo](https://github.com/onflow/fcl-discovery). ### Exclude Wallets diff --git a/docs/tools/clients/fcl-js/index.md b/docs/tools/clients/fcl-js/index.md index ec41964064..0331463475 100644 --- a/docs/tools/clients/fcl-js/index.md +++ b/docs/tools/clients/fcl-js/index.md @@ -69,8 +69,6 @@ fcl.authenticate() - *Interact with smart contracts*: Authorize transactions via the user's chosen wallet - *Prove ownership of a wallet address*: Signing and verifying user signed data -[Learn more about wallet interactions >](api.md#wallet-interactions) - #### Blockchain Interactions - *Query the chain*: Send arbitrary Cadence scripts to the chain and receive back decoded values ```js @@ -109,8 +107,6 @@ const txId = await fcl.mutate({ }); ``` -[Learn more about on-chain interactions >](api.md#on-chain-interactions) - #### Utilities - Get account details from any Flow address - Get the latest block @@ -118,8 +114,6 @@ const txId = await fcl.mutate({ - Event polling - Custom authorization functions -[Learn more about utilities >](api.md#pre-built-interactions) - ## Typescript Support FCL JS supports TypeScript. If you need to import specific types, you can do so via the [@onflow/typedefs](https://github.com/onflow/fcl-js/tree/master/packages/typedefs) package. @@ -143,7 +137,7 @@ For all type definitions available, see [this file](https://github.com/onflow/fc ## Next Steps - See the [Flow App Quick Start](../../../build/getting-started/fcl-quickstart.md). -- See the full [API Reference](api.md) for all FCL functionality. +- See the full [API Reference](./packages-docs/fcl/index.md) for all FCL functionality. - Learn Flow's smart contract language to build any script or transactions: [Cadence](https://cadence-lang.org). - Explore all of Flow [docs and tools](https://developers.flow.com). @@ -183,7 +177,7 @@ The discovery feature can be used via API allowing you to customize your own UI ## 🛠 Want to Use the Flow SDK Directly? -If you prefer to interact with Flow at a **lower level** without using FCL, you can use the [Flow JavaScript SDK](sdk-guidelines.md) directly. The SDK provides raw access to Flow's API for sending transactions, executing scripts, and managing accounts. +If you prefer to interact with Flow at a **lower level** without using FCL, you can use the [Flow JavaScript SDK](./packages-docs/sdk/index.md) directly. The SDK provides raw access to Flow's API for sending transactions, executing scripts, and managing accounts. FCL is built **on top of the Flow SDK**, making it easier to handle authentication, wallet interactions, and dapp connectivity. Choose the approach that best fits your use case. diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/account.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/account.md new file mode 100644 index 0000000000..03d6fb2a4c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/account.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "account" +description: "account function documentation." +--- + + + +# 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.account(address, accountQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { account } from "@onflow/fcl-core" + +account(address, accountQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get account from latest block height +const account = await fcl.account("0x1d007d755706c469"); +console.log("Address:", account.address); +console.log("Balance:", account.balance); +console.log("Keys:", account.keys); +console.log("Contracts:", Object.keys(account.contracts)); + +// Get account at a specific block height +const historicalAccount = await fcl.account("0x1d007d755706c469", { + height: 12345 +}); + +// Get account at a specific block ID +const accountAtBlock = await fcl.account("0x1d007d755706c469", { + id: "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3" +}); + +// Get account from sealed block +const sealedAccount = await fcl.account("0x1d007d755706c469", { + isSealed: true +}); + +// Alternative using builder pattern +fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(123) +]).then(fcl.decode); +``` + +## Parameters + +### `address` + + +- Type: `string` +- Description: Address of the account + +### `accountQueryOptions` (optional) + + +- Type: +```typescript +interface AccountQueryOptions { + height?: number + id?: string + isSealed?: boolean +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#account) + + +A promise that resolves to an Account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/appUtils.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/appUtils.md new file mode 100644 index 0000000000..1030af27c2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/appUtils.md @@ -0,0 +1,177 @@ +--- +sidebar_position: 1 +title: "AppUtils" +description: "Namespace containing AppUtils utilities" +--- + + + +# AppUtils + +## Overview + +Namespace containing AppUtils utilities + +## Functions + +### verifyAccountProof + +Verifies the authenticity of an account proof signature on the Flow blockchain. +Account proofs are cryptographic signatures used to prove ownership of a Flow account without +revealing private keys. This function validates that the provided signatures were indeed created +by the private keys associated with the specified Flow account address. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.AppUtils.verifyAccountProof(appIdentifier, accountProofData, opts) +``` + +Or import the namespace directly: + +```typescript +import { AppUtils } from "@onflow/fcl-core" + +AppUtils.verifyAccountProof(appIdentifier, accountProofData, opts) +``` + +#### Usage + +```typescript +import * as fcl from "@onflow/fcl" + +const accountProofData = { + address: "0x123", + nonce: "F0123" + signatures: [{f_type: "CompositeSignature", f_vsn: "1.0.0", addr: "0x123", keyId: 0, signature: "abc123"}], +} + +const isValid = await fcl.AppUtils.verifyAccountProof( + "AwesomeAppId", + accountProofData, + {fclCryptoContract} +) +``` + +#### Parameters + +##### `appIdentifier` + + +- Type: `string` +- Description: A unique identifier for your application. This is typically +your app's name or domain and is included in the signed message to prevent replay attacks +across different applications. + +##### `accountProofData` + + +- Type: +```typescript +export interface AccountProofData { + address: string + nonce: string + signatures: CompositeSignature[] +} +``` + +##### `opts` (optional) + + +- Type: +```typescript +export interface VerifySignaturesScriptOptions { + fclCryptoContract?: string +} +``` +- Description: Optional configuration parameters + +#### Returns + +`Promise` + +### verifyUserSignatures + +Verifies user signatures for arbitrary messages on the Flow blockchain. This function +validates that the provided signatures were created by the private keys associated with the specified +Flow account when signing the given message. This is useful for authenticating users or validating +signed data outside of transaction contexts. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.AppUtils.verifyUserSignatures(message, compSigs, opts) +``` + +Or import the namespace directly: + +```typescript +import { AppUtils } from "@onflow/fcl-core" + +AppUtils.verifyUserSignatures(message, compSigs, opts) +``` + +#### Usage + +```typescript +// Basic message signature verification +import * as fcl from "@onflow/fcl" + +const originalMessage = "Hello, Flow blockchain!" +const hexMessage = Buffer.from(originalMessage).toString("hex") + +const signatures = [{ + f_type: "CompositeSignature", + f_vsn: "1.0.0", + addr: "0x1234567890abcdef", + keyId: 0, + signature: "abc123def456..." // signature from user's wallet +}] + +const isValid = await fcl.AppUtils.verifyUserSignatures( + hexMessage, + signatures +) +``` + +#### Parameters + +##### `message` + + +- Type: `string` +- Description: The message that was signed, encoded as a hexadecimal string. The original +message should be converted to hex before passing to this function. + +##### `compSigs` + + +- Type: [`CompositeSignature[]`](../types#compositesignature) +- Description: Array of composite signatures to verify. All signatures +must be from the same account address. + +##### `opts` (optional) + + +- Type: +```typescript +export interface VerifySignaturesScriptOptions { + fclCryptoContract?: string +} +``` +- Description: Optional configuration parameters + +#### Returns + +`Promise` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/arg.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/arg.md new file mode 100644 index 0000000000..26d4a9f834 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/arg.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "arg" +description: "arg function documentation." +--- + + + +# arg + +A utility builder to be used with fcl.args[...] to create FCL supported arguments for interactions. + +Arguments are used to pass data to Cadence scripts and transactions. The arguments must match the number and order declared in the Cadence script. +This function creates an ArgumentObject that holds the value and type passed in. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.arg(value, xform) +``` + +Or import directly the specific function: + +```typescript +import { arg } from "@onflow/fcl-core" + +arg(value, xform) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +const result = await fcl.query({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `value` + + +- Type: +```typescript +TypeDescriptorInput +``` +- Description: Any value that you are looking to pass to other builders + +### `xform` + + +- Type: `T` +- Description: A type supported by Flow (FType descriptor) + + +## Returns + +```typescript +CadenceArgument +``` + + +An ArgumentObject that holds the value and type passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/args.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/args.md new file mode 100644 index 0000000000..fbec4c18c3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/args.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "args" +description: "args function documentation." +--- + + + +# args + +A utility builder to be used with other builders to pass in arguments with a value and supported type. + +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. +This function returns a Partial Interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.args(ax) +``` + +Or import directly the specific function: + +```typescript +import { args } from "@onflow/fcl-core" + +args(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +await fcl.mutate({ + cadence: ` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // transaction logic + } + } + `, + args: (arg, t) => [ + arg("10.0", t.UFix64), // Will be the first argument `amount: UFix64` + arg("0xba1132bc08f82fe2", t.Address), // Will be the second argument `to: Address` + ], +}) +``` + +## Parameters + +### `ax` + + +- Type: +```typescript +CadenceArgument[] +``` +- Description: An array of argument objects created with fcl.arg() + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A Partial Interaction object containing the arguments and types passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockHeight.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockHeight.md new file mode 100644 index 0000000000..f2baa0bed9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockHeight.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockHeight" +description: "atBlockHeight function documentation." +--- + + + +# 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. + +Block height expresses the height of the block on the chain. The latest block height increases by one for every valid block produced. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.atBlockHeight(height) +``` + +Or import directly the specific function: + +```typescript +import { atBlockHeight } from "@onflow/fcl-core" + +atBlockHeight(height) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block at specific height +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode); + +// Get account at specific block height +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Execute script at specific block height +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().height + } + `, + fcl.atBlockHeight(100) +]).then(fcl.decode); +``` + +## Parameters + +### `height` + + +- Type: `number` +- Description: The height of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockId.md new file mode 100644 index 0000000000..760753d014 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/atBlockId.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockId" +description: "atBlockId function documentation." +--- + + + +# 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. + +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'). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.atBlockId(id) +``` + +Or import directly the specific function: + +```typescript +import { atBlockId } from "@onflow/fcl-core" + +atBlockId(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block by ID +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get account at specific block ID +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockId("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); + +// Execute script at specific block +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().timestamp + } + `, + fcl.atBlockId("a1b2c3d4e5f6") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` +- Description: The ID of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorization.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorization.md new file mode 100644 index 0000000000..9768255081 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorization.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: "authorization" +description: "authorization function documentation." +--- + + + +# authorization + +Creates an authorization function for use in transactions. + +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. + +Read more about [authorization functions](https://docs.onflow.org/fcl/reference/authorization-function/) and [transaction roles](https://docs.onflow.org/concepts/transaction-signing/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.authorization(addr, signingFunction, keyId, sequenceNum) +``` + +Or import directly the specific function: + +```typescript +import { authorization } from "@onflow/fcl-core" + +authorization(addr, signingFunction, keyId, sequenceNum) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { ec as EC } from "elliptic"; + +// Create a signing function +const signingFunction = ({ message }) => { + // Your signing logic here + return { + addr: "0x123456789abcdef0", + keyId: 0, + signature: "your_signature_here" + }; +}; + +// Create authorization +const authz = fcl.authorization( + "0x123456789abcdef0", // account address + signingFunction, // signing function + 0, // key ID + 42 // sequence number +); + +// Use in transaction +await fcl.mutate({ + cadence: `transaction { prepare(acct: AuthAccount) {} }`, + proposer: authz, + payer: authz, + authorizations: [authz] +}); +``` + +## Parameters + +### `addr` + + +- Type: `string` +- Description: The address of the account that will sign the transaction + +### `signingFunction` + + +- Type: +```typescript +type SigningFn = ( + signable?: SignableMessage +) => SigningResult | Promise +``` +- Description: A function that produces signatures for the account + +### `keyId` (optional) + + +- Type: `string | number` +- Description: The index of the key to use for signing (optional) + +### `sequenceNum` (optional) + + +- Type: `number` +- Description: The sequence number for the account key (optional) + + +## Returns + +```typescript +Partial +``` + + +A partial interaction account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorizations.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorizations.md new file mode 100644 index 0000000000..c71f0a64f5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/authorizations.md @@ -0,0 +1,106 @@ +--- +sidebar_position: 1 +title: "authorizations" +description: "authorizations function documentation." +--- + + + +# authorizations + +A utility builder to set the authorizations on a transaction. + +Authorizations define the accounts that are responsible for paying the transaction fees and providing signatures for the transaction. +You can have multiple authorizers in a single transaction (multi-signature transactions). + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.authorizations(ax) +``` + +Or import directly the specific function: + +```typescript +import { authorizations } from "@onflow/fcl-core" + +authorizations(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Single authorizer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Hello from: ".concat(acct.address.toString())) + } + } + `, + authorizations: [fcl.authz] // Current user authorization +}); + +// Multiple authorizers - both accounts must approve +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct1: AuthAccount, acct2: AuthAccount) { + log("Transaction signed by both accounts") + } + } + `, + authorizations: [userOneAuthz, userTwoAuthz] +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + acct.save("Hello, World!", to: /storage/greeting) + } + } + `, + fcl.authorizations([fcl.authz]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.limit(100) +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An array of authorization functions that produce account authorization details + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/block.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/block.md new file mode 100644 index 0000000000..e52537d2d9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/block.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "block" +description: "block function documentation." +--- + + + +# block + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.block(blockQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { block } from "@onflow/fcl-core" + +block(blockQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest block +const latestBlock = await fcl.block(); // Get the latest finalized block +const latestSealedBlock = await fcl.block({sealed: true}); // Get the latest sealed block + +// Get block by ID (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get block at height (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode) +``` + +## Parameters + +### `blockQueryOptions` (optional) + + +- Type: +```typescript +interface BlockQueryOptions { + sealed?: boolean + height?: number + id?: string +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#block) + + +A promise that resolves to a Block object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/build.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/build.md new file mode 100644 index 0000000000..f6e8be4729 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/build.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "build" +description: "build function documentation." +--- + + + +# build + +A builder function that creates an interaction from an array of builder functions. + +The build function takes an array of builder functions and applies them to create a complete interaction object. This is the foundation for constructing all interactions in Flow, whether they're scripts, transactions, or queries. + +Each builder function modifies specific parts of the interaction object, such as adding Cadence code, arguments, authorization details, or other configuration. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.build(fns) +``` + +Or import directly the specific function: + +```typescript +import { build } from "@onflow/fcl-core" + +build(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Build a script interaction +const scriptInteraction = await fcl.build([ + fcl.script` + access(all) fun main(a: Int, b: Int): Int { + return a + b + } + `, + fcl.args([ + fcl.arg(1, fcl.t.Int), + fcl.arg(2, fcl.t.Int) + ]) +]); + +// Build a transaction interaction +const txInteraction = await fcl.build([ + fcl.transaction` + transaction(name: String) { + prepare(account: AuthAccount) { + log("Hello, " + name) + } + } + `, + fcl.args([fcl.arg("World", fcl.t.String)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `fns` (optional) + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: The functions to apply to the interaction + + +## Returns + +[`Promise`](../types#interaction) + + +A promise of an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/buildMessageHandler.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/buildMessageHandler.md new file mode 100644 index 0000000000..8b89ee505b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/buildMessageHandler.md @@ -0,0 +1,88 @@ +--- +sidebar_position: 1 +title: "buildMessageHandler" +description: "buildMessageHandler function documentation." +--- + + + +# buildMessageHandler + +Creates a message handler for processing window messages from wallet service +frames or popups. This handler manages the communication protocol between FCL and wallet +services, including ready states, responses, and cleanup operations. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.buildMessageHandler(buildMessageHandlerParams) +``` + +Or import directly the specific function: + +```typescript +import { buildMessageHandler } from "@onflow/fcl-core" + +buildMessageHandler(buildMessageHandlerParams) +``` + +## Usage + +```typescript +// Create a message handler for wallet communication +const handler = buildMessageHandler({ + close: () => cleanup(), + send: (msg) => postMessage(msg), + onReady: (e, utils) => initializeWallet(utils), + onResponse: (e, utils) => handleResponse(e.data), + onMessage: (e, utils) => processMessage(e), + onCustomRpc: (payload, utils) => handleRpc(payload) +}) +window.addEventListener("message", handler) +``` + +## Parameters + +### `buildMessageHandlerParams` + + +- Type: +```typescript +export interface BuildMessageHandlerParams { + close: () => void + send: (msg: any) => void + onReady: ( + e: MessageEvent, + utils: {send: (msg: any) => void; close: () => void} + ) => void + onResponse: ( + e: MessageEvent, + utils: {send: (msg: any) => void; close: () => void} + ) => void + onMessage: ( + e: MessageEvent, + utils: {send: (msg: any) => void; close: () => void} + ) => void + onCustomRpc: ( + payload: any, + utils: {send: (msg: any) => void; close: () => void} + ) => void + getSource?: () => Window | null +} +``` + + +## Returns + +```typescript +(e: MessageEvent) => void +``` + + +Message event handler function that can be attached to window message listeners + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/cadence.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/cadence.md new file mode 100644 index 0000000000..ae4dfc5b3b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/cadence.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cadence" +description: "cadence function documentation." +--- + + + +# cadence + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.cadence(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cadence } from "@onflow/fcl-core" + +cadence(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/cdc.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/cdc.md new file mode 100644 index 0000000000..cf693db8a3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/cdc.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cdc" +description: "cdc function documentation." +--- + + + +# cdc + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.cdc(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cdc } from "@onflow/fcl-core" + +cdc(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/config.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/config.md new file mode 100644 index 0000000000..f85b2f4c58 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/config.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "config" +description: "config function documentation." +--- + + + +# config + +Sets the config + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.config(values) +``` + +Or import directly the specific function: + +```typescript +import { config } from "@onflow/fcl-core" + +config(values) +``` + + +## Parameters + +### `values` (optional) + + +- Type: +```typescript +Record +``` +- Description: - The values to set + + +## Returns + +```typescript +{ put: typeof put; get: typeof get; all: typeof all; first: typeof first; update: typeof update; delete: typeof _delete; where: typeof where; subscribe: typeof subscribe; overload: typeof overload; load: typeof load; } +``` + + +The config object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/createSignableVoucher.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/createSignableVoucher.md new file mode 100644 index 0000000000..1bf16c422f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/createSignableVoucher.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "createSignableVoucher" +description: "createSignableVoucher function documentation." +--- + + + +# createSignableVoucher + +Creates a signable voucher object from an interaction for signing purposes. + +A voucher is a standardized representation of a transaction that contains all the necessary +information for signing and submitting to the Flow network. This function transforms an +interaction object into a voucher format. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.createSignableVoucher(ix) +``` + +Or import directly the specific function: + +```typescript +import { createSignableVoucher } from "@onflow/fcl-core" + +createSignableVoucher(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { createSignableVoucher } from "@onflow/sdk" + +// Build a transaction interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); + +// Create a voucher for signing +const voucher = createSignableVoucher(interaction); +console.log(voucher.cadence); // The Cadence script +console.log(voucher.arguments); // The transaction arguments +console.log(voucher.proposalKey); // Proposer account details +console.log(voucher.authorizers); // List of authorizer addresses + +// The voucher can now be signed and submitted +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing transaction details + + +## Returns + +```typescript +{ cadence: string; refBlock: string; computeLimit: number; arguments: any[]; proposalKey: { address: string; keyId: string | number; sequenceNum: number; } | { address?: undefined; keyId?: undefined; sequenceNum?: undefined; }; payer: string; authorizers: string[]; payloadSigs: { address: string; keyId: string | number; sig: string; }[]; envelopeSigs: { address: string; keyId: string | number; sig: string; }[]; } +``` + + +A voucher object containing all transaction data and signatures + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/decode.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/decode.md new file mode 100644 index 0000000000..5b1ea7af55 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/decode.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "decode" +description: "decode function documentation." +--- + + + +# decode + +Decodes the response from 'fcl.send()' into the appropriate JSON representation of any values returned from Cadence code. + +The response from Flow contains encoded values that need to be decoded into JavaScript types. This function handles that conversion, including complex types like structs, arrays, and dictionaries. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.decode(response) +``` + +Or import directly the specific function: + +```typescript +import { decode } from "@onflow/fcl-core" + +decode(response) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple script to add 2 numbers +const response = await fcl.send([ + fcl.script` + access(all) 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); +console.log(decoded); // 3 +console.log(typeof decoded); // "number" + +// Complex return types +const complexResponse = await fcl.send([ + fcl.script` + access(all) fun main(): {String: Int} { + return {"foo": 1, "bar": 2} + } + ` +]); + +const complexDecoded = await fcl.decode(complexResponse); +console.log(complexDecoded); // {foo: 1, bar: 2} +``` + +## Parameters + +### `response` + + +- Type: `any` +- Description: Should be the response returned from 'fcl.send([...])' + + +## Returns + +`Promise` + + +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. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/discovery.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/discovery.md new file mode 100644 index 0000000000..31b8e81045 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/discovery.md @@ -0,0 +1,124 @@ +--- +sidebar_position: 1 +title: "discovery" +description: "Namespace containing discovery utilities" +--- + + + +# discovery + +## Overview + +Namespace containing discovery utilities + +## Functions + +### getDiscoveryService + +Creates and configures a discovery service object used for wallet authentication. +This function combines the provided service configuration with discovery-related settings from +the FCL configuration to create a complete service definition for wallet authentication flows. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.discovery.getDiscoveryService(service) +``` + +Or import the namespace directly: + +```typescript +import { discovery } from "@onflow/fcl-core" + +discovery.getDiscoveryService(service) +``` + +#### Usage + +```typescript +// Get discovery service with default configuration +const discoveryService = await getDiscoveryService() +console.log(discoveryService.endpoint) // Configured discovery endpoint + +// Override discovery service endpoint +const customService = await getDiscoveryService({ + endpoint: "https://wallet.example.com/authn", + method: "HTTP/POST" +}) + +// Use with custom wallet service +const walletService = await getDiscoveryService({ + endpoint: "https://my-wallet.com/fcl", + provider: { + name: "My Wallet", + icon: "https://my-wallet.com/icon.png" + } +}) +``` + +#### Parameters + +##### `service` (optional) + + +- Type: `Partial` +- Description: Optional partial service configuration to override defaults + +#### Returns + +```typescript +export interface DiscoveryService extends Service { + discoveryAuthnInclude: string[] + discoveryAuthnExclude: string[] + discoveryFeaturesSuggested: string[] +} +``` + +### makeDiscoveryServices + +Creates an array of discovery services by combining extension services from the +window object with registered services from the service registry. This is used internally +by FCL to gather all available wallet and authentication services. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.discovery.makeDiscoveryServices() +``` + +Or import the namespace directly: + +```typescript +import { discovery } from "@onflow/fcl-core" + +discovery.makeDiscoveryServices() +``` + +#### Usage + +```typescript +// Get all available discovery services +const services = await makeDiscoveryServices() +console.log(services.length) // Number of available services +services.forEach(service => { + console.log(`Service: ${service.provider?.name}, Type: ${service.type}`) +}) +``` + +#### Returns + +```typescript +Promise +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/display.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/display.md new file mode 100644 index 0000000000..cdc0dd9ac2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/display.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "display" +description: "display function documentation." +--- + + + +# display + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.display(address) +``` + +Or import directly the specific function: + +```typescript +import { display } from "@onflow/fcl-core" + +display(address) +``` + + +## Parameters + +### `address` + + +- Type: `string` +- Description: - Flow address + + +## Returns + +`string` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/events.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/events.md new file mode 100644 index 0000000000..87c944c8b8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/events.md @@ -0,0 +1,99 @@ +--- +sidebar_position: 1 +title: "events" +description: "events function documentation." +--- + + + +# events + +Subscribes to Flow blockchain events in real-time. This function provides a way to listen +for specific events emitted by smart contracts on the Flow blockchain. It automatically handles +fallback to legacy polling for environments that don't support WebSocket subscriptions. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.events(filterOrType) +``` + +Or import directly the specific function: + +```typescript +import { events } from "@onflow/fcl-core" + +events(filterOrType) +``` + +## Usage + +```typescript +// Subscribe to a specific event type +import * as fcl from "@onflow/fcl" + +const unsubscribe = fcl.events("A.0x1654653399040a61.FlowToken.TokensWithdrawn") + .subscribe((event) => { + console.log("Event received:", event) + console.log("Event data:", event.data) + console.log("Transaction ID:", event.transactionId) + }) + +// Stop listening after 30 seconds +setTimeout(() => { + unsubscribe() +}, 30000) + +// Subscribe to multiple event types with error handling +const unsubscribe = fcl.events({ + eventTypes: [ + "A.0x1654653399040a61.FlowToken.TokensWithdrawn", + "A.0x1654653399040a61.FlowToken.TokensDeposited" + ] +}).subscribe( + (event) => { + console.log("Token event:", event.type, event.data) + }, + (error) => { + console.error("Event subscription error:", error) + } +) + +// Subscribe to events starting from a specific block height +const unsubscribe = fcl.events({ + eventTypes: ["A.CONTRACT.EVENT"], + startBlockHeight: 12345678 +}).subscribe((event) => { + console.log("Historical and new events:", event) +}) +``` + +## Parameters + +### `filterOrType` (optional) + + +- Type: `string` | [`EventFilter`](../types#eventfilter) +- Description: Event filter object or event type string. +If a string is provided, it will be treated as a single event type to subscribe to. +If an EventFilter object is provided, it can contain multiple event types and other filter criteria. + + +## Returns + +```typescript +{ subscribe: (onData: (event: Event) => void, onError?: (error: Error) => void) => () => void; } +``` + + +An object containing a subscribe method +• returns.subscribe Function to start the subscription +• returns.subscribe.onData Callback function called when an event is received +• returns.subscribe.onError Optional callback function called when an error occurs +• returns.subscribe.unsubscribe Function returned by subscribe() to stop the subscription + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/execStrategy.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/execStrategy.md new file mode 100644 index 0000000000..25b052ff7e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/execStrategy.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "execStrategy" +description: "execStrategy function documentation." +--- + + + +# execStrategy + +Executes a service strategy based on the service method. This function looks up the +appropriate strategy from the service registry and executes it with the provided parameters. +It's used internally by FCL to handle different communication methods with wallet services. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.execStrategy(execStrategyParams) +``` + +Or import directly the specific function: + +```typescript +import { execStrategy } from "@onflow/fcl-core" + +execStrategy(execStrategyParams) +``` + +## Usage + +```typescript +// Execute a service strategy (internal usage) +const response = await execStrategy({ + service: { method: "HTTP/POST", endpoint: "https://wallet.example.com/authz" }, + body: { transaction: "..." }, + config: execConfig, + abortSignal: controller.signal +}) +``` + +## Parameters + +### `execStrategyParams` + + +- Type: +```typescript +export interface ExecStrategyParams { + service: Service + body: Record + config: ExecConfig + abortSignal: AbortSignal + customRpc?: string + user?: CurrentUser + opts?: Record +} +``` + + +## Returns + +```typescript +export interface StrategyResponse { + status: string + data?: any + updates?: Record + local?: boolean + authorizationUpdates?: Record +} +``` + + +Promise resolving to the strategy response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getAccount.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getAccount.md new file mode 100644 index 0000000000..1dc31f58e0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getAccount.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getAccount" +description: "getAccount function documentation." +--- + + + +# 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. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getAccount(addr) +``` + +Or import directly the specific function: + +```typescript +import { getAccount } from "@onflow/fcl-core" + +getAccount(addr) +``` + +## Usage + +```typescript +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; +}; +``` + +## Parameters + +### `addr` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlock.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlock.md new file mode 100644 index 0000000000..42908e51cf --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlock.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getBlock" +description: "getBlock function documentation." +--- + + + +# 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.block(options)' if you do not need to pair with any other builders. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getBlock(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlock } from "@onflow/fcl-core" + +getBlock(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const latestSealedBlock = await fcl.send([ + fcl.getBlock(true) // isSealed = true +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: If the latest block should be sealed or not. See block states + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlockHeader.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlockHeader.md new file mode 100644 index 0000000000..7e10220d54 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getBlockHeader.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getBlockHeader" +description: "getBlockHeader function documentation." +--- + + + +# getBlockHeader + +A builder function that returns the interaction to get a block header. + +A block header contains metadata about a block without the full transaction details, making it more +lightweight than fetching the entire block. This is useful when you only need block metadata like +timestamp, height, parent hash, etc. + +Use with 'fcl.atBlockId()' and 'fcl.atBlockHeight()' when building the interaction to get headers for specific blocks. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getBlockHeader(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlockHeader } from "@onflow/fcl-core" + +getBlockHeader(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest sealed block header +const sealedHeader = await fcl.send([ + fcl.getBlockHeader(true) +]).then(fcl.decode); + +console.log("Block height:", sealedHeader.height); +console.log("Block timestamp:", sealedHeader.timestamp); +console.log("Parent block ID:", sealedHeader.parentId); + +// Get header for specific block +const blockHeader = await fcl.send([ + fcl.getBlockHeader(), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Get latest finalized block header +const finalizedHeader = await fcl.send([ + fcl.getBlockHeader(false) +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: Block finality state, true for sealed blocks, false for finalized blocks, null for latest + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getChainId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getChainId.md new file mode 100644 index 0000000000..a509259162 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getChainId.md @@ -0,0 +1,64 @@ +--- +sidebar_position: 1 +title: "getChainId" +description: "getChainId function documentation." +--- + + + +# getChainId + +Gets the chain ID if its set, otherwise gets the chain ID from the access node + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getChainId(opts) +``` + +Or import directly the specific function: + +```typescript +import { getChainId } from "@onflow/fcl-core" + +getChainId(opts) +``` + +## Usage + +```typescript +// Get chain ID using configured access node +import * as fcl from "@onflow/fcl" + +const chainId = await fcl.getChainId() +console.log("Connected to:", chainId) // "testnet" or "mainnet" +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface GetChainIdOptions { + node?: unknown + enableRequestLogging?: boolean + [key: string]: any +} +``` +- Description: Optional configuration parameters + + +## Returns + +`Promise` + + +Promise that resolves to the chain ID string (e.g., "mainnet", "testnet", "local") + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCollection.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCollection.md new file mode 100644 index 0000000000..72b7ba3d3c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCollection.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "getCollection" +description: "getCollection function documentation." +--- + + + +# getCollection + +A builder function that returns a collection containing a list of transaction IDs by its collection ID. + +A collection is a batch of transactions that have been included in a block. Each collection has a unique ID +which is the SHA3-256 hash of the collection payload. Collections are used to group related transactions +together for more efficient processing by the network. + +The collection ID provided must be from the current spork. Collections from past sporks are currently unavailable. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getCollection(id) +``` + +Or import directly the specific function: + +```typescript +import { getCollection } from "@onflow/fcl-core" + +getCollection(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get a collection and see what transactions it contains +const collection = await fcl.send([ + fcl.getCollection("cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5") +]).then(fcl.decode); + +console.log("Collection ID:", collection.id); +console.log("Transaction IDs:", collection.transactionIds); +console.log("Total transactions:", collection.transactionIds.length); + +// Process each transaction in the collection +for (const txId of collection.transactionIds) { + const transaction = await fcl.send([ + fcl.getTransaction(txId) + ]).then(fcl.decode); + console.log("Transaction:", transaction); +} +``` + +## Parameters + +### `id` (optional) + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCurrentUser.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCurrentUser.md new file mode 100644 index 0000000000..cb4649bc18 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getCurrentUser.md @@ -0,0 +1,127 @@ +--- +sidebar_position: 1 +title: "getCurrentUser" +description: "getCurrentUser function documentation." +--- + + + +# getCurrentUser + +Creates and configures the Current User service for managing user authentication and +authorization in Flow applications. This is the core service for handling user sessions, wallet +connections, transaction signing, and user data management. The service provides both callable +function interface and object methods for maximum flexibility. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getCurrentUser(config) +``` + +Or import directly the specific function: + +```typescript +import { getCurrentUser } from "@onflow/fcl-core" + +getCurrentUser(config) +``` + +## Usage + +```typescript +// Basic setup and authentication +import * as fcl from "@onflow/fcl" + +// Configure FCL +fcl.config({ + "accessNode.api": "https://rest-testnet.onflow.org", + "discovery.wallet": "https://fcl-discovery.onflow.org/testnet/authn" +}) + +// Create current user service +const currentUser = fcl.getCurrentUser({ + platform: "web" +}) + +// Authenticate user +const user = await currentUser.authenticate() +console.log("Authenticated user:", user.addr) + +// Subscribe to authentication state changes +const currentUser = fcl.getCurrentUser({ platform: "web" }) + +const unsubscribe = currentUser.subscribe((user) => { + if (user.loggedIn) { + console.log("User logged in:", user.addr) + document.getElementById("login-btn").style.display = "none" + document.getElementById("logout-btn").style.display = "block" + } else { + console.log("User logged out") + document.getElementById("login-btn").style.display = "block" + document.getElementById("logout-btn").style.display = "none" + } +}) + +// Clean up subscription +window.addEventListener("beforeunload", () => unsubscribe()) + +// Sign transactions with user authorization +const currentUser = fcl.getCurrentUser({ platform: "web" }) + +const txId = await fcl.mutate({ + cadence: ` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // Transfer tokens logic here + } + } + `, + args: (arg, t) => [ + arg("10.0", t.UFix64), + arg("0x01", t.Address) + ], + authz: currentUser.authorization +}) + +// Sign custom messages +const currentUser = fcl.getCurrentUser({ platform: "web" }) + +const message = Buffer.from("Hello, Flow!").toString("hex") +const signatures = await currentUser.signUserMessage(message) + +console.log("Message signatures:", signatures) +``` + +## Parameters + +### `config` + + +- Type: +```typescript +export interface CurrentUserConfig { + platform: string + discovery?: object | undefined + getStorageProvider?: () => Promise +} +``` +- Description: Configuration object for the current user service + + +## Returns + +```typescript +export interface CurrentUserService extends CurrentUserServiceApi { + (): CurrentUserServiceApi +} +``` + + +Current user service object with authentication and authorization methods + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEvents.md new file mode 100644 index 0000000000..a4e816daef --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEvents.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getEvents" +description: "getEvents function documentation." +--- + + + +# getEvents + +A builder function that returns the interaction to get events. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened during execution. +This function queries for events of a specific type within a range of block heights. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getEvents(eventType, start, end) +``` + +Or import directly the specific function: + +```typescript +import { getEvents } from "@onflow/fcl-core" + +getEvents(eventType, start, end) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get FlowToken transfer events from blocks 1000 to 2000 +const events = await fcl.send([ + fcl.getEvents("A.1654653399040a61.FlowToken.TokensDeposited", 1000, 2000) +]).then(fcl.decode); + +console.log("Found events:", events.length); +events.forEach(event => { + console.log("Event data:", event.data); + console.log("Transaction ID:", event.transactionId); +}); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get (e.g., "A.1654653399040a61.FlowToken.TokensWithdrawn") + +### `start` + + +- Type: `number` +- Description: The start block height to query from + +### `end` + + +- Type: `number` +- Description: The end block height to query to + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockHeightRange.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockHeightRange.md new file mode 100644 index 0000000000..612731ef30 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockHeightRange.md @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockHeightRange" +description: "getEventsAtBlockHeightRange function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +Block height range expresses the height of the start and end block in the chain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockHeightRange } from "@onflow/fcl-core" + +getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get events at block height range +await fcl + .send([ + fcl.getEventsAtBlockHeightRange( + "A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name + 35580624, // block to start looking for events at + 35580624 // block to stop looking for events at + ), + ]) + .then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `startHeight` + + +- Type: `number` +- Description: The height of the block to start looking for events (inclusive) + +### `endHeight` + + +- Type: `number` +- Description: The height of the block to stop looking for events (inclusive) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockIds.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockIds.md new file mode 100644 index 0000000000..9a95b47f6a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getEventsAtBlockIds.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockIds" +description: "getEventsAtBlockIds function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getEventsAtBlockIds(eventType, blockIds) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockIds } from "@onflow/fcl-core" + +getEventsAtBlockIds(eventType, blockIds) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const events = await fcl.send([ + fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [ + "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7", + "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f" + ]) +]).then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `blockIds` + + +- Type: `string[]` +- Description: The ids of the blocks to scan for events + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getExecHttpPost.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getExecHttpPost.md new file mode 100644 index 0000000000..1ed78b438b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getExecHttpPost.md @@ -0,0 +1,70 @@ +--- +sidebar_position: 1 +title: "getExecHttpPost" +description: "getExecHttpPost function documentation." +--- + + + +# getExecHttpPost + +Creates an HTTP POST strategy executor that handles wallet service communication +via HTTP POST requests. This function manages the full lifecycle including polling for +responses, handling local views, and managing user interactions. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getExecHttpPost(execLocal) +``` + +Or import directly the specific function: + +```typescript +import { getExecHttpPost } from "@onflow/fcl-core" + +getExecHttpPost(execLocal) +``` + +## Usage + +```typescript +// Create an HTTP POST executor +const httpPostExec = getExecHttpPost(async (view, { serviceEndpoint, onClose }) => { + // Render local view and return cleanup function + return [viewData, () => cleanup()] +}) +``` + +## Parameters + +### `execLocal` + + +- Type: +```typescript +export type ExecLocalFunction = ( + view: any, + options: { + serviceEndpoint: typeof serviceEndpoint + onClose: () => void + } +) => Promise<[any, () => void]> +``` +- Description: Function to execute local view rendering and user interaction + + +## Returns + +```typescript +({ service, body, config, opts }: ExecHttpPostParams) => Promise +``` + + +HTTP POST strategy function that can be used to execute services + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getMutate.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getMutate.md new file mode 100644 index 0000000000..cfe223e150 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getMutate.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "getMutate" +description: "getMutate function documentation." +--- + + + +# getMutate + +Factory function that returns a mutate function for a given currentUser. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getMutate(currentUserOrConfig) +``` + +Or import directly the specific function: + +```typescript +import { getMutate } from "@onflow/fcl-core" + +getMutate(currentUserOrConfig) +``` + + +## Parameters + +### `currentUserOrConfig` + + +- Type: +```typescript +export interface CurrentUserService extends CurrentUserServiceApi { + (): CurrentUserServiceApi +} +``` +- Description: CurrentUser actor or configuration + + +## Returns + +```typescript +(opts?: MutateOptions) => Promise +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNetworkParameters.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNetworkParameters.md new file mode 100644 index 0000000000..fc95507490 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNetworkParameters.md @@ -0,0 +1,68 @@ +--- +sidebar_position: 1 +title: "getNetworkParameters" +description: "getNetworkParameters function documentation." +--- + + + +# getNetworkParameters + +A builder function that returns the interaction to get network parameters. + +Network parameters contain important configuration information about the Flow network, +including the chain ID, which is essential for signing transactions correctly. +This information is crucial for ensuring transactions are submitted to the correct network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getNetworkParameters() +``` + +Or import directly the specific function: + +```typescript +import { getNetworkParameters } from "@onflow/fcl-core" + +getNetworkParameters() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get network parameters to verify chain ID +const params = await fcl.send([ + fcl.getNetworkParameters() +]).then(fcl.decode); + +console.log("Chain ID:", params.chainId); +console.log("Network:", params.name); + +// Use this to verify you're connected to the right network +if (params.chainId === "flow-mainnet") { + console.log("Connected to Flow Mainnet"); +} else if (params.chainId === "flow-testnet") { + console.log("Connected to Flow Testnet"); +} +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNodeVersionInfo.md new file mode 100644 index 0000000000..199c66a291 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getNodeVersionInfo.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getNodeVersionInfo" +description: "getNodeVersionInfo function documentation." +--- + + + +# getNodeVersionInfo + +A builder function for the Get Node Version Info interaction. + +Creates an interaction to retrieve version information from the connected Flow Access Node. +This includes details about the node's software version, protocol version, and spork information. + +Consider using the pre-built interaction 'fcl.nodeVersionInfo()' if you do not need to pair with any other builders. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getNodeVersionInfo() +``` + +Or import directly the specific function: + +```typescript +import { getNodeVersionInfo } from "@onflow/fcl-core" + +getNodeVersionInfo() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information using builder +const versionInfo = await fcl.send([ + fcl.getNodeVersionInfo() +]).then(fcl.decode); + +console.log("Node version:", versionInfo.semver); +console.log("Protocol version:", versionInfo.protocol_version); +console.log("Spork ID:", versionInfo.spork_id); + +// Use with other builders if needed +const interaction = await fcl.build([ + fcl.getNodeVersionInfo() + // other builders can be added here +]); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransaction.md new file mode 100644 index 0000000000..de9c6bfc7a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransaction.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getTransaction" +description: "getTransaction function documentation." +--- + + + +# getTransaction + +A builder function that returns the interaction to get a transaction by id. + +Transaction id is a hash of the encoded transaction payload and can be calculated before submitting the transaction to the network. +Transaction status represents the state of a transaction in the blockchain. Status can change until it is finalized. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id).onceExecuted()' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getTransaction(id) +``` + +Or import directly the specific function: + +```typescript +import { getTransaction } from "@onflow/fcl-core" + +getTransaction(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const tx = await fcl.send([ + fcl.getTransaction("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransactionStatus.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransactionStatus.md new file mode 100644 index 0000000000..aa853c4270 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/getTransactionStatus.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "getTransactionStatus" +description: "getTransactionStatus function documentation." +--- + + + +# getTransactionStatus + +A builder function that returns the status of transaction. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id)' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.getTransactionStatus(transactionId) +``` + +Or import directly the specific function: + +```typescript +import { getTransactionStatus } from "@onflow/fcl-core" + +getTransactionStatus(transactionId) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const status = await fcl.send([ + fcl.getTransactionStatus("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The id of the transaction to get the status of + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/index.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/index.md new file mode 100644 index 0000000000..bf059f51b9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/index.md @@ -0,0 +1,326 @@ +--- +sidebar_position: 1 +title: "@onflow/fcl-core" +description: "Core JavaScript/TypeScript library providing shared functionality for Flow blockchain interactions." +--- + + + +# @onflow/fcl-core + +## Overview + +The Flow fcl-core library provides a set of tools for developers to build applications on the Flow blockchain. + +## Installation + +You can install the @onflow/fcl-core package using npm or yarn: + +```bash +npm install @onflow/fcl-core +``` + +Or using yarn: + +```bash +yarn add @onflow/fcl-core +``` + +### Requirements + +- Node.js 14.x or later + +### Importing + +You can import the entire package: + +```typescript +import * as fcl from "@onflow/fcl-core" +``` + +Or import specific functions: + +```typescript +import { functionName } from "@onflow/fcl-core" +``` + +## 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. + +```javascript +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. + +```javascript +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 + +| 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](https://developers.onflow.org/http-api/). | +| `app.detail.title` | `Cryptokitties` | Your applications title, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.icon` | `https://fcl-discovery.onflow.org/images/blocto.png` | Url for your applications icon, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.description` | `Cryptokitties is a blockchain game` | Your applications description, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.url` | `https://cryptokitties.co` | Your applications url, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `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. | +| `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`, `testnet`, `mainnet`. | +| `walletconnect.projectId` | `YOUR_PROJECT_ID` | Your app's WalletConnect project ID. See [WalletConnect Cloud](https://cloud.walletconnect.com/sign-in) to obtain a project ID for your application. | +| `walletconnect.disableNotifications` | `false` | Optional flag to disable pending WalletConnect request notifications within the application's UI. | + +## Using Contracts in Scripts and Transactions + +### Address Replacement + +Configuration keys that start with `0x` will be replaced in FCL scripts and transactions, this allows you to write your script or transaction Cadence code once and not have to change it when you point your application at a difference instance of the Flow Blockchain. + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl.config().put('0xFungibleToken', '0xf233dcee88fe0abe'); + +async function myScript() { + return fcl + .send([ + fcl.script` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + access(all) fun main() { /* Rest of the script goes here */ } + `, + ]) + .then(fcl.decode); +} + +async function myTransaction() { + return fcl + .send([ + fcl.transaction` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + transaction { /* Rest of the transaction goes here */ } + `, + ]) + .then(fcl.decode); +} +``` + +#### Example + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl + .config() + .put('flow.network', 'testnet') + .put('walletconnect.projectId', 'YOUR_PROJECT_ID') + .put('accessNode.api', 'https://rest-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('app.detail.description', 'A test harness for FCL') + .put('app.detail.url', 'https://myapp.com') + .put('service.OpenID.scopes', 'email email_verified name zoneinfo') + .put('0xFlowToken', '0x7e60df042a9c0868'); +``` + +### Using `flow.json` for Contract Imports + +A simpler and more flexible way to manage contract imports in scripts and transactions is by using the `config.load` method in FCL. This lets you load contract configurations from a `flow.json` file, keeping your import syntax clean and allowing FCL to pick the correct contract addresses based on the network you're using. + +#### 1. Define Your Contracts in `flow.json` + +Here’s an example of a `flow.json` file with aliases for multiple networks: + +```json +{ + "contracts": { + "HelloWorld": { + "source": "./cadence/contracts/HelloWorld.cdc", + "aliases": { + "testnet": "0x1cf0e2f2f715450", + "mainnet": "0xf8d6e0586b0a20c7" + } + } + } +} +``` + +- **`source`**: Points to the contract file in your project. +- **`aliases`**: Maps each network to the correct contract address. + +#### 2. Configure FCL + +Load the `flow.json` file and set up FCL to use it: + +```javascript +import { config } from '@onflow/fcl'; +import flowJSON from '../flow.json'; + +config({ + 'flow.network': 'testnet', // Choose your network, e.g., testnet or mainnet + 'accessNode.api': 'https://rest-testnet.onflow.org', // Access node for the network + 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`, // Wallet discovery +}).load({ flowJSON }); +``` + +With this setup, FCL will automatically use the correct contract address based on the selected network (e.g., `testnet` or `mainnet`). + +#### 3. Use Contract Names in Scripts and Transactions + +After setting up `flow.json`, you can import contracts by name in your Cadence scripts or transactions: + +```cadence +import "HelloWorld" + +access(all) fun main(): String { + return HelloWorld.sayHello() +} +``` + +FCL replaces `"HelloWorld"` with the correct address from the `flow.json` configuration. + +> **Note**: Don’t store private keys in your `flow.json`. Instead, keep sensitive keys in a separate, `.gitignore`-protected file. + +## API Reference + +This section contains documentation for all of the functions and namespaces in the fcl-core package. + +- [account](./account.md) - Retrieve any account from Flow network's latest block or from a specified block... +- [AppUtils](./appUtils.md) (namespace) - Namespace containing AppUtils utilities +- [AppUtils.verifyAccountProof](./appUtils.md#verifyAccountProof) - Verifies the authenticity of an account proof signature on the Flow blockchain.... +- [arg](./arg.md) - A utility builder to be used with fcl.args[...] to create FCL supported... +- [args](./args.md) - A utility builder to be used with other builders to pass in arguments with a... +- [atBlockHeight](./atBlockHeight.md) - A builder function that returns a partial interaction to a block at a specific... +- [atBlockId](./atBlockId.md) - A builder function that returns a partial interaction to a block at a specific... +- [authorization](./authorization.md) - Creates an authorization function for use in transactions. An authorization... +- [authorizations](./authorizations.md) - A utility builder to set the authorizations on a transaction. Authorizations... +- [block](./block.md) - Query the network for block by id, height or get the latest block. Block ID is... +- [build](./build.md) - A builder function that creates an interaction from an array of builder... +- [buildMessageHandler](./buildMessageHandler.md) - Creates a message handler for processing window messages from wallet service... +- [cadence](./cadence.md) - Creates a template function +- [cdc](./cdc.md) - Creates a template function +- [config](./config.md) - Sets the config +- [createSignableVoucher](./createSignableVoucher.md) - Creates a signable voucher object from an interaction for signing purposes. A... +- [decode](./decode.md) - Decodes the response from 'fcl.send()' into the appropriate JSON representation... +- [discovery](./discovery.md) (namespace) - Namespace containing discovery utilities +- [discovery.getDiscoveryService](./discovery.md#getDiscoveryService) - Creates and configures a discovery service object used for wallet... +- [discovery.makeDiscoveryServices](./discovery.md#makeDiscoveryServices) - Creates an array of discovery services by combining extension services from the... +- [display](./display.md) - Adds 0x to address if not already present +- [events](./events.md) - Subscribes to Flow blockchain events in real-time. This function provides a way... +- [execStrategy](./execStrategy.md) - Executes a service strategy based on the service method. This function looks up... +- [getAccount](./getAccount.md) - A builder function that returns the interaction to get an account by address.... +- [getBlock](./getBlock.md) - A builder function that returns the interaction to get the latest block. Use... +- [getBlockHeader](./getBlockHeader.md) - A builder function that returns the interaction to get a block header. A block... +- [getChainId](./getChainId.md) - Gets the chain ID if its set, otherwise gets the chain ID from the access node +- [getCollection](./getCollection.md) - A builder function that returns a collection containing a list of transaction... +- [getCurrentUser](./getCurrentUser.md) - Creates and configures the Current User service for managing user authentication... +- [getEvents](./getEvents.md) - A builder function that returns the interaction to get events. Events are... +- [getEventsAtBlockHeightRange](./getEventsAtBlockHeightRange.md) - A builder function that returns all instances of a particular event (by name)... +- [getEventsAtBlockIds](./getEventsAtBlockIds.md) - A builder function that returns all instances of a particular event (by name)... +- [getExecHttpPost](./getExecHttpPost.md) - Creates an HTTP POST strategy executor that handles wallet service communication... +- [getMutate](./getMutate.md) - Factory function that returns a mutate function for a given currentUser. +- [getNetworkParameters](./getNetworkParameters.md) - A builder function that returns the interaction to get network parameters.... +- [getNodeVersionInfo](./getNodeVersionInfo.md) - A builder function for the Get Node Version Info interaction. Creates an... +- [getTransaction](./getTransaction.md) - A builder function that returns the interaction to get a transaction by id.... +- [getTransactionStatus](./getTransactionStatus.md) - A builder function that returns the status of transaction. The transaction id... +- [initServiceRegistry](./initServiceRegistry.md) - Initializes the service registry with core strategies for different... +- [InteractionTemplateUtils](./interactionTemplateUtils.md) (namespace) - Namespace containing InteractionTemplateUtils utilities +- [InteractionTemplateUtils.deriveCadenceByNetwork](./interactionTemplateUtils.md#deriveCadenceByNetwork) - Fills import addresses in Cadence for network +- [InteractionTemplateUtils.generateDependencyPin](./interactionTemplateUtils.md#generateDependencyPin) - Generates a dependency pin for a smart contract on the Flow blockchain. A... +- [InteractionTemplateUtils.generateDependencyPinAtLatestSealedBlock](./interactionTemplateUtils.md#generateDependencyPinAtLatestSealedBlock) - Generates a dependency pin for a smart contract at the latest sealed block on... +- [InteractionTemplateUtils.generateTemplateId](./interactionTemplateUtils.md#generateTemplateId) - Generates Interaction Template ID for a given Interaction Template +- [InteractionTemplateUtils.getInteractionTemplateAudits](./interactionTemplateUtils.md#getInteractionTemplateAudits) - Checks whether a set of auditors have audited a given Interaction Template on... +- [InteractionTemplateUtils.getTemplateArgumentMessage](./interactionTemplateUtils.md#getTemplateArgumentMessage) - Gets Interaction Template argument message by message key, argument label, and... +- [InteractionTemplateUtils.getTemplateMessage](./interactionTemplateUtils.md#getTemplateMessage) - Get Interaction Template argument message +- [InteractionTemplateUtils.verifyDependencyPinsSame](./interactionTemplateUtils.md#verifyDependencyPinsSame) - Checks if an Interaction Template's pins match those generated at a block height +- [InteractionTemplateUtils.verifyDependencyPinsSameAtLatestSealedBlock](./interactionTemplateUtils.md#verifyDependencyPinsSameAtLatestSealedBlock) - Checks if an Interaction Template's pins match those generated at the latest... +- [InteractionTemplateUtils.verifyGeneratedTemplateId](./interactionTemplateUtils.md#verifyGeneratedTemplateId) - Verifies the given Interaction Template Id has been correctly generated +- [invariant](./invariant.md) +- [isBad](./isBad.md) - Checks if an interaction has a failed status. +- [isOk](./isOk.md) - Checks if an interaction has a successful status. +- [isReactNative](./isReactNative.md) - Checks if the current environment is React Native. This function returns a... +- [limit](./limit.md) - A utility builder to set the compute limit on a transaction. The compute limit... +- [nodeVersionInfo](./nodeVersionInfo.md) - Retrieve version information from the connected Flow Access Node. This function... +- [normalizePollingResponse](./normalizePollingResponse.md) - Normalizes a polling response to ensure compatibility with FCL format +- [param](./param.md) - Legacy function for setting a single parameter on an interaction. +- [params](./params.md) - Legacy function for setting parameters on an interaction. +- [payer](./payer.md) - A builder function that adds payer account(s) to a transaction. Every... +- [ping](./ping.md) - A builder function that creates a ping interaction to test connectivity to the... +- [pipe](./pipe.md) - Async pipe function to compose interactions. The pipe function is the foundation... +- [pluginRegistry](./pluginRegistry.md) - Global plugin registry instance for managing FCL plugins. This registry handles... +- [proposer](./proposer.md) - A builder function that adds the proposer to a transaction. The proposer is... +- [query](./query.md) - Allows you to submit scripts to query the blockchain. +- [queryRaw](./queryRaw.md) - Allows you to submit scripts to query the blockchain and get raw response data. +- [ref](./ref.md) - A builder function that sets the reference block for a transaction. The... +- [sansPrefix](./sansPrefix.md) - Removes 0x from address if present +- [script](./script.md) - A builder function that creates a script interaction. Scripts allow you to write... +- [send](./send.md) - Sends arbitrary scripts, transactions, and requests to Flow. This method... +- [serialize](./serialize.md) - Serializes a Flow transaction or script to a JSON-formatted signable voucher... +- [serviceEndpoint](./serviceEndpoint.md) - Creates a URL object from a service endpoint with additional parameters... +- [setIsReactNative](./setIsReactNative.md) - Sets the React Native environment flag for FCL. This function should be called... +- [subscribe](./subscribe.md) - Subscribe to real-time data from the Flow blockchain and automatically decode... +- [subscribeEvents](./subscribeEvents.md) - Subscribe to events with the given filter and parameters. Creates a subscription... +- [subscribeRaw](./subscribeRaw.md) - Subscribe to a topic without decoding the data. This function creates a raw... +- [transaction](./transaction.md) - A template builder to use a Cadence transaction for an interaction. FCL "mutate"... +- [tx](./tx.md) - Creates a transaction monitor that provides methods for tracking and subscribing... +- [validator](./validator.md) - A builder function that adds a validator to a transaction. Validators are... +- [verifyUserSignatures](./verifyUserSignatures.md) - Verify a valid signature/s for an account on Flow. +- [voucherIntercept](./voucherIntercept.md) - A builder function that intercepts and modifies a voucher. This function is... +- [voucherToTxId](./voucherToTxId.md) - Converts a voucher object to a transaction ID. This function computes the... +- [WalletUtils](./walletUtils.md) (namespace) - Namespace containing WalletUtils utilities +- [WalletUtils.approve](./walletUtils.md#approve) - Sends an approval response to FCL with the provided data. This indicates that... +- [WalletUtils.close](./walletUtils.md#close) - Closes the wallet service window/iframe and notifies FCL that the service is... +- [WalletUtils.decline](./walletUtils.md#decline) - Sends a decline response to FCL indicating that the user has rejected or... +- [WalletUtils.encodeAccountProof](./walletUtils.md#encodeAccountProof) - Encodes account proof data for cryptographic signing on the Flow blockchain.... +- [WalletUtils.encodeMessageFromSignable](./walletUtils.md#encodeMessageFromSignable) - Encodes a message from a signable object for a specific signer address. This... +- [WalletUtils.injectExtService](./walletUtils.md#injectExtService) - Injects an external authentication service into the global FCL extensions array.... +- [WalletUtils.onMessageFromFCL](./walletUtils.md#onMessageFromFCL) - Sets up a message listener to receive messages from the parent FCL application.... +- [WalletUtils.ready](./walletUtils.md#ready) - Initiates the communication handshake between a wallet service and FCL. This... +- [WalletUtils.redirect](./walletUtils.md#redirect) - Sends a redirect response to FCL indicating that the operation requires a... +- [WalletUtils.sendMsgToFCL](./walletUtils.md#sendMsgToFCL) - Sends messages from a wallet or service back to the parent FCL application. This... +- [why](./why.md) - Returns the reason for an interaction failure. +- [withPrefix](./withPrefix.md) - Adds 0x to address if not already present + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/initServiceRegistry.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/initServiceRegistry.md new file mode 100644 index 0000000000..a6ee597003 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/initServiceRegistry.md @@ -0,0 +1,66 @@ +--- +sidebar_position: 1 +title: "initServiceRegistry" +description: "initServiceRegistry function documentation." +--- + + + +# initServiceRegistry + +Initializes the service registry with core strategies for different communication methods. +This function sets up the registry that manages wallet service strategies and should be called once +during FCL initialization with platform-specific core strategies. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.initServiceRegistry(options) +``` + +Or import directly the specific function: + +```typescript +import { initServiceRegistry } from "@onflow/fcl-core" + +initServiceRegistry(options) +``` + +## Usage + +```typescript +// Initialize service registry with core strategies +const registry = initServiceRegistry({ + coreStrategies: { + "HTTP/POST": httpPostStrategy, + "IFRAME/RPC": iframeRpcStrategy, + "POP/RPC": popupRpcStrategy + } +}) +``` + +## Parameters + +### `options` + + +- Type: +```typescript +{ coreStrategies: any; } +``` + + +## Returns + +```typescript +Readonly<{ add: (servicePlugin: any) => void; getServices: () => any[]; getStrategy: (method: any) => unknown; getStrategies: () => any[]; }> +``` + + +The initialized service registry instance + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/interactionTemplateUtils.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/interactionTemplateUtils.md new file mode 100644 index 0000000000..c68426958d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/interactionTemplateUtils.md @@ -0,0 +1,522 @@ +--- +sidebar_position: 1 +title: "InteractionTemplateUtils" +description: "Namespace containing InteractionTemplateUtils utilities" +--- + + + +# InteractionTemplateUtils + +## Overview + +Namespace containing InteractionTemplateUtils utilities + +## Functions + +### deriveCadenceByNetwork + +Fills import addresses in Cadence for network + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.deriveCadenceByNetwork(deriveCadenceByNetworkParams) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.deriveCadenceByNetwork(deriveCadenceByNetworkParams) +``` + + +#### Parameters + +##### `deriveCadenceByNetworkParams` + + +- Type: +```typescript +export interface DeriveCadenceByNetworkParams { + network: string + template: InteractionTemplate +} +``` + +#### Returns + +`Promise` + +### generateDependencyPin + +Generates a dependency pin for a smart contract on the Flow blockchain. A dependency +pin is a cryptographic hash that uniquely identifies a specific version of a contract at a particular +state. This is used in Interaction Templates to ensure consistent behavior by pinning to specific +contract versions and preventing issues from contract updates. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.generateDependencyPin(generateDependencyPinParams, opts) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.generateDependencyPin(generateDependencyPinParams, opts) +``` + +#### Usage + +```typescript +// Generate dependency pin for a contract at current state +import * as fcl from "@onflow/fcl" + +const dependencyPin = await fcl.InteractionTemplateUtils.generateDependencyPin({ + version: "1.1.0", + address: "0x1654653399040a61", + contractName: "FlowToken" +}) +``` + +#### Parameters + +##### `generateDependencyPinParams` + + +- Type: +```typescript +export interface GenerateDependencyPinParams { + address: string + contractName: string + blockHeight: number +} +``` + +##### `opts` (optional) + + +- Type: `any` +- Description: Additional options to pass to the underlying interaction + +#### Returns + +`Promise` + +### generateDependencyPinAtLatestSealedBlock + +Generates a dependency pin for a smart contract at the latest sealed block on the Flow +blockchain. This variant ensures the pin is generated against the most recent finalized state of the +network, providing consistency and avoiding issues with pending transactions affecting the pin generation. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.generateDependencyPinAtLatestSealedBlock(generateDependencyPinParams, opts) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.generateDependencyPinAtLatestSealedBlock(generateDependencyPinParams, opts) +``` + +#### Usage + +```typescript +// Generate dependency pin at latest sealed block +import * as fcl from "@onflow/fcl" + +const dependencyPin = await fcl.InteractionTemplateUtils.generateDependencyPinAtLatestSealedBlock({ + version: "1.1.0", + address: "0x1654653399040a61", + contractName: "FlowToken" +}) +``` + +#### Parameters + +##### `generateDependencyPinParams` + + +- Type: +```typescript +export interface GenerateDependencyPinParams { + address: string + contractName: string + blockHeight: number +} +``` + +##### `opts` (optional) + + +- Type: `any` +- Description: Additional options to pass to the underlying interaction + +#### Returns + +`Promise` + +### generateTemplateId + +Generates Interaction Template ID for a given Interaction Template + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.generateTemplateId(interactionTemplate) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.generateTemplateId(interactionTemplate) +``` + + +#### Parameters + +##### `interactionTemplate` + + +- Type: +```typescript +{ template: InteractionTemplate; } +``` + +#### Returns + +`Promise` + +### getInteractionTemplateAudits + +Checks whether a set of auditors have audited a given Interaction Template on the Flow +blockchain. This function validates that the provided interaction template has been properly audited +for security by trusted auditors before execution. It queries the Flow blockchain's audit contract +to verify audit status. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.getInteractionTemplateAudits(getInteractionTemplateAuditsParams, opts) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.getInteractionTemplateAudits(getInteractionTemplateAuditsParams, opts) +``` + +#### Usage + +```typescript +// Check if template has been audited by specific auditors +import * as fcl from "@onflow/fcl" + +const template = { + f_type: "InteractionTemplate", + f_version: "1.1.0", + id: "template-id-123", + data: { + type: "transaction", + interface: "...", + cadence: "transaction { ... }" + } +} + +const auditorAddresses = [ + "0x1234567890abcdef", + "0xabcdef1234567890" +] + +const auditResults = await fcl.InteractionTemplateUtils.getInteractionTemplateAudits({ + template, + auditors: auditorAddresses +}) + +console.log(auditResults) +// { "0x1234567890abcdef": true, "0xabcdef1234567890": false } +``` + +#### Parameters + +##### `getInteractionTemplateAuditsParams` + + +- Type: +```typescript +export interface GetInteractionTemplateAuditsParams { + template: InteractionTemplate + auditors?: string[] +} +``` + +##### `opts` (optional) + + +- Type: +```typescript +export interface GetInteractionTemplateAuditsOpts { + flowInteractionAuditContract?: string +} +``` +- Description: Optional configuration parameters + +#### Returns + +`Promise>` + +### getTemplateArgumentMessage + +Gets Interaction Template argument message by message key, argument label, and localization + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.getTemplateArgumentMessage(getTemplateArgumentMessageParams) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.getTemplateArgumentMessage(getTemplateArgumentMessageParams) +``` + + +#### Parameters + +##### `getTemplateArgumentMessageParams` + + +- Type: +```typescript +export interface GetTemplateArgumentMessageParams { + localization?: string + argumentLabel: string + messageKey: string + template: InteractionTemplate +} +``` + +#### Returns + +`string` + +### getTemplateMessage + +Get Interaction Template argument message + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.getTemplateMessage(getTemplateMessageParams) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.getTemplateMessage(getTemplateMessageParams) +``` + + +#### Parameters + +##### `getTemplateMessageParams` + + +- Type: +```typescript +export interface GetTemplateMessageParams { + localization?: string + messageKey: string + template: InteractionTemplate +} +``` + +#### Returns + +`string` + +### verifyDependencyPinsSame + +Checks if an Interaction Template's pins match those generated at a block height + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.verifyDependencyPinsSame(verifyDependencyPinsSameParams, opts) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.verifyDependencyPinsSame(verifyDependencyPinsSameParams, opts) +``` + + +#### Parameters + +##### `verifyDependencyPinsSameParams` + + +- Type: +```typescript +export interface VerifyDependencyPinsSameParams { + template: InteractionTemplate + blockHeight?: number +} +``` + +##### `opts` (optional) + + +- Type: +```typescript +export interface VerifyDependencyPinsSameOpts { + [key: string]: any +} +``` + +#### Returns + +`Promise` + +### verifyDependencyPinsSameAtLatestSealedBlock + +Checks if an Interaction Template's pins match those generated at the latest block height + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.verifyDependencyPinsSameAtLatestSealedBlock(verifyDependencyPinsSameAtLatestSealedBlockParams, opts) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.verifyDependencyPinsSameAtLatestSealedBlock(verifyDependencyPinsSameAtLatestSealedBlockParams, opts) +``` + + +#### Parameters + +##### `verifyDependencyPinsSameAtLatestSealedBlockParams` + + +- Type: +```typescript +export interface VerifyDependencyPinsSameAtLatestSealedBlockParams { + template: InteractionTemplate + network: string +} +``` + +##### `opts` (optional) + + +- Type: +```typescript +export interface VerifyDependencyPinsSameOpts { + [key: string]: any +} +``` + +#### Returns + +`Promise` + +### verifyGeneratedTemplateId + +Verifies the given Interaction Template Id has been correctly generated + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.InteractionTemplateUtils.verifyGeneratedTemplateId(interactionTemplate) +``` + +Or import the namespace directly: + +```typescript +import { InteractionTemplateUtils } from "@onflow/fcl-core" + +InteractionTemplateUtils.verifyGeneratedTemplateId(interactionTemplate) +``` + + +#### Parameters + +##### `interactionTemplate` + + +- Type: +```typescript +{ template: InteractionTemplate; } +``` + +#### Returns + +`Promise` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/invariant.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/invariant.md new file mode 100644 index 0000000000..bd61003442 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/invariant.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +title: "invariant" +description: "invariant function documentation." +--- + + + +# invariant + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.invariant(args) +``` + +Or import directly the specific function: + +```typescript +import { invariant } from "@onflow/fcl-core" + +invariant(args) +``` + + +## Parameters + +### `args` (optional) + + +- Type: `any[]` + + +## Returns + +```typescript +(ix: any) => any +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/isBad.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isBad.md new file mode 100644 index 0000000000..d8edffe3e8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isBad.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 1 +title: "isBad" +description: "isBad function documentation." +--- + + + +# isBad + +Checks if an interaction has a failed status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.isBad(ix) +``` + +Or import directly the specific function: + +```typescript +import { isBad } from "@onflow/fcl-core" + +isBad(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isBad, why } from "@onflow/sdk" + +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isBad(response)) { + console.log("Transaction failed:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is BAD, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/isOk.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isOk.md new file mode 100644 index 0000000000..85fd5ef50c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isOk.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "isOk" +description: "isOk function documentation." +--- + + + +# isOk + +Checks if an interaction has a successful status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.isOk(ix) +``` + +Or import directly the specific function: + +```typescript +import { isOk } from "@onflow/fcl-core" + +isOk(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isOk } from "@onflow/sdk" + +// Check if a transaction was successful +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isOk(response)) { + console.log("Transaction was successful"); +} else { + console.log("Transaction failed"); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is OK, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/isReactNative.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isReactNative.md new file mode 100644 index 0000000000..261fbb96d7 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/isReactNative.md @@ -0,0 +1,57 @@ +--- +sidebar_position: 1 +title: "isReactNative" +description: "isReactNative function documentation." +--- + + + +# isReactNative + +Checks if the current environment is React Native. This function returns a boolean +indicating whether FCL is running in a React Native environment rather than a browser or Node.js. +This is useful for platform-specific functionality and enabling React Native-specific features. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.isReactNative() +``` + +Or import directly the specific function: + +```typescript +import { isReactNative } from "@onflow/fcl-core" + +isReactNative() +``` + +## Usage + +```typescript +// Check if running in React Native +import * as fcl from "@onflow/fcl" + +if (fcl.isReactNative()) { + console.log("Running in React Native") + // Use React Native specific wallet integrations + // Enable deep linking for wallet connections +} else { + console.log("Running in browser or Node.js") + // Use web-based wallet integrations +} +``` + + +## Returns + +`boolean` + + +True if running in React Native environment, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/limit.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/limit.md new file mode 100644 index 0000000000..c51569d895 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/limit.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "limit" +description: "limit function documentation." +--- + + + +# limit + +A utility builder to set the compute limit on a transaction. + +The compute limit is the maximum amount of computation that can be performed during transaction execution. +Setting an appropriate compute limit helps prevent infinite loops and ensures predictable transaction costs. + +Read more about [computation cost](https://docs.onflow.org/concepts/fees/#computation-cost) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.limit(limit) +``` + +Or import directly the specific function: + +```typescript +import { limit } from "@onflow/fcl-core" + +limit(limit) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + // Complex transaction logic here + } + } + `, + limit: 1000 // Set compute limit to 1000 +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.limit(9999) // Set higher limit for complex operations +]); +``` + +## Parameters + +### `limit` + + +- Type: `number` +- Description: The maximum amount of computation for the transaction + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/nodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/nodeVersionInfo.md new file mode 100644 index 0000000000..92f8ab92d3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/nodeVersionInfo.md @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +title: "nodeVersionInfo" +description: "nodeVersionInfo function documentation." +--- + + + +# nodeVersionInfo + +Retrieve version information from the connected Flow Access Node. + +This function returns detailed information about the Flow node's version, including the protocol version, spork information, and node-specific details. This is useful for debugging, compatibility checks, and understanding the network state. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.nodeVersionInfo(opts) +``` + +Or import directly the specific function: + +```typescript +import { nodeVersionInfo } from "@onflow/fcl-core" + +nodeVersionInfo(opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information +const versionInfo = await fcl.nodeVersionInfo(); +console.log(versionInfo); +// { +// semver: "v0.37.13", +// commit: "12345abcd", +// spork_id: "mainnet-23", +// protocol_version: "2.13.10", +// spork_root_block_height: "88483760", +// node_root_block_height: "88483760" +// } + +// Check compatibility +const info = await fcl.nodeVersionInfo(); +if (info.protocol_version.startsWith("2.13")) { + console.log("Compatible with current protocol version"); +} +``` + +## Parameters + +### `opts` (optional) + + +- Type: `any` +- Description: Optional parameters for the request + + +## Returns + +[`Promise`](../types#nodeversioninfo) + + +A promise that resolves to a block response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/normalizePollingResponse.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/normalizePollingResponse.md new file mode 100644 index 0000000000..3447fb4125 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/normalizePollingResponse.md @@ -0,0 +1,78 @@ +--- +sidebar_position: 1 +title: "normalizePollingResponse" +description: "normalizePollingResponse function documentation." +--- + + + +# normalizePollingResponse + +Normalizes a polling response to ensure compatibility with FCL format + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.normalizePollingResponse(resp) +``` + +Or import directly the specific function: + +```typescript +import { normalizePollingResponse } from "@onflow/fcl-core" + +normalizePollingResponse(resp) +``` + +## Usage + +```typescript +const resp = normalizePollingResponse({ + f_type: "PollingResponse", + f_vsn: "1.0.0", + status: "PENDING", // PENDING | APPROVED | DECLINED | REDIRECT + reason: null, // Reason for Declining Transaction + data: null, // Return value for APPROVED + updates: BackChannelRpc, + local: Frame, +}) +``` + +## Parameters + +### `resp` + + +- Type: +```typescript +export interface PollingResponse { + f_type: "PollingResponse" + f_vsn: "1.0.0" + status: "APPROVED" | "DECLINED" | "REDIRECT" + reason: string | null + data: any +} +``` +- Description: The polling response to normalize + + +## Returns + +```typescript +export interface PollingResponse { + f_type: "PollingResponse" + f_vsn: "1.0.0" + status: "APPROVED" | "DECLINED" | "REDIRECT" + reason: string | null + data: any +} +``` + + +The normalized polling response or null + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/param.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/param.md new file mode 100644 index 0000000000..ca072d2113 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/param.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "param" +description: "param function documentation." +--- + + + +# param + +Legacy function for setting a single parameter on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.param(params) +``` + +Or import directly the specific function: + +```typescript +import { param } from "@onflow/fcl-core" + +param(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameter to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/params.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/params.md new file mode 100644 index 0000000000..ff356e21c5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/params.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "params" +description: "params function documentation." +--- + + + +# params + +Legacy function for setting parameters on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.params(params) +``` + +Or import directly the specific function: + +```typescript +import { params } from "@onflow/fcl-core" + +params(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameters to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/payer.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/payer.md new file mode 100644 index 0000000000..a7457ccdec --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/payer.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "payer" +description: "payer function documentation." +--- + + + +# payer + +A builder function that adds payer account(s) to a transaction. + +Every transaction requires at least one payer. + +The payer is the account that pays the transaction fee for executing the transaction on the network. +The payer account must have sufficient Flow tokens to cover the transaction fees. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#payer) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.payer(ax) +``` + +Or import directly the specific function: + +```typescript +import { payer } from "@onflow/fcl-core" + +payer(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using current user as payer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Transaction fees paid by: ".concat(acct.address.toString())) + } + } + `, + payer: fcl.authz // Current user as payer +}); + +// Using custom payer with builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.proposer(fcl.authz), // Current user as proposer + fcl.authorizations([fcl.authz]), // Current user as authorizer + fcl.payer(customPayerAuthz) // Custom payer pays fees +]); + +// Multiple payers (advanced use case) +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.payer([payerAuthz1, payerAuthz2]) // Multiple payers split fees +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An account address or an array of account addresses + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that takes an interaction object and returns a new interaction object with the payer(s) added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/ping.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/ping.md new file mode 100644 index 0000000000..85c933b601 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/ping.md @@ -0,0 +1,72 @@ +--- +sidebar_position: 1 +title: "ping" +description: "ping function documentation." +--- + + + +# ping + +A builder function that creates a ping interaction to test connectivity to the Flow Access Node. + +The ping interaction is a simple way to test if the Flow Access Node is reachable and responding. This is useful for health checks, connectivity testing, and debugging network issues. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.ping() +``` + +Or import directly the specific function: + +```typescript +import { ping } from "@onflow/fcl-core" + +ping() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple ping to test connectivity +try { + const response = await fcl.send([fcl.ping()]); + console.log("Access Node is reachable"); +} catch (error) { + console.error("Access Node is not reachable:", error); +} + +// Use ping for health checks +const healthCheck = async () => { + try { + await fcl.send([fcl.ping()]); + return { status: "healthy", timestamp: new Date().toISOString() }; + } catch (error) { + return { status: "unhealthy", error: error.message, timestamp: new Date().toISOString() }; + } +}; + +const health = await healthCheck(); +console.log("Health status:", health); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/pipe.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/pipe.md new file mode 100644 index 0000000000..fc48b95b83 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/pipe.md @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +title: "pipe" +description: "pipe function documentation." +--- + + + +# pipe + +Async pipe function to compose interactions. + +The pipe function is the foundation for composing multiple interaction builder functions together. +It sequentially applies builder functions to an interaction, allowing for complex interaction construction. +Each function in the pipe receives the result of the previous function and can modify or validate the interaction. + +Pipe has two main forms: +1. `pipe(builderFunctions)`: Returns a builder function +2. `pipe(interaction, builderFunctions)`: Directly executes the pipe on an interaction + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.pipe(fns) +``` + +Or import directly the specific function: + +```typescript +import { pipe } from "@onflow/fcl-core" + +pipe(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using pipe to create a reusable builder +const myTransactionBuilder = fcl.pipe([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Use the builder +const interaction = await fcl.build([myTransactionBuilder]); + +// Pipe is used internally by build() and send() +await fcl.send([ + fcl.script`access(all) fun main(): Int { return 42 }` +]); // This uses pipe internally +``` + +## Parameters + +### `fns` + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: Array of builder functions to apply + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +An interaction builder function when called with just functions, or a Promise<Interaction> when called with an interaction and functions + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/pluginRegistry.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/pluginRegistry.md new file mode 100644 index 0000000000..747df5674d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/pluginRegistry.md @@ -0,0 +1,54 @@ +--- +sidebar_position: 1 +title: "pluginRegistry" +description: "pluginRegistry function documentation." +--- + + + +# pluginRegistry + +Global plugin registry instance for managing FCL plugins. This registry handles +the registration and management of various FCL plugins including service plugins that add +new wallet services and strategies. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.pluginRegistry() +``` + +Or import directly the specific function: + +```typescript +import { pluginRegistry } from "@onflow/fcl-core" + +pluginRegistry() +``` + +## Usage + +```typescript +// Add a plugin to the registry +pluginRegistry.add({ + name: "MyWalletPlugin", + f_type: "ServicePlugin", + type: "discovery-service", + services: [...], + serviceStrategy: { method: "CUSTOM/RPC", exec: customExecFunction } +}) +``` + + +## Returns + +```typescript +Readonly<{ add: (plugins: any) => void; getPlugins: () => Map; }> +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/proposer.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/proposer.md new file mode 100644 index 0000000000..f656bd6865 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/proposer.md @@ -0,0 +1,94 @@ +--- +sidebar_position: 1 +title: "proposer" +description: "proposer function documentation." +--- + + + +# proposer + +A builder function that adds the proposer to a transaction. + +The proposer is responsible for providing the proposal key and paying the network fee for the transaction. +The proposer key is used to specify the sequence number and prevent replay attacks. + +Every transaction requires exactly one proposer. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#proposer) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.proposer(authz) +``` + +Or import directly the specific function: + +```typescript +import { proposer } from "@onflow/fcl-core" + +proposer(authz) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using the current user as proposer +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + log("Hello from proposer!") + } + } + `, + proposer: fcl.authz +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `authz` + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: The authorization object for the proposer + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction object and returns a new interaction object with the proposer added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/query.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/query.md new file mode 100644 index 0000000000..e49bb28c55 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/query.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "query" +description: "query function documentation." +--- + + + +# query + +Allows you to submit scripts to query the blockchain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.query(opts) +``` + +Or import directly the specific function: + +```typescript +import { query } from "@onflow/fcl-core" + +query(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface QueryOptions { + cadence?: string + args?: ArgsFn + template?: any + isSealed?: boolean + limit?: number +} +``` +- Description: Query options configuration + + +## Returns + +`Promise` + + +A JSON representation of the response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/queryRaw.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/queryRaw.md new file mode 100644 index 0000000000..d83fc617c2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/queryRaw.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "queryRaw" +description: "queryRaw function documentation." +--- + + + +# queryRaw + +Allows you to submit scripts to query the blockchain and get raw response data. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.queryRaw(opts) +``` + +Or import directly the specific function: + +```typescript +import { queryRaw } from "@onflow/fcl-core" + +queryRaw(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; + +const result = await fcl.queryRaw({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface QueryOptions { + cadence?: string + args?: ArgsFn + template?: any + isSealed?: boolean + limit?: number +} +``` +- Description: Query Options and configuration + + +## Returns + +`Promise` + + +A promise that resolves to the raw query result + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/ref.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/ref.md new file mode 100644 index 0000000000..e615211aa5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/ref.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "ref" +description: "ref function documentation." +--- + + + +# ref + +A builder function that sets the reference block for a transaction. + +The 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.ref(refBlock) +``` + +Or import directly the specific function: + +```typescript +import { ref } from "@onflow/fcl-core" + +ref(refBlock) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Set specific reference block for transaction +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction with custom reference block") + } + } + `, + fcl.ref("a1b2c3d4e5f6789..."), // Custom reference block ID + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Usually, you don't need to set reference block manually +// as FCL will automatically set it to the latest block +``` + +## Parameters + +### `refBlock` + + +- Type: `string` +- Description: The reference block ID + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/sansPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/sansPrefix.md new file mode 100644 index 0000000000..f44db126e7 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/sansPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "sansPrefix" +description: "sansPrefix function documentation." +--- + + + +# sansPrefix + +Removes 0x from address if present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.sansPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { sansPrefix } from "@onflow/fcl-core" + +sansPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address without 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/script.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/script.md new file mode 100644 index 0000000000..40826189b7 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/script.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "script" +description: "script function documentation." +--- + + + +# script + +A builder function that creates a script interaction. Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. + +You can learn more about [Cadence here](https://cadence-lang.org/docs/language), 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.script(args) +``` + +Or import directly the specific function: + +```typescript +import { script } from "@onflow/fcl-core" + +script(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray | ((x?: unknown) => string), ...unknown[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/send.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/send.md new file mode 100644 index 0000000000..3480ef60b1 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/send.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "send" +description: "send function documentation." +--- + + + +# 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. + +WARNING: Must be used in conjunction with 'fcl.decode(response)' to get back correct keys and all values in JSON. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.send(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { send } from "@onflow/fcl-core" + +send(args, opts) +``` + +## Usage + +```typescript +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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +false | Function | (false | Function)[] +``` +- Description: An array of builders (functions that take an interaction object and return a new interaction object) + +### `opts` (optional) + + +- Type: `any` +- Description: Additional optional options for the request + + +## Returns + +`Promise` + + +A promise that resolves to a ResponseObject containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/serialize.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/serialize.md new file mode 100644 index 0000000000..2bb3fb4c35 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/serialize.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "serialize" +description: "serialize function documentation." +--- + + + +# serialize + +Serializes a Flow transaction or script to a JSON-formatted signable voucher that can be +used for offline signing or inspection. This is useful for creating signable transactions that can be +signed by external wallets or hardware devices. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.serialize(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { serialize } from "@onflow/fcl-core" + +serialize(args, opts) +``` + +## Usage + +```typescript +// Serialize a simple transaction +import * as fcl from "@onflow/fcl" + +const voucher = await fcl.serialize([ + fcl.transaction` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // Transaction logic here + } + } + `, + fcl.args([ + fcl.arg("10.0", fcl.t.UFix64), + fcl.arg("0x01", fcl.t.Address) + ]), + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]) +``` + +## Parameters + +### `args` + + +- Type: `(false` | `InteractionBuilderFn)[]` | [`Interaction`](../types#interaction) +- Description: Array of interaction builder functions or a pre-built interaction object. Builder functions are typically from + +### `opts` (optional) + + +- Type: +```typescript +export interface SerializeOptions { + resolve?: InteractionBuilderFn +} +``` +- Description: Optional configuration object + + +## Returns + +`Promise` + + +A JSON string representation of the signable voucher that contains all +the transaction details needed for signing + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/serviceEndpoint.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/serviceEndpoint.md new file mode 100644 index 0000000000..06f2154306 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/serviceEndpoint.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "serviceEndpoint" +description: "serviceEndpoint function documentation." +--- + + + +# serviceEndpoint + +Creates a URL object from a service endpoint with additional parameters including +the application origin and service-specific parameters. This function is used internally by +FCL strategies to construct the complete URL for service communication. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.serviceEndpoint(service) +``` + +Or import directly the specific function: + +```typescript +import { serviceEndpoint } from "@onflow/fcl-core" + +serviceEndpoint(service) +``` + +## Usage + +```typescript +// Create URL from service +const service = { + endpoint: "https://wallet.example.com/authn", + params: { + appName: "MyApp", + nonce: "abc123" + } +} +const url = serviceEndpoint(service) +console.log(url.toString()) +// https://wallet.example.com/authn?l6n=https://myapp.com&appName=MyApp&nonce=abc123 +``` + +## Parameters + +### `service` + + +- Type: [`Service`](../types#service) +- Description: The service object containing endpoint and optional parameters + + +## Returns + +`URL` + + +URL object with all parameters appended as query string parameters + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/setIsReactNative.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/setIsReactNative.md new file mode 100644 index 0000000000..d3a95ff075 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/setIsReactNative.md @@ -0,0 +1,63 @@ +--- +sidebar_position: 1 +title: "setIsReactNative" +description: "setIsReactNative function documentation." +--- + + + +# setIsReactNative + +Sets the React Native environment flag for FCL. This function should be called during +initialization of React Native applications to inform FCL that it's running in a React Native +environment. This enables React Native-specific behaviors and optimizations. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.setIsReactNative(value) +``` + +Or import directly the specific function: + +```typescript +import { setIsReactNative } from "@onflow/fcl-core" + +setIsReactNative(value) +``` + +## Usage + +```typescript +// Set React Native flag during app initialization +import * as fcl from "@onflow/fcl" + +// In your React Native app's entry point (e.g., App.js) +fcl.setIsReactNative(true) + +// Configure FCL for React Native +fcl.config({ + "accessNode.api": "https://rest-testnet.onflow.org", + "discovery.wallet": "https://fcl-discovery.onflow.org/api/testnet/authn" +}) +``` + +## Parameters + +### `value` + + +- Type: `boolean` +- Description: True to indicate React Native environment, false otherwise + + +## Returns + +`void` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribe.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribe.md new file mode 100644 index 0000000000..a1729eeb83 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribe.md @@ -0,0 +1,101 @@ +--- +sidebar_position: 1 +title: "subscribe" +description: "subscribe function documentation." +--- + + + +# subscribe + +Subscribe to real-time data from the Flow blockchain and automatically decode the responses. + +This is a utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the 'decode' function. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.subscribe(subscribeParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribe } from "@onflow/fcl-core" + +subscribe(subscribeParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to events +const subscription = fcl.subscribe({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (events) => { + console.log("Received events:", events); + }, + onError: (error) => { + console.error("Subscription error:", error); + } +}); + +// Subscribe to blocks +const blockSubscription = fcl.subscribe({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (block) => { + console.log("New block:", block); + }, + onError: (error) => { + console.error("Block subscription error:", error); + } +}); + +// Later, to unsubscribe: +subscription.unsubscribe(); +blockSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeParams` + + +- Type: +```typescript +SubscribeParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +[`Subscription`](../types#subscription) + + +A subscription object that allows you to manage the subscription (e.g., to unsubscribe later) + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeEvents.md new file mode 100644 index 0000000000..d3cb279dc5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeEvents.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "subscribeEvents" +description: "subscribeEvents function documentation." +--- + + + +# subscribeEvents + +Subscribe to events with the given filter and parameters. + +Creates a subscription to listen for real-time events from the Flow blockchain. This function configures +the subscription parameters for filtering specific events based on type, addresses, contracts, and other criteria. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened. +Subscriptions allow you to listen for these events in real-time without polling. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.subscribeEvents(eventFilter) +``` + +Or import directly the specific function: + +```typescript +import { subscribeEvents } from "@onflow/fcl-core" + +subscribeEvents(eventFilter) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Subscribe to FlowToken transfer events +const subscription = await fcl.send([ + fcl.subscribeEvents({ + eventTypes: [ + "A.1654653399040a61.FlowToken.TokensWithdrawn", + "A.1654653399040a61.FlowToken.TokensDeposited" + ], + startHeight: 1000000, // Start from specific block height + heartbeatInterval: 3000 // 3 second heartbeat + }) +]); + +// Subscribe to events from specific contracts +const contractSubscription = await fcl.send([ + fcl.subscribeEvents({ + contracts: ["FlowToken", "FungibleToken"], + addresses: ["0x1654653399040a61"] + }) +]); + +// Handle the subscription data elsewhere using fcl.subscribe() +``` + +## Parameters + +### `eventFilter` + + +- Type: [`EventFilter`](../types#eventfilter) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeRaw.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeRaw.md new file mode 100644 index 0000000000..8939983b6c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/subscribeRaw.md @@ -0,0 +1,105 @@ +--- +sidebar_position: 1 +title: "subscribeRaw" +description: "subscribeRaw function documentation." +--- + + + +# subscribeRaw + +Subscribe to a topic without decoding the data. + +This function creates a raw subscription to Flow blockchain data streams without automatic decoding. +It's useful when you need more control over data processing or want to handle raw responses directly. +For most use cases, consider using the `subscribe()` function instead which provides automatic decoding. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.subscribeRaw(subscribeRawParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribeRaw } from "@onflow/fcl-core" + +subscribeRaw(subscribeRawParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to raw event data without automatic decoding +const rawSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (rawData) => { + console.log("Raw event data:", rawData); + // Handle raw data manually - no automatic decoding + }, + onError: (error) => { + console.error("Raw subscription error:", error); + } +}); + +// Subscribe to raw block data +const blockSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (rawBlock) => { + console.log("Raw block data:", rawBlock); + }, + onError: (error) => { + console.error("Error:", error); + } +}); + +// Unsubscribe when done +rawSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeRawParams` + + +- Type: +```typescript +SubscribeRawParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +```typescript +{ unsubscribe: () => void; } +``` + + +A subscription object with an unsubscribe method + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/transaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/transaction.md new file mode 100644 index 0000000000..108c201d51 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/transaction.md @@ -0,0 +1,104 @@ +--- +sidebar_position: 1 +title: "transaction" +description: "transaction function documentation." +--- + + + +# transaction + +A template builder to use a Cadence transaction for an interaction. FCL "mutate" does the work of building, signing, and sending a transaction behind the scenes. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.transaction(args) +``` + +Or import directly the specific function: + +```typescript +import { transaction } from "@onflow/fcl-core" + +transaction(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +// Basic transaction usage +await fcl.mutate({ + cadence: ` + transaction(a: Int) { + prepare(acct: &Account) { + log(acct) + log(a) + } + } + `, + args: (arg, t) => [ + arg(6, t.Int) + ], + limit: 50 +}) + +// Single party, single signature +// Proposer, payer and authorizer are the same account +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + authz: currentUser, // Optional. Will default to currentUser if not provided. + limit: 50, +}) + +// Multiple parties +// Proposer and authorizer are the same account, but different payer +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + proposer: authzFn, + payer: authzTwoFn, + authorizations: [authzFn], + limit: 50, +}) +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray, ...any[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/tx.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/tx.md new file mode 100644 index 0000000000..b6261e8be7 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/tx.md @@ -0,0 +1,120 @@ +--- +sidebar_position: 1 +title: "tx" +description: "tx function documentation." +--- + + + +# tx + +Creates a transaction monitor that provides methods for tracking and subscribing to +transaction status updates on the Flow blockchain. This function returns an object with methods +to get snapshots, subscribe to status changes, and wait for specific transaction states. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.tx(transactionId, opts) +``` + +Or import directly the specific function: + +```typescript +import { tx } from "@onflow/fcl-core" + +tx(transactionId, opts) +``` + +## Usage + +```typescript +// Basic transaction monitoring +import * as fcl from "@onflow/fcl" + +const txId = await fcl.mutate({ + cadence: ` + transaction { + execute { log("Hello, World!") } + } + ` +}) + +// Get current status +const status = await fcl.tx(txId).snapshot() +console.log("Current status:", status.status) + +// Subscribe to all status changes +const unsubscribe = fcl.tx(txId).subscribe((status) => { + console.log("Status update:", status.status) + if (status.status === fcl.transaction.isSealed) { + console.log("Transaction sealed!") + console.log("Events:", status.events) + } +}) +// Clean up subscription when done +setTimeout(() => unsubscribe(), 60000) + +// Wait for specific transaction states +try { + // Wait for finalization (consensus reached) + const finalizedStatus = await fcl.tx(txId).onceFinalized() + console.log("Transaction finalized") + + // Wait for execution (transaction executed) + const executedStatus = await fcl.tx(txId).onceExecuted() + console.log("Transaction executed") + + // Wait for sealing (transaction sealed in block) + const sealedStatus = await fcl.tx(txId).onceSealed() + console.log("Transaction sealed:", sealedStatus.events) +} catch (error) { + console.error("Transaction failed:", error.message) +} + +// Handle transaction errors +fcl.tx(txId).subscribe( + (status) => { + if (status.statusCode === 1) { + console.error("Transaction error:", status.errorMessage) + } + }, + (error) => { + console.error("Subscription error:", error) + } +) +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The 64-character hex transaction ID to monitor. Must be a valid +Flow transaction hash (64 bytes represented as hex string). + +### `opts` (optional) + + +- Type: +```typescript +{ pollRate?: number; txNotFoundTimeout?: number; } +``` +- Description: Optional configuration parameters + + +## Returns + +```typescript +{ snapshot: () => Promise; subscribe: (onData: (txStatus: TransactionStatus) => void, onError?: (err: Error) => void) => () => void; onceFinalized: () => Promise; onceExecuted: () => Promise; onceSealed: () => Promise; } +``` + + +Transaction monitor object with methods for tracking transaction status + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/validator.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/validator.md new file mode 100644 index 0000000000..aeda96e935 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/validator.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "validator" +description: "validator function documentation." +--- + + + +# validator + +A builder function that adds a validator to a transaction. + +Validators are functions that run during transaction building to check for invalid configurations or parameters. +They help catch errors early before submitting transactions to the network, preventing failed transactions +and wasted compute costs. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.validator(cb) +``` + +Or import directly the specific function: + +```typescript +import { validator } from "@onflow/fcl-core" + +validator(cb) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Custom validator to ensure account has sufficient balance +const validateBalance = (ix) => { + if (ix.message.computeLimit > 1000) { + throw new Error("Compute limit too high for this account"); + } + return ix; +}; + +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.validator(validateBalance), + fcl.limit(500) // This will pass validation +]); +``` + +## Parameters + +### `cb` + + +- Type: `Function` +- Description: The validator function that takes an interaction and returns it (or throws an error if invalid) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/verifyUserSignatures.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/verifyUserSignatures.md new file mode 100644 index 0000000000..ffeb2358ab --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/verifyUserSignatures.md @@ -0,0 +1,40 @@ +--- +sidebar_position: 1 +title: "verifyUserSignatures" +description: "verifyUserSignatures function documentation." +--- + + + +# verifyUserSignatures + +Verify a valid signature/s for an account on Flow. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.verifyUserSignatures() +``` + +Or import directly the specific function: + +```typescript +import { verifyUserSignatures } from "@onflow/fcl-core" + +verifyUserSignatures() +``` + + + +## Returns + +```typescript +Promise | ((...args: any[]) => Promise>) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherIntercept.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherIntercept.md new file mode 100644 index 0000000000..32db834caa --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherIntercept.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "voucherIntercept" +description: "voucherIntercept function documentation." +--- + + + +# voucherIntercept + +A builder function that intercepts and modifies a voucher. + +This function is useful for debugging, logging, or making modifications to +the transaction data. The voucher contains all the transaction details in their final form. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.voucherIntercept(fn) +``` + +Or import directly the specific function: + +```typescript +import { voucherIntercept } from "@onflow/fcl-core" + +voucherIntercept(fn) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Intercept voucher for logging +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.voucherIntercept((voucher) => { + console.log("Voucher details:", { + cadence: voucher.cadence, + proposalKey: voucher.proposalKey, + payer: voucher.payer, + authorizers: voucher.authorizers, + computeLimit: voucher.computeLimit + }); + }), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]) +]); +``` + +## Parameters + +### `fn` + + +- Type: +```typescript +type VoucherInterceptFn = (voucher: Voucher) => any | Promise +``` +- Description: The function to intercept and potentially modify the voucher + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherToTxId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherToTxId.md new file mode 100644 index 0000000000..c04ffc5d86 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/voucherToTxId.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: "voucherToTxId" +description: "voucherToTxId function documentation." +--- + + + +# voucherToTxId + +Converts a voucher object to a transaction ID. + +This function computes the transaction ID by encoding and hashing the voucher. +The transaction ID can be used to track the transaction status on the Flow network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.voucherToTxId(voucher) +``` + +Or import directly the specific function: + +```typescript +import { voucherToTxId } from "@onflow/fcl-core" + +voucherToTxId(voucher) +``` + +## Usage + +```typescript +import { voucherToTxId, createSignableVoucher } from "@onflow/sdk" +import * as fcl from "@onflow/fcl"; + +// Create a voucher from an interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Hello, Flow!") + } + } + `, + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]); + +const voucher = createSignableVoucher(interaction); + +// Calculate the transaction ID +const txId = voucherToTxId(voucher); +console.log("Transaction ID:", txId); +// Returns something like: "a1b2c3d4e5f6789..." + +// You can use this ID to track the transaction +const txStatus = await fcl.tx(txId).onceSealed(); +console.log("Transaction status:", txStatus); +``` + +## Parameters + +### `voucher` + + +- Type: +```typescript +export interface Voucher { + cadence: string + refBlock: string + computeLimit: number + arguments: VoucherArgument[] + proposalKey: VoucherProposalKey + payer: string + authorizers: string[] + payloadSigs: Sig[] + envelopeSigs: Sig[] +} +``` +- Description: The voucher object to convert + + +## Returns + +`string` + + +A transaction ID string + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/walletUtils.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/walletUtils.md new file mode 100644 index 0000000000..e223d57388 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/walletUtils.md @@ -0,0 +1,619 @@ +--- +sidebar_position: 1 +title: "WalletUtils" +description: "Namespace containing WalletUtils utilities" +--- + + + +# WalletUtils + +## Overview + +Namespace containing WalletUtils utilities + +## Functions + +### approve + +Sends an approval response to FCL with the provided data. This indicates that the user +has approved the requested operation (authentication, transaction signing, etc.) and includes the +resulting data (signatures, account information, etc.). + +Sends "FCL:VIEW:RESPONSE". with status "APPROVED". + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.approve(data) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.approve(data) +``` + +#### Usage + +```typescript +// Approve authentication with account data +import { approve } from "@onflow/fcl" + +const accountData = { + f_type: "AuthnResponse", + f_vsn: "1.0.0", + addr: "0x1234567890abcdef", + services: [ + { + f_type: "Service", + f_vsn: "1.0.0", + type: "authz", + method: "HTTP/POST", + endpoint: "https://wallet.example.com/authz" + } + ] +} + +approve(accountData) +``` + +#### Parameters + +##### `data` + + +- Type: `any` +- Description: The approval data to send back to FCL (signatures, account info, etc.) + +#### Returns + +`void` + +### close + +Closes the wallet service window/iframe and notifies FCL that the service is shutting down. +This should be called when the user cancels an operation or when the wallet service needs to close itself. + +Sends "FCL:VIEW:CLOSE". + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.close() +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.close() +``` + + +#### Returns + +`void` + +### decline + +Sends a decline response to FCL indicating that the user has rejected or cancelled +the requested operation. This should be called when the user explicitly cancels an operation +or when an error prevents the operation from completing. + +Sends "FCL:VIEW:RESPONSE". with status "DECLINED". + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.decline(reason) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.decline(reason) +``` + +#### Usage + +```typescript +// Decline when user cancels authentication +import { decline } from "@onflow/fcl" + +document.getElementById('cancel-btn').addEventListener('click', () => { + decline("User cancelled authentication") +}) +``` + +#### Parameters + +##### `reason` + + +- Type: `string` +- Description: Human-readable reason for declining the request + +#### Returns + +`void` + +### encodeAccountProof + +Encodes account proof data for cryptographic signing on the Flow blockchain. This function +creates a standardized message format that combines the application identifier, account address, +and nonce into a format suitable for cryptographic signing. The encoded message can then be signed +by the account's private key to create an account proof. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.encodeAccountProof(accountProofData, includeDomainTag) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.encodeAccountProof(accountProofData, includeDomainTag) +``` + +#### Usage + +```typescript +// Basic account proof encoding +import { encodeAccountProof } from "@onflow/fcl" + +const accountProofData = { + address: "0x1234567890abcdef", + nonce: "75f8587e5bd982ec9289c5be1f9426bd12b4c1de9c7a7e4d8c5f9e8b2a7c3f1e9", // 64 hex chars (32 bytes) + appIdentifier: "MyAwesomeApp" +} + +const encodedMessage = encodeAccountProof(accountProofData) +console.log("Encoded message:", encodedMessage) +``` + +#### Parameters + +##### `accountProofData` + + +- Type: +```typescript +export interface AccountProofData { + address: string + nonce: string + signatures: CompositeSignature[] +} +``` + +##### `includeDomainTag` (optional) + + +- Type: `boolean` +- Description: Whether to include the FCL domain tag in the encoding + +#### Returns + +`string` + +### encodeMessageFromSignable + +Encodes a message from a signable object for a specific signer address. + +This function determines whether the signer should sign the transaction payload or envelope +based on their role in the transaction (authorizer, proposer, or payer), then encodes the +appropriate message for signing. + +Payload signers include authorizers and proposers (but not payers) +Envelope signers include only payers + +The encoded message is what gets signed by the account's private key to create the transaction signature. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.encodeMessageFromSignable(signable, signerAddress) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.encodeMessageFromSignable(signable, signerAddress) +``` + +#### Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// This function is typically used internally by authorization functions +// when implementing custom wallet connectors or signing flows + +const signable = { + voucher: { + cadence: "transaction { prepare(acct: AuthAccount) {} }", + authorizers: ["0x01"], + proposalKey: { address: "0x01", keyId: 0, sequenceNum: 42 }, + payer: "0x02", + refBlock: "a1b2c3", + computeLimit: 100, + arguments: [], + payloadSigs: [] + } +}; + +// For an authorizer (payload signer) +const authorizerMessage = fcl.encodeMessageFromSignable(signable, "0x01"); +console.log("Authorizer signs:", authorizerMessage); + +// For a payer (envelope signer) +const payerMessage = fcl.encodeMessageFromSignable(signable, "0x02"); +console.log("Payer signs:", payerMessage); +``` + +#### Parameters + +##### `signable` + + +- Type: `any` +- Description: The signable object containing transaction data and voucher + +##### `signerAddress` + + +- Type: `any` +- Description: The address of the signer to encode the message for + +#### Returns + +```typescript +(signable: Signable, signerAddress: string) => string +``` + +### injectExtService + +Injects an external authentication service into the global FCL extensions array. +This function is used by wallet providers to register their authentication services with FCL, +making them available for user authentication. The service must be of type "authn" and have +a valid endpoint. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.injectExtService(service) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.injectExtService(service) +``` + +#### Usage + +```typescript +// Register a wallet authentication service +const walletService = { + type: "authn", + endpoint: "https://example-wallet.com/fcl/authn", + method: "HTTP/POST", + identity: { address: "0x123..." }, + provider: { name: "Example Wallet" } +} +fcl.WalletUtils.injectExtService(walletService) +``` + +#### Parameters + +##### `service` + + +- Type: [`Service`](../types#service) +- Description: The authentication service to inject. Must have type "authn" and a valid endpoint + +#### Returns + +`void` + +### onMessageFromFCL + +Sets up a message listener to receive messages from the parent FCL application. This +function is used by wallet services to listen for specific message types from FCL and respond +accordingly. It handles message filtering, data sanitization, and provides context about the +message origin for security purposes. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.onMessageFromFCL(messageType, cb) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.onMessageFromFCL(messageType, cb) +``` + +#### Usage + +```typescript +// Listen for authentication requests from FCL +import { onMessageFromFCL } from "@onflow/fcl" + +const removeListener = onMessageFromFCL("FCL:VIEW:READY:RESPONSE", (data, context) => { + console.log("FCL is ready for communication") + console.log("Message from:", context.origin) + console.log("Ready data:", data) + + // Verify origin for security + if (context.origin === "https://myapp.com") { + initializeWalletServices() + } else { + console.warn("Unexpected origin:", context.origin) + } +}) + +// Stop listening when wallet service closes +window.addEventListener("beforeunload", () => { + removeListener() +}) +``` + +#### Parameters + +##### `messageType` + + +- Type: `string` +- Description: The specific message type to listen for (e.g., "FCL:VIEW:READY:RESPONSE") + +##### `cb` (optional) + + +- Type: +```typescript +(data: any, context: { origin: string; }) => void +``` +- Description: Callback function executed when a matching message is received + +#### Returns + +```typescript +() => void +``` + +### ready + +Initiates the communication handshake between a wallet service and FCL. This function +listens for the "FCL:VIEW:READY:RESPONSE" message from FCL and automatically sends "FCL:VIEW:READY" +to indicate the wallet service is ready to receive requests. This is typically the first function +called when a wallet service loads. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.ready(cb, msg) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.ready(cb, msg) +``` + +#### Usage + +```typescript +// Basic wallet service initialization +import { ready } from "@onflow/fcl" + +ready((data, context) => { + console.log("FCL is ready to communicate") + console.log("FCL origin:", context.origin) + console.log("Ready data:", data) + + // Wallet service is now ready to handle authentication requests + initializeWalletUI() +}) +``` + +#### Parameters + +##### `cb` + + +- Type: +```typescript +(data: any, context: { origin: string; }) => void +``` +- Description: Callback function executed when FCL responds with ready confirmation + +##### `msg` (optional) + + +- Type: +```typescript +export interface PollingResponse { + f_type: "PollingResponse" + f_vsn: "1.0.0" + status: "APPROVED" | "DECLINED" | "REDIRECT" + reason: string | null + data: any +} +``` +- Description: Optional message payload to include with ready signal + +#### Returns + +`void` + +### redirect + +Sends a redirect response to FCL indicating that the operation requires a redirect +to complete. This is used when the wallet service needs to redirect the user to another URL +(such as a native app deep link or external service). + +Sends "FCL:VIEW:RESPONSE". with status "REDIRECT". + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.redirect(data) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.redirect(data) +``` + +#### Usage + +```typescript +// Redirect to native wallet app +import { redirect } from "@onflow/fcl" + +redirect({ + f_type: "RedirectResponse", + f_vsn: "1.0.0", + url: "flow-wallet://sign?transaction=abc123", + callback: "https://myapp.com/callback" +}) +``` + +#### Parameters + +##### `data` + + +- Type: `any` +- Description: Redirect data containing the target URL and any additional parameters + +#### Returns + +`void` + +### sendMsgToFCL + +Sends messages from a wallet or service back to the parent FCL application. This function +handles communication between wallet UIs (running in iframes, popups, or redirects) and the main FCL +application. It automatically detects the communication method (redirect, iframe, or popup) and sends +the message accordingly. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.WalletUtils.sendMsgToFCL(type, msg) +``` + +Or import the namespace directly: + +```typescript +import { WalletUtils } from "@onflow/fcl-core" + +WalletUtils.sendMsgToFCL(type, msg) +``` + +#### Usage + +```typescript +// Send approval response with signature data +import { sendMsgToFCL } from "@onflow/fcl" + +sendMsgToFCL("FCL:VIEW:RESPONSE", { + f_type: "CompositeSignature", + f_vsn: "1.0.0", + addr: "0x1234567890abcdef", + keyId: 0, + signature: "abc123..." +}) +``` + +#### Parameters + +##### `type` + + +- Type: `string` +- Description: The message type identifier (e.g., "FCL:VIEW:RESPONSE", "FCL:VIEW:READY") + +##### `msg` (optional) + + +- Type: +```typescript +export interface PollingResponse { + f_type: "PollingResponse" + f_vsn: "1.0.0" + status: "APPROVED" | "DECLINED" | "REDIRECT" + reason: string | null + data: any +} +``` +- Description: Optional message payload containing response data + +#### Returns + +`void` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/why.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/why.md new file mode 100644 index 0000000000..6088ecfc56 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/why.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "why" +description: "why function documentation." +--- + + + +# why + +Returns the reason for an interaction failure. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.why(ix) +``` + +Or import directly the specific function: + +```typescript +import { why } from "@onflow/fcl-core" + +why(ix) +``` + +## Usage + +```typescript +import { Bad, why, initInteraction } from "@onflow/sdk" + +const interaction = Bad(initInteraction(), "Network timeout"); +console.log(why(interaction)); // "Network timeout" + +// Used with error handling +if (isBad(response)) { + console.error("Error occurred:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to get the failure reason from + + +## Returns + +`string` + + +The reason string or undefined if no reason is set + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-core/withPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl-core/withPrefix.md new file mode 100644 index 0000000000..ccb0b3781f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-core/withPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "withPrefix" +description: "withPrefix function documentation." +--- + + + +# withPrefix + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-core" + +fcl.withPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { withPrefix } from "@onflow/fcl-core" + +withPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/account.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/account.md new file mode 100644 index 0000000000..0bddefc910 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/account.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "account" +description: "account function documentation." +--- + + + +# 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.account(address, accountQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { account } from "@onflow/fcl-react-native" + +account(address, accountQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get account from latest block height +const account = await fcl.account("0x1d007d755706c469"); +console.log("Address:", account.address); +console.log("Balance:", account.balance); +console.log("Keys:", account.keys); +console.log("Contracts:", Object.keys(account.contracts)); + +// Get account at a specific block height +const historicalAccount = await fcl.account("0x1d007d755706c469", { + height: 12345 +}); + +// Get account at a specific block ID +const accountAtBlock = await fcl.account("0x1d007d755706c469", { + id: "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3" +}); + +// Get account from sealed block +const sealedAccount = await fcl.account("0x1d007d755706c469", { + isSealed: true +}); + +// Alternative using builder pattern +fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(123) +]).then(fcl.decode); +``` + +## Parameters + +### `address` + + +- Type: `string` +- Description: Address of the account + +### `accountQueryOptions` (optional) + + +- Type: +```typescript +interface AccountQueryOptions { + height?: number + id?: string + isSealed?: boolean +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#account) + + +A promise that resolves to an Account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/arg.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/arg.md new file mode 100644 index 0000000000..5ac5bc02a6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/arg.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "arg" +description: "arg function documentation." +--- + + + +# arg + +A utility builder to be used with fcl.args[...] to create FCL supported arguments for interactions. + +Arguments are used to pass data to Cadence scripts and transactions. The arguments must match the number and order declared in the Cadence script. +This function creates an ArgumentObject that holds the value and type passed in. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.arg(value, xform) +``` + +Or import directly the specific function: + +```typescript +import { arg } from "@onflow/fcl-react-native" + +arg(value, xform) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +const result = await fcl.query({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `value` + + +- Type: +```typescript +TypeDescriptorInput +``` +- Description: Any value that you are looking to pass to other builders + +### `xform` + + +- Type: `T` +- Description: A type supported by Flow (FType descriptor) + + +## Returns + +```typescript +CadenceArgument +``` + + +An ArgumentObject that holds the value and type passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/args.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/args.md new file mode 100644 index 0000000000..6b8b3965db --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/args.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "args" +description: "args function documentation." +--- + + + +# args + +A utility builder to be used with other builders to pass in arguments with a value and supported type. + +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. +This function returns a Partial Interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.args(ax) +``` + +Or import directly the specific function: + +```typescript +import { args } from "@onflow/fcl-react-native" + +args(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +await fcl.mutate({ + cadence: ` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // transaction logic + } + } + `, + args: (arg, t) => [ + arg("10.0", t.UFix64), // Will be the first argument `amount: UFix64` + arg("0xba1132bc08f82fe2", t.Address), // Will be the second argument `to: Address` + ], +}) +``` + +## Parameters + +### `ax` + + +- Type: +```typescript +CadenceArgument[] +``` +- Description: An array of argument objects created with fcl.arg() + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A Partial Interaction object containing the arguments and types passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockHeight.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockHeight.md new file mode 100644 index 0000000000..21c394ae39 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockHeight.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockHeight" +description: "atBlockHeight function documentation." +--- + + + +# 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. + +Block height expresses the height of the block on the chain. The latest block height increases by one for every valid block produced. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.atBlockHeight(height) +``` + +Or import directly the specific function: + +```typescript +import { atBlockHeight } from "@onflow/fcl-react-native" + +atBlockHeight(height) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block at specific height +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode); + +// Get account at specific block height +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Execute script at specific block height +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().height + } + `, + fcl.atBlockHeight(100) +]).then(fcl.decode); +``` + +## Parameters + +### `height` + + +- Type: `number` +- Description: The height of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockId.md new file mode 100644 index 0000000000..b0af6470ff --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/atBlockId.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockId" +description: "atBlockId function documentation." +--- + + + +# 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. + +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'). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.atBlockId(id) +``` + +Or import directly the specific function: + +```typescript +import { atBlockId } from "@onflow/fcl-react-native" + +atBlockId(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block by ID +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get account at specific block ID +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockId("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); + +// Execute script at specific block +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().timestamp + } + `, + fcl.atBlockId("a1b2c3d4e5f6") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` +- Description: The ID of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authenticate.md new file mode 100644 index 0000000000..932925ac92 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authenticate.md @@ -0,0 +1,44 @@ +--- +sidebar_position: 1 +title: "authenticate" +description: "authenticate function documentation." +--- + + + +# authenticate + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.authenticate(opts) +``` + +Or import directly the specific function: + +```typescript +import { authenticate } from "@onflow/fcl-react-native" + +authenticate(opts) +``` + + +## Parameters + +### `opts` (optional) + + +- Type: `{}` + + +## Returns + +[`Promise`](../types#currentuser) + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorization.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorization.md new file mode 100644 index 0000000000..51ca8b3de6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorization.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: "authorization" +description: "authorization function documentation." +--- + + + +# authorization + +Creates an authorization function for use in transactions. + +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. + +Read more about [authorization functions](https://docs.onflow.org/fcl/reference/authorization-function/) and [transaction roles](https://docs.onflow.org/concepts/transaction-signing/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.authorization(addr, signingFunction, keyId, sequenceNum) +``` + +Or import directly the specific function: + +```typescript +import { authorization } from "@onflow/fcl-react-native" + +authorization(addr, signingFunction, keyId, sequenceNum) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { ec as EC } from "elliptic"; + +// Create a signing function +const signingFunction = ({ message }) => { + // Your signing logic here + return { + addr: "0x123456789abcdef0", + keyId: 0, + signature: "your_signature_here" + }; +}; + +// Create authorization +const authz = fcl.authorization( + "0x123456789abcdef0", // account address + signingFunction, // signing function + 0, // key ID + 42 // sequence number +); + +// Use in transaction +await fcl.mutate({ + cadence: `transaction { prepare(acct: AuthAccount) {} }`, + proposer: authz, + payer: authz, + authorizations: [authz] +}); +``` + +## Parameters + +### `addr` + + +- Type: `string` +- Description: The address of the account that will sign the transaction + +### `signingFunction` + + +- Type: +```typescript +type SigningFn = ( + signable?: SignableMessage +) => SigningResult | Promise +``` +- Description: A function that produces signatures for the account + +### `keyId` (optional) + + +- Type: `string | number` +- Description: The index of the key to use for signing (optional) + +### `sequenceNum` (optional) + + +- Type: `number` +- Description: The sequence number for the account key (optional) + + +## Returns + +```typescript +Partial +``` + + +A partial interaction account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorizations.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorizations.md new file mode 100644 index 0000000000..d3a1913337 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/authorizations.md @@ -0,0 +1,106 @@ +--- +sidebar_position: 1 +title: "authorizations" +description: "authorizations function documentation." +--- + + + +# authorizations + +A utility builder to set the authorizations on a transaction. + +Authorizations define the accounts that are responsible for paying the transaction fees and providing signatures for the transaction. +You can have multiple authorizers in a single transaction (multi-signature transactions). + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.authorizations(ax) +``` + +Or import directly the specific function: + +```typescript +import { authorizations } from "@onflow/fcl-react-native" + +authorizations(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Single authorizer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Hello from: ".concat(acct.address.toString())) + } + } + `, + authorizations: [fcl.authz] // Current user authorization +}); + +// Multiple authorizers - both accounts must approve +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct1: AuthAccount, acct2: AuthAccount) { + log("Transaction signed by both accounts") + } + } + `, + authorizations: [userOneAuthz, userTwoAuthz] +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + acct.save("Hello, World!", to: /storage/greeting) + } + } + `, + fcl.authorizations([fcl.authz]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.limit(100) +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An array of authorization functions that produce account authorization details + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/block.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/block.md new file mode 100644 index 0000000000..6976150f0e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/block.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "block" +description: "block function documentation." +--- + + + +# block + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.block(blockQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { block } from "@onflow/fcl-react-native" + +block(blockQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest block +const latestBlock = await fcl.block(); // Get the latest finalized block +const latestSealedBlock = await fcl.block({sealed: true}); // Get the latest sealed block + +// Get block by ID (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get block at height (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode) +``` + +## Parameters + +### `blockQueryOptions` (optional) + + +- Type: +```typescript +interface BlockQueryOptions { + sealed?: boolean + height?: number + id?: string +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#block) + + +A promise that resolves to a Block object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/build.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/build.md new file mode 100644 index 0000000000..546d2cc75a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/build.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "build" +description: "build function documentation." +--- + + + +# build + +A builder function that creates an interaction from an array of builder functions. + +The build function takes an array of builder functions and applies them to create a complete interaction object. This is the foundation for constructing all interactions in Flow, whether they're scripts, transactions, or queries. + +Each builder function modifies specific parts of the interaction object, such as adding Cadence code, arguments, authorization details, or other configuration. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.build(fns) +``` + +Or import directly the specific function: + +```typescript +import { build } from "@onflow/fcl-react-native" + +build(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Build a script interaction +const scriptInteraction = await fcl.build([ + fcl.script` + access(all) fun main(a: Int, b: Int): Int { + return a + b + } + `, + fcl.args([ + fcl.arg(1, fcl.t.Int), + fcl.arg(2, fcl.t.Int) + ]) +]); + +// Build a transaction interaction +const txInteraction = await fcl.build([ + fcl.transaction` + transaction(name: String) { + prepare(account: AuthAccount) { + log("Hello, " + name) + } + } + `, + fcl.args([fcl.arg("World", fcl.t.String)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `fns` (optional) + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: The functions to apply to the interaction + + +## Returns + +[`Promise`](../types#interaction) + + +A promise of an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cadence.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cadence.md new file mode 100644 index 0000000000..227866dbf5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cadence.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cadence" +description: "cadence function documentation." +--- + + + +# cadence + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.cadence(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cadence } from "@onflow/fcl-react-native" + +cadence(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cdc.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cdc.md new file mode 100644 index 0000000000..8945be22b4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/cdc.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cdc" +description: "cdc function documentation." +--- + + + +# cdc + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.cdc(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cdc } from "@onflow/fcl-react-native" + +cdc(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/config.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/config.md new file mode 100644 index 0000000000..f948182892 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/config.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "config" +description: "config function documentation." +--- + + + +# config + +Sets the config + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.config(values) +``` + +Or import directly the specific function: + +```typescript +import { config } from "@onflow/fcl-react-native" + +config(values) +``` + + +## Parameters + +### `values` (optional) + + +- Type: +```typescript +Record +``` +- Description: - The values to set + + +## Returns + +```typescript +{ put: typeof put; get: typeof get; all: typeof all; first: typeof first; update: typeof update; delete: typeof _delete; where: typeof where; subscribe: typeof subscribe; overload: typeof overload; load: typeof load; } +``` + + +The config object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/createSignableVoucher.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/createSignableVoucher.md new file mode 100644 index 0000000000..53e99f98ca --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/createSignableVoucher.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "createSignableVoucher" +description: "createSignableVoucher function documentation." +--- + + + +# createSignableVoucher + +Creates a signable voucher object from an interaction for signing purposes. + +A voucher is a standardized representation of a transaction that contains all the necessary +information for signing and submitting to the Flow network. This function transforms an +interaction object into a voucher format. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.createSignableVoucher(ix) +``` + +Or import directly the specific function: + +```typescript +import { createSignableVoucher } from "@onflow/fcl-react-native" + +createSignableVoucher(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { createSignableVoucher } from "@onflow/sdk" + +// Build a transaction interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); + +// Create a voucher for signing +const voucher = createSignableVoucher(interaction); +console.log(voucher.cadence); // The Cadence script +console.log(voucher.arguments); // The transaction arguments +console.log(voucher.proposalKey); // Proposer account details +console.log(voucher.authorizers); // List of authorizer addresses + +// The voucher can now be signed and submitted +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing transaction details + + +## Returns + +```typescript +{ cadence: string; refBlock: string; computeLimit: number; arguments: any[]; proposalKey: { address: string; keyId: string | number; sequenceNum: number; } | { address?: undefined; keyId?: undefined; sequenceNum?: undefined; }; payer: string; authorizers: string[]; payloadSigs: { address: string; keyId: string | number; sig: string; }[]; envelopeSigs: { address: string; keyId: string | number; sig: string; }[]; } +``` + + +A voucher object containing all transaction data and signatures + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/decode.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/decode.md new file mode 100644 index 0000000000..0e863ac24e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/decode.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "decode" +description: "decode function documentation." +--- + + + +# decode + +Decodes the response from 'fcl.send()' into the appropriate JSON representation of any values returned from Cadence code. + +The response from Flow contains encoded values that need to be decoded into JavaScript types. This function handles that conversion, including complex types like structs, arrays, and dictionaries. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.decode(response) +``` + +Or import directly the specific function: + +```typescript +import { decode } from "@onflow/fcl-react-native" + +decode(response) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple script to add 2 numbers +const response = await fcl.send([ + fcl.script` + access(all) 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); +console.log(decoded); // 3 +console.log(typeof decoded); // "number" + +// Complex return types +const complexResponse = await fcl.send([ + fcl.script` + access(all) fun main(): {String: Int} { + return {"foo": 1, "bar": 2} + } + ` +]); + +const complexDecoded = await fcl.decode(complexResponse); +console.log(complexDecoded); // {foo: 1, bar: 2} +``` + +## Parameters + +### `response` + + +- Type: `any` +- Description: Should be the response returned from 'fcl.send([...])' + + +## Returns + +`Promise` + + +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. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/display.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/display.md new file mode 100644 index 0000000000..6d7007ee4b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/display.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "display" +description: "display function documentation." +--- + + + +# display + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.display(address) +``` + +Or import directly the specific function: + +```typescript +import { display } from "@onflow/fcl-react-native" + +display(address) +``` + + +## Parameters + +### `address` + + +- Type: `string` +- Description: - Flow address + + +## Returns + +`string` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/events.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/events.md new file mode 100644 index 0000000000..3f3eec94cd --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/events.md @@ -0,0 +1,99 @@ +--- +sidebar_position: 1 +title: "events" +description: "events function documentation." +--- + + + +# events + +Subscribes to Flow blockchain events in real-time. This function provides a way to listen +for specific events emitted by smart contracts on the Flow blockchain. It automatically handles +fallback to legacy polling for environments that don't support WebSocket subscriptions. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.events(filterOrType) +``` + +Or import directly the specific function: + +```typescript +import { events } from "@onflow/fcl-react-native" + +events(filterOrType) +``` + +## Usage + +```typescript +// Subscribe to a specific event type +import * as fcl from "@onflow/fcl" + +const unsubscribe = fcl.events("A.0x1654653399040a61.FlowToken.TokensWithdrawn") + .subscribe((event) => { + console.log("Event received:", event) + console.log("Event data:", event.data) + console.log("Transaction ID:", event.transactionId) + }) + +// Stop listening after 30 seconds +setTimeout(() => { + unsubscribe() +}, 30000) + +// Subscribe to multiple event types with error handling +const unsubscribe = fcl.events({ + eventTypes: [ + "A.0x1654653399040a61.FlowToken.TokensWithdrawn", + "A.0x1654653399040a61.FlowToken.TokensDeposited" + ] +}).subscribe( + (event) => { + console.log("Token event:", event.type, event.data) + }, + (error) => { + console.error("Event subscription error:", error) + } +) + +// Subscribe to events starting from a specific block height +const unsubscribe = fcl.events({ + eventTypes: ["A.CONTRACT.EVENT"], + startBlockHeight: 12345678 +}).subscribe((event) => { + console.log("Historical and new events:", event) +}) +``` + +## Parameters + +### `filterOrType` (optional) + + +- Type: `string` | [`EventFilter`](../types#eventfilter) +- Description: Event filter object or event type string. +If a string is provided, it will be treated as a single event type to subscribe to. +If an EventFilter object is provided, it can contain multiple event types and other filter criteria. + + +## Returns + +```typescript +{ subscribe: (onData: (event: Event) => void, onError?: (error: Error) => void) => () => void; } +``` + + +An object containing a subscribe method +• returns.subscribe Function to start the subscription +• returns.subscribe.onData Callback function called when an event is received +• returns.subscribe.onError Optional callback function called when an error occurs +• returns.subscribe.unsubscribe Function returned by subscribe() to stop the subscription + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getAccount.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getAccount.md new file mode 100644 index 0000000000..8e33ec2292 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getAccount.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getAccount" +description: "getAccount function documentation." +--- + + + +# 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. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getAccount(addr) +``` + +Or import directly the specific function: + +```typescript +import { getAccount } from "@onflow/fcl-react-native" + +getAccount(addr) +``` + +## Usage + +```typescript +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; +}; +``` + +## Parameters + +### `addr` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlock.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlock.md new file mode 100644 index 0000000000..ed78c9bae9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlock.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getBlock" +description: "getBlock function documentation." +--- + + + +# 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.block(options)' if you do not need to pair with any other builders. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getBlock(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlock } from "@onflow/fcl-react-native" + +getBlock(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const latestSealedBlock = await fcl.send([ + fcl.getBlock(true) // isSealed = true +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: If the latest block should be sealed or not. See block states + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlockHeader.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlockHeader.md new file mode 100644 index 0000000000..a341bbc019 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getBlockHeader.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getBlockHeader" +description: "getBlockHeader function documentation." +--- + + + +# getBlockHeader + +A builder function that returns the interaction to get a block header. + +A block header contains metadata about a block without the full transaction details, making it more +lightweight than fetching the entire block. This is useful when you only need block metadata like +timestamp, height, parent hash, etc. + +Use with 'fcl.atBlockId()' and 'fcl.atBlockHeight()' when building the interaction to get headers for specific blocks. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getBlockHeader(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlockHeader } from "@onflow/fcl-react-native" + +getBlockHeader(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest sealed block header +const sealedHeader = await fcl.send([ + fcl.getBlockHeader(true) +]).then(fcl.decode); + +console.log("Block height:", sealedHeader.height); +console.log("Block timestamp:", sealedHeader.timestamp); +console.log("Parent block ID:", sealedHeader.parentId); + +// Get header for specific block +const blockHeader = await fcl.send([ + fcl.getBlockHeader(), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Get latest finalized block header +const finalizedHeader = await fcl.send([ + fcl.getBlockHeader(false) +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: Block finality state, true for sealed blocks, false for finalized blocks, null for latest + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getChainId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getChainId.md new file mode 100644 index 0000000000..309857d40b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getChainId.md @@ -0,0 +1,64 @@ +--- +sidebar_position: 1 +title: "getChainId" +description: "getChainId function documentation." +--- + + + +# getChainId + +Gets the chain ID if its set, otherwise gets the chain ID from the access node + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getChainId(opts) +``` + +Or import directly the specific function: + +```typescript +import { getChainId } from "@onflow/fcl-react-native" + +getChainId(opts) +``` + +## Usage + +```typescript +// Get chain ID using configured access node +import * as fcl from "@onflow/fcl" + +const chainId = await fcl.getChainId() +console.log("Connected to:", chainId) // "testnet" or "mainnet" +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface GetChainIdOptions { + node?: unknown + enableRequestLogging?: boolean + [key: string]: any +} +``` +- Description: Optional configuration parameters + + +## Returns + +`Promise` + + +Promise that resolves to the chain ID string (e.g., "mainnet", "testnet", "local") + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getCollection.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getCollection.md new file mode 100644 index 0000000000..2fc75ac056 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getCollection.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "getCollection" +description: "getCollection function documentation." +--- + + + +# getCollection + +A builder function that returns a collection containing a list of transaction IDs by its collection ID. + +A collection is a batch of transactions that have been included in a block. Each collection has a unique ID +which is the SHA3-256 hash of the collection payload. Collections are used to group related transactions +together for more efficient processing by the network. + +The collection ID provided must be from the current spork. Collections from past sporks are currently unavailable. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getCollection(id) +``` + +Or import directly the specific function: + +```typescript +import { getCollection } from "@onflow/fcl-react-native" + +getCollection(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get a collection and see what transactions it contains +const collection = await fcl.send([ + fcl.getCollection("cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5") +]).then(fcl.decode); + +console.log("Collection ID:", collection.id); +console.log("Transaction IDs:", collection.transactionIds); +console.log("Total transactions:", collection.transactionIds.length); + +// Process each transaction in the collection +for (const txId of collection.transactionIds) { + const transaction = await fcl.send([ + fcl.getTransaction(txId) + ]).then(fcl.decode); + console.log("Transaction:", transaction); +} +``` + +## Parameters + +### `id` (optional) + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEvents.md new file mode 100644 index 0000000000..8b936dcbb5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEvents.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getEvents" +description: "getEvents function documentation." +--- + + + +# getEvents + +A builder function that returns the interaction to get events. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened during execution. +This function queries for events of a specific type within a range of block heights. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getEvents(eventType, start, end) +``` + +Or import directly the specific function: + +```typescript +import { getEvents } from "@onflow/fcl-react-native" + +getEvents(eventType, start, end) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get FlowToken transfer events from blocks 1000 to 2000 +const events = await fcl.send([ + fcl.getEvents("A.1654653399040a61.FlowToken.TokensDeposited", 1000, 2000) +]).then(fcl.decode); + +console.log("Found events:", events.length); +events.forEach(event => { + console.log("Event data:", event.data); + console.log("Transaction ID:", event.transactionId); +}); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get (e.g., "A.1654653399040a61.FlowToken.TokensWithdrawn") + +### `start` + + +- Type: `number` +- Description: The start block height to query from + +### `end` + + +- Type: `number` +- Description: The end block height to query to + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockHeightRange.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockHeightRange.md new file mode 100644 index 0000000000..21b6c8e8df --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockHeightRange.md @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockHeightRange" +description: "getEventsAtBlockHeightRange function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +Block height range expresses the height of the start and end block in the chain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockHeightRange } from "@onflow/fcl-react-native" + +getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get events at block height range +await fcl + .send([ + fcl.getEventsAtBlockHeightRange( + "A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name + 35580624, // block to start looking for events at + 35580624 // block to stop looking for events at + ), + ]) + .then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `startHeight` + + +- Type: `number` +- Description: The height of the block to start looking for events (inclusive) + +### `endHeight` + + +- Type: `number` +- Description: The height of the block to stop looking for events (inclusive) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockIds.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockIds.md new file mode 100644 index 0000000000..30268e0e38 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getEventsAtBlockIds.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockIds" +description: "getEventsAtBlockIds function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getEventsAtBlockIds(eventType, blockIds) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockIds } from "@onflow/fcl-react-native" + +getEventsAtBlockIds(eventType, blockIds) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const events = await fcl.send([ + fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [ + "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7", + "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f" + ]) +]).then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `blockIds` + + +- Type: `string[]` +- Description: The ids of the blocks to scan for events + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNetworkParameters.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNetworkParameters.md new file mode 100644 index 0000000000..d55b833edf --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNetworkParameters.md @@ -0,0 +1,68 @@ +--- +sidebar_position: 1 +title: "getNetworkParameters" +description: "getNetworkParameters function documentation." +--- + + + +# getNetworkParameters + +A builder function that returns the interaction to get network parameters. + +Network parameters contain important configuration information about the Flow network, +including the chain ID, which is essential for signing transactions correctly. +This information is crucial for ensuring transactions are submitted to the correct network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getNetworkParameters() +``` + +Or import directly the specific function: + +```typescript +import { getNetworkParameters } from "@onflow/fcl-react-native" + +getNetworkParameters() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get network parameters to verify chain ID +const params = await fcl.send([ + fcl.getNetworkParameters() +]).then(fcl.decode); + +console.log("Chain ID:", params.chainId); +console.log("Network:", params.name); + +// Use this to verify you're connected to the right network +if (params.chainId === "flow-mainnet") { + console.log("Connected to Flow Mainnet"); +} else if (params.chainId === "flow-testnet") { + console.log("Connected to Flow Testnet"); +} +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNodeVersionInfo.md new file mode 100644 index 0000000000..0ba766bb8e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getNodeVersionInfo.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getNodeVersionInfo" +description: "getNodeVersionInfo function documentation." +--- + + + +# getNodeVersionInfo + +A builder function for the Get Node Version Info interaction. + +Creates an interaction to retrieve version information from the connected Flow Access Node. +This includes details about the node's software version, protocol version, and spork information. + +Consider using the pre-built interaction 'fcl.nodeVersionInfo()' if you do not need to pair with any other builders. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getNodeVersionInfo() +``` + +Or import directly the specific function: + +```typescript +import { getNodeVersionInfo } from "@onflow/fcl-react-native" + +getNodeVersionInfo() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information using builder +const versionInfo = await fcl.send([ + fcl.getNodeVersionInfo() +]).then(fcl.decode); + +console.log("Node version:", versionInfo.semver); +console.log("Protocol version:", versionInfo.protocol_version); +console.log("Spork ID:", versionInfo.spork_id); + +// Use with other builders if needed +const interaction = await fcl.build([ + fcl.getNodeVersionInfo() + // other builders can be added here +]); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransaction.md new file mode 100644 index 0000000000..50fc2f136e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransaction.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getTransaction" +description: "getTransaction function documentation." +--- + + + +# getTransaction + +A builder function that returns the interaction to get a transaction by id. + +Transaction id is a hash of the encoded transaction payload and can be calculated before submitting the transaction to the network. +Transaction status represents the state of a transaction in the blockchain. Status can change until it is finalized. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id).onceExecuted()' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getTransaction(id) +``` + +Or import directly the specific function: + +```typescript +import { getTransaction } from "@onflow/fcl-react-native" + +getTransaction(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const tx = await fcl.send([ + fcl.getTransaction("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransactionStatus.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransactionStatus.md new file mode 100644 index 0000000000..a265bdc02f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/getTransactionStatus.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "getTransactionStatus" +description: "getTransactionStatus function documentation." +--- + + + +# getTransactionStatus + +A builder function that returns the status of transaction. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id)' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.getTransactionStatus(transactionId) +``` + +Or import directly the specific function: + +```typescript +import { getTransactionStatus } from "@onflow/fcl-react-native" + +getTransactionStatus(transactionId) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const status = await fcl.send([ + fcl.getTransactionStatus("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The id of the transaction to get the status of + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/index.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/index.md new file mode 100644 index 0000000000..d480f40b08 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/index.md @@ -0,0 +1,296 @@ +--- +sidebar_position: 1 +title: "@onflow/fcl-react-native" +description: "React Native JavaScript/TypeScript library for building mobile applications on the Flow blockchain." +--- + + + +# @onflow/fcl-react-native + +## Overview + +The Flow fcl-react-native library provides a set of tools for developers to build applications on the Flow blockchain. + +## Installation + +You can install the @onflow/fcl-react-native package using npm or yarn: + +```bash +npm install @onflow/fcl-react-native +``` + +Or using yarn: + +```bash +yarn add @onflow/fcl-react-native +``` + +### Requirements + +- Node.js 14.x or later + +### Importing + +You can import the entire package: + +```typescript +import * as fcl from "@onflow/fcl-react-native" +``` + +Or import specific functions: + +```typescript +import { functionName } from "@onflow/fcl-react-native" +``` + +## 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. + +```javascript +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. + +```javascript +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 + +| 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](https://developers.onflow.org/http-api/). | +| `app.detail.title` | `Cryptokitties` | Your applications title, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.icon` | `https://fcl-discovery.onflow.org/images/blocto.png` | Url for your applications icon, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.description` | `Cryptokitties is a blockchain game` | Your applications description, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.url` | `https://cryptokitties.co` | Your applications url, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `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. | +| `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`, `testnet`, `mainnet`. | +| `walletconnect.projectId` | `YOUR_PROJECT_ID` | Your app's WalletConnect project ID. See [WalletConnect Cloud](https://cloud.walletconnect.com/sign-in) to obtain a project ID for your application. | +| `walletconnect.disableNotifications` | `false` | Optional flag to disable pending WalletConnect request notifications within the application's UI. | + +## Using Contracts in Scripts and Transactions + +### Address Replacement + +Configuration keys that start with `0x` will be replaced in FCL scripts and transactions, this allows you to write your script or transaction Cadence code once and not have to change it when you point your application at a difference instance of the Flow Blockchain. + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl.config().put('0xFungibleToken', '0xf233dcee88fe0abe'); + +async function myScript() { + return fcl + .send([ + fcl.script` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + access(all) fun main() { /* Rest of the script goes here */ } + `, + ]) + .then(fcl.decode); +} + +async function myTransaction() { + return fcl + .send([ + fcl.transaction` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + transaction { /* Rest of the transaction goes here */ } + `, + ]) + .then(fcl.decode); +} +``` + +#### Example + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl + .config() + .put('flow.network', 'testnet') + .put('walletconnect.projectId', 'YOUR_PROJECT_ID') + .put('accessNode.api', 'https://rest-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('app.detail.description', 'A test harness for FCL') + .put('app.detail.url', 'https://myapp.com') + .put('service.OpenID.scopes', 'email email_verified name zoneinfo') + .put('0xFlowToken', '0x7e60df042a9c0868'); +``` + +### Using `flow.json` for Contract Imports + +A simpler and more flexible way to manage contract imports in scripts and transactions is by using the `config.load` method in FCL. This lets you load contract configurations from a `flow.json` file, keeping your import syntax clean and allowing FCL to pick the correct contract addresses based on the network you're using. + +#### 1. Define Your Contracts in `flow.json` + +Here’s an example of a `flow.json` file with aliases for multiple networks: + +```json +{ + "contracts": { + "HelloWorld": { + "source": "./cadence/contracts/HelloWorld.cdc", + "aliases": { + "testnet": "0x1cf0e2f2f715450", + "mainnet": "0xf8d6e0586b0a20c7" + } + } + } +} +``` + +- **`source`**: Points to the contract file in your project. +- **`aliases`**: Maps each network to the correct contract address. + +#### 2. Configure FCL + +Load the `flow.json` file and set up FCL to use it: + +```javascript +import { config } from '@onflow/fcl'; +import flowJSON from '../flow.json'; + +config({ + 'flow.network': 'testnet', // Choose your network, e.g., testnet or mainnet + 'accessNode.api': 'https://rest-testnet.onflow.org', // Access node for the network + 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`, // Wallet discovery +}).load({ flowJSON }); +``` + +With this setup, FCL will automatically use the correct contract address based on the selected network (e.g., `testnet` or `mainnet`). + +#### 3. Use Contract Names in Scripts and Transactions + +After setting up `flow.json`, you can import contracts by name in your Cadence scripts or transactions: + +```cadence +import "HelloWorld" + +access(all) fun main(): String { + return HelloWorld.sayHello() +} +``` + +FCL replaces `"HelloWorld"` with the correct address from the `flow.json` configuration. + +> **Note**: Don’t store private keys in your `flow.json`. Instead, keep sensitive keys in a separate, `.gitignore`-protected file. + +## API Reference + +This section contains documentation for all of the functions and namespaces in the fcl-react-native package. + +- [account](./account.md) - Retrieve any account from Flow network's latest block or from a specified block... +- [arg](./arg.md) - A utility builder to be used with fcl.args[...] to create FCL supported... +- [args](./args.md) - A utility builder to be used with other builders to pass in arguments with a... +- [atBlockHeight](./atBlockHeight.md) - A builder function that returns a partial interaction to a block at a specific... +- [atBlockId](./atBlockId.md) - A builder function that returns a partial interaction to a block at a specific... +- [authenticate](./authenticate.md) +- [authorization](./authorization.md) - Creates an authorization function for use in transactions. An authorization... +- [authorizations](./authorizations.md) - A utility builder to set the authorizations on a transaction. Authorizations... +- [block](./block.md) - Query the network for block by id, height or get the latest block. Block ID is... +- [build](./build.md) - A builder function that creates an interaction from an array of builder... +- [cadence](./cadence.md) - Creates a template function +- [cdc](./cdc.md) - Creates a template function +- [config](./config.md) - Sets the config +- [createSignableVoucher](./createSignableVoucher.md) - Creates a signable voucher object from an interaction for signing purposes. A... +- [decode](./decode.md) - Decodes the response from 'fcl.send()' into the appropriate JSON representation... +- [display](./display.md) - Adds 0x to address if not already present +- [events](./events.md) - Subscribes to Flow blockchain events in real-time. This function provides a way... +- [getAccount](./getAccount.md) - A builder function that returns the interaction to get an account by address.... +- [getBlock](./getBlock.md) - A builder function that returns the interaction to get the latest block. Use... +- [getBlockHeader](./getBlockHeader.md) - A builder function that returns the interaction to get a block header. A block... +- [getChainId](./getChainId.md) - Gets the chain ID if its set, otherwise gets the chain ID from the access node +- [getCollection](./getCollection.md) - A builder function that returns a collection containing a list of transaction... +- [getEvents](./getEvents.md) - A builder function that returns the interaction to get events. Events are... +- [getEventsAtBlockHeightRange](./getEventsAtBlockHeightRange.md) - A builder function that returns all instances of a particular event (by name)... +- [getEventsAtBlockIds](./getEventsAtBlockIds.md) - A builder function that returns all instances of a particular event (by name)... +- [getNetworkParameters](./getNetworkParameters.md) - A builder function that returns the interaction to get network parameters.... +- [getNodeVersionInfo](./getNodeVersionInfo.md) - A builder function for the Get Node Version Info interaction. Creates an... +- [getTransaction](./getTransaction.md) - A builder function that returns the interaction to get a transaction by id.... +- [getTransactionStatus](./getTransactionStatus.md) - A builder function that returns the status of transaction. The transaction id... +- [invariant](./invariant.md) +- [isBad](./isBad.md) - Checks if an interaction has a failed status. +- [isOk](./isOk.md) - Checks if an interaction has a successful status. +- [limit](./limit.md) - A utility builder to set the compute limit on a transaction. The compute limit... +- [logIn](./logIn.md) +- [nodeVersionInfo](./nodeVersionInfo.md) - Retrieve version information from the connected Flow Access Node. This function... +- [param](./param.md) - Legacy function for setting a single parameter on an interaction. +- [params](./params.md) - Legacy function for setting parameters on an interaction. +- [payer](./payer.md) - A builder function that adds payer account(s) to a transaction. Every... +- [ping](./ping.md) - A builder function that creates a ping interaction to test connectivity to the... +- [pipe](./pipe.md) - Async pipe function to compose interactions. The pipe function is the foundation... +- [pluginRegistry](./pluginRegistry.md) - Global plugin registry instance for managing FCL plugins. This registry handles... +- [proposer](./proposer.md) - A builder function that adds the proposer to a transaction. The proposer is... +- [query](./query.md) - Allows you to submit scripts to query the blockchain. +- [reauthenticate](./reauthenticate.md) +- [ref](./ref.md) - A builder function that sets the reference block for a transaction. The... +- [sansPrefix](./sansPrefix.md) - Removes 0x from address if present +- [script](./script.md) - A builder function that creates a script interaction. Scripts allow you to write... +- [send](./send.md) - Sends arbitrary scripts, transactions, and requests to Flow. This method... +- [serialize](./serialize.md) - Serializes a Flow transaction or script to a JSON-formatted signable voucher... +- [ServiceDiscovery](./serviceDiscovery.md) (namespace) - Namespace containing ServiceDiscovery utilities +- [signUp](./signUp.md) +- [subscribe](./subscribe.md) - Subscribe to real-time data from the Flow blockchain and automatically decode... +- [subscribeEvents](./subscribeEvents.md) - Subscribe to events with the given filter and parameters. Creates a subscription... +- [subscribeRaw](./subscribeRaw.md) - Subscribe to a topic without decoding the data. This function creates a raw... +- [transaction](./transaction.md) - A template builder to use a Cadence transaction for an interaction. FCL "mutate"... +- [tx](./tx.md) - Creates a transaction monitor that provides methods for tracking and subscribing... +- [unauthenticate](./unauthenticate.md) +- [useServiceDiscovery](./useServiceDiscovery.md) (namespace) - Namespace containing useServiceDiscovery utilities +- [useServiceDiscovery.getAsyncStorage](./useServiceDiscovery.md#getAsyncStorage) +- [validator](./validator.md) - A builder function that adds a validator to a transaction. Validators are... +- [verifyUserSignatures](./verifyUserSignatures.md) - Verify a valid signature/s for an account on Flow. +- [voucherIntercept](./voucherIntercept.md) - A builder function that intercepts and modifies a voucher. This function is... +- [voucherToTxId](./voucherToTxId.md) - Converts a voucher object to a transaction ID. This function computes the... +- [why](./why.md) - Returns the reason for an interaction failure. +- [withPrefix](./withPrefix.md) - Adds 0x to address if not already present + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/invariant.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/invariant.md new file mode 100644 index 0000000000..e24e20bec0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/invariant.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +title: "invariant" +description: "invariant function documentation." +--- + + + +# invariant + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.invariant(args) +``` + +Or import directly the specific function: + +```typescript +import { invariant } from "@onflow/fcl-react-native" + +invariant(args) +``` + + +## Parameters + +### `args` (optional) + + +- Type: `any[]` + + +## Returns + +```typescript +(ix: any) => any +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isBad.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isBad.md new file mode 100644 index 0000000000..95cf9429be --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isBad.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 1 +title: "isBad" +description: "isBad function documentation." +--- + + + +# isBad + +Checks if an interaction has a failed status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.isBad(ix) +``` + +Or import directly the specific function: + +```typescript +import { isBad } from "@onflow/fcl-react-native" + +isBad(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isBad, why } from "@onflow/sdk" + +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isBad(response)) { + console.log("Transaction failed:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is BAD, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isOk.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isOk.md new file mode 100644 index 0000000000..8931eb2bbe --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/isOk.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "isOk" +description: "isOk function documentation." +--- + + + +# isOk + +Checks if an interaction has a successful status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.isOk(ix) +``` + +Or import directly the specific function: + +```typescript +import { isOk } from "@onflow/fcl-react-native" + +isOk(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isOk } from "@onflow/sdk" + +// Check if a transaction was successful +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isOk(response)) { + console.log("Transaction was successful"); +} else { + console.log("Transaction failed"); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is OK, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/limit.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/limit.md new file mode 100644 index 0000000000..4324fdb800 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/limit.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "limit" +description: "limit function documentation." +--- + + + +# limit + +A utility builder to set the compute limit on a transaction. + +The compute limit is the maximum amount of computation that can be performed during transaction execution. +Setting an appropriate compute limit helps prevent infinite loops and ensures predictable transaction costs. + +Read more about [computation cost](https://docs.onflow.org/concepts/fees/#computation-cost) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.limit(limit) +``` + +Or import directly the specific function: + +```typescript +import { limit } from "@onflow/fcl-react-native" + +limit(limit) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + // Complex transaction logic here + } + } + `, + limit: 1000 // Set compute limit to 1000 +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.limit(9999) // Set higher limit for complex operations +]); +``` + +## Parameters + +### `limit` + + +- Type: `number` +- Description: The maximum amount of computation for the transaction + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/logIn.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/logIn.md new file mode 100644 index 0000000000..2faff9c810 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/logIn.md @@ -0,0 +1,44 @@ +--- +sidebar_position: 1 +title: "logIn" +description: "logIn function documentation." +--- + + + +# logIn + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.logIn(opts) +``` + +Or import directly the specific function: + +```typescript +import { logIn } from "@onflow/fcl-react-native" + +logIn(opts) +``` + + +## Parameters + +### `opts` (optional) + + +- Type: `{}` + + +## Returns + +[`Promise`](../types#currentuser) + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/nodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/nodeVersionInfo.md new file mode 100644 index 0000000000..789336a08d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/nodeVersionInfo.md @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +title: "nodeVersionInfo" +description: "nodeVersionInfo function documentation." +--- + + + +# nodeVersionInfo + +Retrieve version information from the connected Flow Access Node. + +This function returns detailed information about the Flow node's version, including the protocol version, spork information, and node-specific details. This is useful for debugging, compatibility checks, and understanding the network state. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.nodeVersionInfo(opts) +``` + +Or import directly the specific function: + +```typescript +import { nodeVersionInfo } from "@onflow/fcl-react-native" + +nodeVersionInfo(opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information +const versionInfo = await fcl.nodeVersionInfo(); +console.log(versionInfo); +// { +// semver: "v0.37.13", +// commit: "12345abcd", +// spork_id: "mainnet-23", +// protocol_version: "2.13.10", +// spork_root_block_height: "88483760", +// node_root_block_height: "88483760" +// } + +// Check compatibility +const info = await fcl.nodeVersionInfo(); +if (info.protocol_version.startsWith("2.13")) { + console.log("Compatible with current protocol version"); +} +``` + +## Parameters + +### `opts` (optional) + + +- Type: `any` +- Description: Optional parameters for the request + + +## Returns + +[`Promise`](../types#nodeversioninfo) + + +A promise that resolves to a block response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/param.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/param.md new file mode 100644 index 0000000000..ebed49b6c4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/param.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "param" +description: "param function documentation." +--- + + + +# param + +Legacy function for setting a single parameter on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.param(params) +``` + +Or import directly the specific function: + +```typescript +import { param } from "@onflow/fcl-react-native" + +param(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameter to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/params.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/params.md new file mode 100644 index 0000000000..4d44a84797 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/params.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "params" +description: "params function documentation." +--- + + + +# params + +Legacy function for setting parameters on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.params(params) +``` + +Or import directly the specific function: + +```typescript +import { params } from "@onflow/fcl-react-native" + +params(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameters to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/payer.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/payer.md new file mode 100644 index 0000000000..489d4fe2e2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/payer.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "payer" +description: "payer function documentation." +--- + + + +# payer + +A builder function that adds payer account(s) to a transaction. + +Every transaction requires at least one payer. + +The payer is the account that pays the transaction fee for executing the transaction on the network. +The payer account must have sufficient Flow tokens to cover the transaction fees. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#payer) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.payer(ax) +``` + +Or import directly the specific function: + +```typescript +import { payer } from "@onflow/fcl-react-native" + +payer(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using current user as payer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Transaction fees paid by: ".concat(acct.address.toString())) + } + } + `, + payer: fcl.authz // Current user as payer +}); + +// Using custom payer with builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.proposer(fcl.authz), // Current user as proposer + fcl.authorizations([fcl.authz]), // Current user as authorizer + fcl.payer(customPayerAuthz) // Custom payer pays fees +]); + +// Multiple payers (advanced use case) +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.payer([payerAuthz1, payerAuthz2]) // Multiple payers split fees +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An account address or an array of account addresses + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that takes an interaction object and returns a new interaction object with the payer(s) added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ping.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ping.md new file mode 100644 index 0000000000..2dd1559a13 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ping.md @@ -0,0 +1,72 @@ +--- +sidebar_position: 1 +title: "ping" +description: "ping function documentation." +--- + + + +# ping + +A builder function that creates a ping interaction to test connectivity to the Flow Access Node. + +The ping interaction is a simple way to test if the Flow Access Node is reachable and responding. This is useful for health checks, connectivity testing, and debugging network issues. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.ping() +``` + +Or import directly the specific function: + +```typescript +import { ping } from "@onflow/fcl-react-native" + +ping() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple ping to test connectivity +try { + const response = await fcl.send([fcl.ping()]); + console.log("Access Node is reachable"); +} catch (error) { + console.error("Access Node is not reachable:", error); +} + +// Use ping for health checks +const healthCheck = async () => { + try { + await fcl.send([fcl.ping()]); + return { status: "healthy", timestamp: new Date().toISOString() }; + } catch (error) { + return { status: "unhealthy", error: error.message, timestamp: new Date().toISOString() }; + } +}; + +const health = await healthCheck(); +console.log("Health status:", health); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pipe.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pipe.md new file mode 100644 index 0000000000..109b83df7f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pipe.md @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +title: "pipe" +description: "pipe function documentation." +--- + + + +# pipe + +Async pipe function to compose interactions. + +The pipe function is the foundation for composing multiple interaction builder functions together. +It sequentially applies builder functions to an interaction, allowing for complex interaction construction. +Each function in the pipe receives the result of the previous function and can modify or validate the interaction. + +Pipe has two main forms: +1. `pipe(builderFunctions)`: Returns a builder function +2. `pipe(interaction, builderFunctions)`: Directly executes the pipe on an interaction + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.pipe(fns) +``` + +Or import directly the specific function: + +```typescript +import { pipe } from "@onflow/fcl-react-native" + +pipe(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using pipe to create a reusable builder +const myTransactionBuilder = fcl.pipe([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Use the builder +const interaction = await fcl.build([myTransactionBuilder]); + +// Pipe is used internally by build() and send() +await fcl.send([ + fcl.script`access(all) fun main(): Int { return 42 }` +]); // This uses pipe internally +``` + +## Parameters + +### `fns` + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: Array of builder functions to apply + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +An interaction builder function when called with just functions, or a Promise<Interaction> when called with an interaction and functions + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pluginRegistry.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pluginRegistry.md new file mode 100644 index 0000000000..d30e727ca4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/pluginRegistry.md @@ -0,0 +1,54 @@ +--- +sidebar_position: 1 +title: "pluginRegistry" +description: "pluginRegistry function documentation." +--- + + + +# pluginRegistry + +Global plugin registry instance for managing FCL plugins. This registry handles +the registration and management of various FCL plugins including service plugins that add +new wallet services and strategies. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.pluginRegistry() +``` + +Or import directly the specific function: + +```typescript +import { pluginRegistry } from "@onflow/fcl-react-native" + +pluginRegistry() +``` + +## Usage + +```typescript +// Add a plugin to the registry +pluginRegistry.add({ + name: "MyWalletPlugin", + f_type: "ServicePlugin", + type: "discovery-service", + services: [...], + serviceStrategy: { method: "CUSTOM/RPC", exec: customExecFunction } +}) +``` + + +## Returns + +```typescript +Readonly<{ add: (plugins: any) => void; getPlugins: () => Map; }> +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/proposer.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/proposer.md new file mode 100644 index 0000000000..eec465199c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/proposer.md @@ -0,0 +1,94 @@ +--- +sidebar_position: 1 +title: "proposer" +description: "proposer function documentation." +--- + + + +# proposer + +A builder function that adds the proposer to a transaction. + +The proposer is responsible for providing the proposal key and paying the network fee for the transaction. +The proposer key is used to specify the sequence number and prevent replay attacks. + +Every transaction requires exactly one proposer. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#proposer) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.proposer(authz) +``` + +Or import directly the specific function: + +```typescript +import { proposer } from "@onflow/fcl-react-native" + +proposer(authz) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using the current user as proposer +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + log("Hello from proposer!") + } + } + `, + proposer: fcl.authz +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `authz` + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: The authorization object for the proposer + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction object and returns a new interaction object with the proposer added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/query.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/query.md new file mode 100644 index 0000000000..13d038cac7 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/query.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "query" +description: "query function documentation." +--- + + + +# query + +Allows you to submit scripts to query the blockchain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.query(opts) +``` + +Or import directly the specific function: + +```typescript +import { query } from "@onflow/fcl-react-native" + +query(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface QueryOptions { + cadence?: string + args?: ArgsFn + template?: any + isSealed?: boolean + limit?: number +} +``` +- Description: Query options configuration + + +## Returns + +`Promise` + + +A JSON representation of the response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/reauthenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/reauthenticate.md new file mode 100644 index 0000000000..ab7fc3da3f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/reauthenticate.md @@ -0,0 +1,44 @@ +--- +sidebar_position: 1 +title: "reauthenticate" +description: "reauthenticate function documentation." +--- + + + +# reauthenticate + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.reauthenticate(opts) +``` + +Or import directly the specific function: + +```typescript +import { reauthenticate } from "@onflow/fcl-react-native" + +reauthenticate(opts) +``` + + +## Parameters + +### `opts` (optional) + + +- Type: `{}` + + +## Returns + +[`Promise`](../types#currentuser) + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ref.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ref.md new file mode 100644 index 0000000000..85c0675a9d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/ref.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "ref" +description: "ref function documentation." +--- + + + +# ref + +A builder function that sets the reference block for a transaction. + +The 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.ref(refBlock) +``` + +Or import directly the specific function: + +```typescript +import { ref } from "@onflow/fcl-react-native" + +ref(refBlock) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Set specific reference block for transaction +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction with custom reference block") + } + } + `, + fcl.ref("a1b2c3d4e5f6789..."), // Custom reference block ID + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Usually, you don't need to set reference block manually +// as FCL will automatically set it to the latest block +``` + +## Parameters + +### `refBlock` + + +- Type: `string` +- Description: The reference block ID + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/sansPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/sansPrefix.md new file mode 100644 index 0000000000..ffec60dc33 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/sansPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "sansPrefix" +description: "sansPrefix function documentation." +--- + + + +# sansPrefix + +Removes 0x from address if present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.sansPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { sansPrefix } from "@onflow/fcl-react-native" + +sansPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address without 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/script.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/script.md new file mode 100644 index 0000000000..9bd275c654 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/script.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "script" +description: "script function documentation." +--- + + + +# script + +A builder function that creates a script interaction. Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. + +You can learn more about [Cadence here](https://cadence-lang.org/docs/language), 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.script(args) +``` + +Or import directly the specific function: + +```typescript +import { script } from "@onflow/fcl-react-native" + +script(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray | ((x?: unknown) => string), ...unknown[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/send.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/send.md new file mode 100644 index 0000000000..eea9225664 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/send.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "send" +description: "send function documentation." +--- + + + +# 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. + +WARNING: Must be used in conjunction with 'fcl.decode(response)' to get back correct keys and all values in JSON. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.send(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { send } from "@onflow/fcl-react-native" + +send(args, opts) +``` + +## Usage + +```typescript +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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +false | Function | (false | Function)[] +``` +- Description: An array of builders (functions that take an interaction object and return a new interaction object) + +### `opts` (optional) + + +- Type: `any` +- Description: Additional optional options for the request + + +## Returns + +`Promise` + + +A promise that resolves to a ResponseObject containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serialize.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serialize.md new file mode 100644 index 0000000000..7944c24e37 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serialize.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "serialize" +description: "serialize function documentation." +--- + + + +# serialize + +Serializes a Flow transaction or script to a JSON-formatted signable voucher that can be +used for offline signing or inspection. This is useful for creating signable transactions that can be +signed by external wallets or hardware devices. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.serialize(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { serialize } from "@onflow/fcl-react-native" + +serialize(args, opts) +``` + +## Usage + +```typescript +// Serialize a simple transaction +import * as fcl from "@onflow/fcl" + +const voucher = await fcl.serialize([ + fcl.transaction` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // Transaction logic here + } + } + `, + fcl.args([ + fcl.arg("10.0", fcl.t.UFix64), + fcl.arg("0x01", fcl.t.Address) + ]), + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]) +``` + +## Parameters + +### `args` + + +- Type: `(false` | `InteractionBuilderFn)[]` | [`Interaction`](../types#interaction) +- Description: Array of interaction builder functions or a pre-built interaction object. Builder functions are typically from + +### `opts` (optional) + + +- Type: +```typescript +export interface SerializeOptions { + resolve?: InteractionBuilderFn +} +``` +- Description: Optional configuration object + + +## Returns + +`Promise` + + +A JSON string representation of the signable voucher that contains all +the transaction details needed for signing + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serviceDiscovery.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serviceDiscovery.md new file mode 100644 index 0000000000..d435fa2bac --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/serviceDiscovery.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +title: "ServiceDiscovery" +description: "Namespace containing ServiceDiscovery utilities" +--- + + + +# ServiceDiscovery + +## Overview + +Namespace containing ServiceDiscovery utilities + +## Functions + +### getAsyncStorage + + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.ServiceDiscovery.getAsyncStorage() +``` + +Or import the namespace directly: + +```typescript +import { ServiceDiscovery } from "@onflow/fcl-react-native" + +ServiceDiscovery.getAsyncStorage() +``` + + +#### Returns + +```typescript +{ can: boolean; get: (key: string) => Promise; put: (key: string, value: any) => Promise; } +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/signUp.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/signUp.md new file mode 100644 index 0000000000..ec35d3c3b3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/signUp.md @@ -0,0 +1,44 @@ +--- +sidebar_position: 1 +title: "signUp" +description: "signUp function documentation." +--- + + + +# signUp + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.signUp(opts) +``` + +Or import directly the specific function: + +```typescript +import { signUp } from "@onflow/fcl-react-native" + +signUp(opts) +``` + + +## Parameters + +### `opts` (optional) + + +- Type: `{}` + + +## Returns + +[`Promise`](../types#currentuser) + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribe.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribe.md new file mode 100644 index 0000000000..bdb77b54c0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribe.md @@ -0,0 +1,101 @@ +--- +sidebar_position: 1 +title: "subscribe" +description: "subscribe function documentation." +--- + + + +# subscribe + +Subscribe to real-time data from the Flow blockchain and automatically decode the responses. + +This is a utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the 'decode' function. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.subscribe(subscribeParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribe } from "@onflow/fcl-react-native" + +subscribe(subscribeParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to events +const subscription = fcl.subscribe({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (events) => { + console.log("Received events:", events); + }, + onError: (error) => { + console.error("Subscription error:", error); + } +}); + +// Subscribe to blocks +const blockSubscription = fcl.subscribe({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (block) => { + console.log("New block:", block); + }, + onError: (error) => { + console.error("Block subscription error:", error); + } +}); + +// Later, to unsubscribe: +subscription.unsubscribe(); +blockSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeParams` + + +- Type: +```typescript +SubscribeParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +[`Subscription`](../types#subscription) + + +A subscription object that allows you to manage the subscription (e.g., to unsubscribe later) + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeEvents.md new file mode 100644 index 0000000000..a55320c668 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeEvents.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "subscribeEvents" +description: "subscribeEvents function documentation." +--- + + + +# subscribeEvents + +Subscribe to events with the given filter and parameters. + +Creates a subscription to listen for real-time events from the Flow blockchain. This function configures +the subscription parameters for filtering specific events based on type, addresses, contracts, and other criteria. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened. +Subscriptions allow you to listen for these events in real-time without polling. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.subscribeEvents(eventFilter) +``` + +Or import directly the specific function: + +```typescript +import { subscribeEvents } from "@onflow/fcl-react-native" + +subscribeEvents(eventFilter) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Subscribe to FlowToken transfer events +const subscription = await fcl.send([ + fcl.subscribeEvents({ + eventTypes: [ + "A.1654653399040a61.FlowToken.TokensWithdrawn", + "A.1654653399040a61.FlowToken.TokensDeposited" + ], + startHeight: 1000000, // Start from specific block height + heartbeatInterval: 3000 // 3 second heartbeat + }) +]); + +// Subscribe to events from specific contracts +const contractSubscription = await fcl.send([ + fcl.subscribeEvents({ + contracts: ["FlowToken", "FungibleToken"], + addresses: ["0x1654653399040a61"] + }) +]); + +// Handle the subscription data elsewhere using fcl.subscribe() +``` + +## Parameters + +### `eventFilter` + + +- Type: [`EventFilter`](../types#eventfilter) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeRaw.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeRaw.md new file mode 100644 index 0000000000..8a15cf23a8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/subscribeRaw.md @@ -0,0 +1,105 @@ +--- +sidebar_position: 1 +title: "subscribeRaw" +description: "subscribeRaw function documentation." +--- + + + +# subscribeRaw + +Subscribe to a topic without decoding the data. + +This function creates a raw subscription to Flow blockchain data streams without automatic decoding. +It's useful when you need more control over data processing or want to handle raw responses directly. +For most use cases, consider using the `subscribe()` function instead which provides automatic decoding. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.subscribeRaw(subscribeRawParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribeRaw } from "@onflow/fcl-react-native" + +subscribeRaw(subscribeRawParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to raw event data without automatic decoding +const rawSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (rawData) => { + console.log("Raw event data:", rawData); + // Handle raw data manually - no automatic decoding + }, + onError: (error) => { + console.error("Raw subscription error:", error); + } +}); + +// Subscribe to raw block data +const blockSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (rawBlock) => { + console.log("Raw block data:", rawBlock); + }, + onError: (error) => { + console.error("Error:", error); + } +}); + +// Unsubscribe when done +rawSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeRawParams` + + +- Type: +```typescript +SubscribeRawParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +```typescript +{ unsubscribe: () => void; } +``` + + +A subscription object with an unsubscribe method + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/transaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/transaction.md new file mode 100644 index 0000000000..cb26b644ef --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/transaction.md @@ -0,0 +1,104 @@ +--- +sidebar_position: 1 +title: "transaction" +description: "transaction function documentation." +--- + + + +# transaction + +A template builder to use a Cadence transaction for an interaction. FCL "mutate" does the work of building, signing, and sending a transaction behind the scenes. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.transaction(args) +``` + +Or import directly the specific function: + +```typescript +import { transaction } from "@onflow/fcl-react-native" + +transaction(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +// Basic transaction usage +await fcl.mutate({ + cadence: ` + transaction(a: Int) { + prepare(acct: &Account) { + log(acct) + log(a) + } + } + `, + args: (arg, t) => [ + arg(6, t.Int) + ], + limit: 50 +}) + +// Single party, single signature +// Proposer, payer and authorizer are the same account +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + authz: currentUser, // Optional. Will default to currentUser if not provided. + limit: 50, +}) + +// Multiple parties +// Proposer and authorizer are the same account, but different payer +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + proposer: authzFn, + payer: authzTwoFn, + authorizations: [authzFn], + limit: 50, +}) +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray, ...any[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/tx.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/tx.md new file mode 100644 index 0000000000..0a956c63f1 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/tx.md @@ -0,0 +1,120 @@ +--- +sidebar_position: 1 +title: "tx" +description: "tx function documentation." +--- + + + +# tx + +Creates a transaction monitor that provides methods for tracking and subscribing to +transaction status updates on the Flow blockchain. This function returns an object with methods +to get snapshots, subscribe to status changes, and wait for specific transaction states. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.tx(transactionId, opts) +``` + +Or import directly the specific function: + +```typescript +import { tx } from "@onflow/fcl-react-native" + +tx(transactionId, opts) +``` + +## Usage + +```typescript +// Basic transaction monitoring +import * as fcl from "@onflow/fcl" + +const txId = await fcl.mutate({ + cadence: ` + transaction { + execute { log("Hello, World!") } + } + ` +}) + +// Get current status +const status = await fcl.tx(txId).snapshot() +console.log("Current status:", status.status) + +// Subscribe to all status changes +const unsubscribe = fcl.tx(txId).subscribe((status) => { + console.log("Status update:", status.status) + if (status.status === fcl.transaction.isSealed) { + console.log("Transaction sealed!") + console.log("Events:", status.events) + } +}) +// Clean up subscription when done +setTimeout(() => unsubscribe(), 60000) + +// Wait for specific transaction states +try { + // Wait for finalization (consensus reached) + const finalizedStatus = await fcl.tx(txId).onceFinalized() + console.log("Transaction finalized") + + // Wait for execution (transaction executed) + const executedStatus = await fcl.tx(txId).onceExecuted() + console.log("Transaction executed") + + // Wait for sealing (transaction sealed in block) + const sealedStatus = await fcl.tx(txId).onceSealed() + console.log("Transaction sealed:", sealedStatus.events) +} catch (error) { + console.error("Transaction failed:", error.message) +} + +// Handle transaction errors +fcl.tx(txId).subscribe( + (status) => { + if (status.statusCode === 1) { + console.error("Transaction error:", status.errorMessage) + } + }, + (error) => { + console.error("Subscription error:", error) + } +) +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The 64-character hex transaction ID to monitor. Must be a valid +Flow transaction hash (64 bytes represented as hex string). + +### `opts` (optional) + + +- Type: +```typescript +{ pollRate?: number; txNotFoundTimeout?: number; } +``` +- Description: Optional configuration parameters + + +## Returns + +```typescript +{ snapshot: () => Promise; subscribe: (onData: (txStatus: TransactionStatus) => void, onError?: (err: Error) => void) => () => void; onceFinalized: () => Promise; onceExecuted: () => Promise; onceSealed: () => Promise; } +``` + + +Transaction monitor object with methods for tracking transaction status + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/unauthenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/unauthenticate.md new file mode 100644 index 0000000000..4399a19891 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/unauthenticate.md @@ -0,0 +1,37 @@ +--- +sidebar_position: 1 +title: "unauthenticate" +description: "unauthenticate function documentation." +--- + + + +# unauthenticate + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.unauthenticate() +``` + +Or import directly the specific function: + +```typescript +import { unauthenticate } from "@onflow/fcl-react-native" + +unauthenticate() +``` + + + +## Returns + +`void` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/useServiceDiscovery.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/useServiceDiscovery.md new file mode 100644 index 0000000000..223753da71 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/useServiceDiscovery.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +title: "useServiceDiscovery" +description: "Namespace containing useServiceDiscovery utilities" +--- + + + +# useServiceDiscovery + +## Overview + +Namespace containing useServiceDiscovery utilities + +## Functions + +### getAsyncStorage + + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.useServiceDiscovery.getAsyncStorage() +``` + +Or import the namespace directly: + +```typescript +import { useServiceDiscovery } from "@onflow/fcl-react-native" + +useServiceDiscovery.getAsyncStorage() +``` + + +#### Returns + +```typescript +{ can: boolean; get: (key: string) => Promise; put: (key: string, value: any) => Promise; } +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/validator.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/validator.md new file mode 100644 index 0000000000..780669cec5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/validator.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "validator" +description: "validator function documentation." +--- + + + +# validator + +A builder function that adds a validator to a transaction. + +Validators are functions that run during transaction building to check for invalid configurations or parameters. +They help catch errors early before submitting transactions to the network, preventing failed transactions +and wasted compute costs. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.validator(cb) +``` + +Or import directly the specific function: + +```typescript +import { validator } from "@onflow/fcl-react-native" + +validator(cb) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Custom validator to ensure account has sufficient balance +const validateBalance = (ix) => { + if (ix.message.computeLimit > 1000) { + throw new Error("Compute limit too high for this account"); + } + return ix; +}; + +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.validator(validateBalance), + fcl.limit(500) // This will pass validation +]); +``` + +## Parameters + +### `cb` + + +- Type: `Function` +- Description: The validator function that takes an interaction and returns it (or throws an error if invalid) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/verifyUserSignatures.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/verifyUserSignatures.md new file mode 100644 index 0000000000..59ab63832a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/verifyUserSignatures.md @@ -0,0 +1,40 @@ +--- +sidebar_position: 1 +title: "verifyUserSignatures" +description: "verifyUserSignatures function documentation." +--- + + + +# verifyUserSignatures + +Verify a valid signature/s for an account on Flow. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.verifyUserSignatures() +``` + +Or import directly the specific function: + +```typescript +import { verifyUserSignatures } from "@onflow/fcl-react-native" + +verifyUserSignatures() +``` + + + +## Returns + +```typescript +Promise | ((...args: any[]) => Promise>) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherIntercept.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherIntercept.md new file mode 100644 index 0000000000..fcde4232a3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherIntercept.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "voucherIntercept" +description: "voucherIntercept function documentation." +--- + + + +# voucherIntercept + +A builder function that intercepts and modifies a voucher. + +This function is useful for debugging, logging, or making modifications to +the transaction data. The voucher contains all the transaction details in their final form. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.voucherIntercept(fn) +``` + +Or import directly the specific function: + +```typescript +import { voucherIntercept } from "@onflow/fcl-react-native" + +voucherIntercept(fn) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Intercept voucher for logging +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.voucherIntercept((voucher) => { + console.log("Voucher details:", { + cadence: voucher.cadence, + proposalKey: voucher.proposalKey, + payer: voucher.payer, + authorizers: voucher.authorizers, + computeLimit: voucher.computeLimit + }); + }), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]) +]); +``` + +## Parameters + +### `fn` + + +- Type: +```typescript +type VoucherInterceptFn = (voucher: Voucher) => any | Promise +``` +- Description: The function to intercept and potentially modify the voucher + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherToTxId.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherToTxId.md new file mode 100644 index 0000000000..caab78500a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/voucherToTxId.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: "voucherToTxId" +description: "voucherToTxId function documentation." +--- + + + +# voucherToTxId + +Converts a voucher object to a transaction ID. + +This function computes the transaction ID by encoding and hashing the voucher. +The transaction ID can be used to track the transaction status on the Flow network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.voucherToTxId(voucher) +``` + +Or import directly the specific function: + +```typescript +import { voucherToTxId } from "@onflow/fcl-react-native" + +voucherToTxId(voucher) +``` + +## Usage + +```typescript +import { voucherToTxId, createSignableVoucher } from "@onflow/sdk" +import * as fcl from "@onflow/fcl"; + +// Create a voucher from an interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Hello, Flow!") + } + } + `, + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]); + +const voucher = createSignableVoucher(interaction); + +// Calculate the transaction ID +const txId = voucherToTxId(voucher); +console.log("Transaction ID:", txId); +// Returns something like: "a1b2c3d4e5f6789..." + +// You can use this ID to track the transaction +const txStatus = await fcl.tx(txId).onceSealed(); +console.log("Transaction status:", txStatus); +``` + +## Parameters + +### `voucher` + + +- Type: +```typescript +export interface Voucher { + cadence: string + refBlock: string + computeLimit: number + arguments: VoucherArgument[] + proposalKey: VoucherProposalKey + payer: string + authorizers: string[] + payloadSigs: Sig[] + envelopeSigs: Sig[] +} +``` +- Description: The voucher object to convert + + +## Returns + +`string` + + +A transaction ID string + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/why.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/why.md new file mode 100644 index 0000000000..7707ed8c5f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/why.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "why" +description: "why function documentation." +--- + + + +# why + +Returns the reason for an interaction failure. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.why(ix) +``` + +Or import directly the specific function: + +```typescript +import { why } from "@onflow/fcl-react-native" + +why(ix) +``` + +## Usage + +```typescript +import { Bad, why, initInteraction } from "@onflow/sdk" + +const interaction = Bad(initInteraction(), "Network timeout"); +console.log(why(interaction)); // "Network timeout" + +// Used with error handling +if (isBad(response)) { + console.error("Error occurred:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to get the failure reason from + + +## Returns + +`string` + + +The reason string or undefined if no reason is set + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/withPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/withPrefix.md new file mode 100644 index 0000000000..113d09650c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl-react-native/withPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "withPrefix" +description: "withPrefix function documentation." +--- + + + +# withPrefix + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl-react-native" + +fcl.withPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { withPrefix } from "@onflow/fcl-react-native" + +withPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/account.md b/docs/tools/clients/fcl-js/packages-docs/fcl/account.md new file mode 100644 index 0000000000..b69fe5b1cf --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/account.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "account" +description: "account function documentation." +--- + + + +# 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.account(address, accountQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { account } from "@onflow/fcl" + +account(address, accountQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get account from latest block height +const account = await fcl.account("0x1d007d755706c469"); +console.log("Address:", account.address); +console.log("Balance:", account.balance); +console.log("Keys:", account.keys); +console.log("Contracts:", Object.keys(account.contracts)); + +// Get account at a specific block height +const historicalAccount = await fcl.account("0x1d007d755706c469", { + height: 12345 +}); + +// Get account at a specific block ID +const accountAtBlock = await fcl.account("0x1d007d755706c469", { + id: "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3" +}); + +// Get account from sealed block +const sealedAccount = await fcl.account("0x1d007d755706c469", { + isSealed: true +}); + +// Alternative using builder pattern +fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(123) +]).then(fcl.decode); +``` + +## Parameters + +### `address` + + +- Type: `string` +- Description: Address of the account + +### `accountQueryOptions` (optional) + + +- Type: +```typescript +interface AccountQueryOptions { + height?: number + id?: string + isSealed?: boolean +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#account) + + +A promise that resolves to an Account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/arg.md b/docs/tools/clients/fcl-js/packages-docs/fcl/arg.md new file mode 100644 index 0000000000..669051dda1 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/arg.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "arg" +description: "arg function documentation." +--- + + + +# arg + +A utility builder to be used with fcl.args[...] to create FCL supported arguments for interactions. + +Arguments are used to pass data to Cadence scripts and transactions. The arguments must match the number and order declared in the Cadence script. +This function creates an ArgumentObject that holds the value and type passed in. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.arg(value, xform) +``` + +Or import directly the specific function: + +```typescript +import { arg } from "@onflow/fcl" + +arg(value, xform) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +const result = await fcl.query({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `value` + + +- Type: +```typescript +TypeDescriptorInput +``` +- Description: Any value that you are looking to pass to other builders + +### `xform` + + +- Type: `T` +- Description: A type supported by Flow (FType descriptor) + + +## Returns + +```typescript +CadenceArgument +``` + + +An ArgumentObject that holds the value and type passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/args.md b/docs/tools/clients/fcl-js/packages-docs/fcl/args.md new file mode 100644 index 0000000000..9642e1112b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/args.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "args" +description: "args function documentation." +--- + + + +# args + +A utility builder to be used with other builders to pass in arguments with a value and supported type. + +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. +This function returns a Partial Interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.args(ax) +``` + +Or import directly the specific function: + +```typescript +import { args } from "@onflow/fcl" + +args(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +await fcl.mutate({ + cadence: ` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // transaction logic + } + } + `, + args: (arg, t) => [ + arg("10.0", t.UFix64), // Will be the first argument `amount: UFix64` + arg("0xba1132bc08f82fe2", t.Address), // Will be the second argument `to: Address` + ], +}) +``` + +## Parameters + +### `ax` + + +- Type: +```typescript +CadenceArgument[] +``` +- Description: An array of argument objects created with fcl.arg() + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A Partial Interaction object containing the arguments and types passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockHeight.md b/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockHeight.md new file mode 100644 index 0000000000..1fe91dc097 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockHeight.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockHeight" +description: "atBlockHeight function documentation." +--- + + + +# 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. + +Block height expresses the height of the block on the chain. The latest block height increases by one for every valid block produced. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.atBlockHeight(height) +``` + +Or import directly the specific function: + +```typescript +import { atBlockHeight } from "@onflow/fcl" + +atBlockHeight(height) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block at specific height +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode); + +// Get account at specific block height +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Execute script at specific block height +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().height + } + `, + fcl.atBlockHeight(100) +]).then(fcl.decode); +``` + +## Parameters + +### `height` + + +- Type: `number` +- Description: The height of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockId.md b/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockId.md new file mode 100644 index 0000000000..1854a806a8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/atBlockId.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockId" +description: "atBlockId function documentation." +--- + + + +# 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. + +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'). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.atBlockId(id) +``` + +Or import directly the specific function: + +```typescript +import { atBlockId } from "@onflow/fcl" + +atBlockId(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block by ID +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get account at specific block ID +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockId("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); + +// Execute script at specific block +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().timestamp + } + `, + fcl.atBlockId("a1b2c3d4e5f6") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` +- Description: The ID of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/authenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl/authenticate.md new file mode 100644 index 0000000000..0e45d76a78 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/authenticate.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "authenticate" +description: "authenticate function documentation." +--- + + + +# authenticate + +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. + +This method can only be used in web browsers. + +`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. + +`authenticate` can also take a service returned from discovery with `fcl.authenticate({ service })`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.authenticate(opts) +``` + +Or import directly the specific function: + +```typescript +import { authenticate } from "@onflow/fcl" + +authenticate(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; +fcl + .config() + .put('accessNode.api', 'https://rest-testnet.onflow.org') + .put('discovery.wallet', 'https://fcl-discovery.onflow.org/testnet/authn'); +// anywhere on the page +fcl.authenticate(); +``` + +## Parameters + +### `opts` (optional) + + +- Type: `{}` +- Description: Authentication options + + +## Returns + +[`Promise`](../types#currentuser) + + +Promise that resolves to the authenticated CurrentUser object or undefined + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/authorization.md b/docs/tools/clients/fcl-js/packages-docs/fcl/authorization.md new file mode 100644 index 0000000000..620b63e6a9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/authorization.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: "authorization" +description: "authorization function documentation." +--- + + + +# authorization + +Creates an authorization function for use in transactions. + +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. + +Read more about [authorization functions](https://docs.onflow.org/fcl/reference/authorization-function/) and [transaction roles](https://docs.onflow.org/concepts/transaction-signing/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.authorization(addr, signingFunction, keyId, sequenceNum) +``` + +Or import directly the specific function: + +```typescript +import { authorization } from "@onflow/fcl" + +authorization(addr, signingFunction, keyId, sequenceNum) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { ec as EC } from "elliptic"; + +// Create a signing function +const signingFunction = ({ message }) => { + // Your signing logic here + return { + addr: "0x123456789abcdef0", + keyId: 0, + signature: "your_signature_here" + }; +}; + +// Create authorization +const authz = fcl.authorization( + "0x123456789abcdef0", // account address + signingFunction, // signing function + 0, // key ID + 42 // sequence number +); + +// Use in transaction +await fcl.mutate({ + cadence: `transaction { prepare(acct: AuthAccount) {} }`, + proposer: authz, + payer: authz, + authorizations: [authz] +}); +``` + +## Parameters + +### `addr` + + +- Type: `string` +- Description: The address of the account that will sign the transaction + +### `signingFunction` + + +- Type: +```typescript +type SigningFn = ( + signable?: SignableMessage +) => SigningResult | Promise +``` +- Description: A function that produces signatures for the account + +### `keyId` (optional) + + +- Type: `string | number` +- Description: The index of the key to use for signing (optional) + +### `sequenceNum` (optional) + + +- Type: `number` +- Description: The sequence number for the account key (optional) + + +## Returns + +```typescript +Partial +``` + + +A partial interaction account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/authorizations.md b/docs/tools/clients/fcl-js/packages-docs/fcl/authorizations.md new file mode 100644 index 0000000000..ba163fa6cf --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/authorizations.md @@ -0,0 +1,106 @@ +--- +sidebar_position: 1 +title: "authorizations" +description: "authorizations function documentation." +--- + + + +# authorizations + +A utility builder to set the authorizations on a transaction. + +Authorizations define the accounts that are responsible for paying the transaction fees and providing signatures for the transaction. +You can have multiple authorizers in a single transaction (multi-signature transactions). + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.authorizations(ax) +``` + +Or import directly the specific function: + +```typescript +import { authorizations } from "@onflow/fcl" + +authorizations(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Single authorizer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Hello from: ".concat(acct.address.toString())) + } + } + `, + authorizations: [fcl.authz] // Current user authorization +}); + +// Multiple authorizers - both accounts must approve +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct1: AuthAccount, acct2: AuthAccount) { + log("Transaction signed by both accounts") + } + } + `, + authorizations: [userOneAuthz, userTwoAuthz] +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + acct.save("Hello, World!", to: /storage/greeting) + } + } + `, + fcl.authorizations([fcl.authz]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.limit(100) +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An array of authorization functions that produce account authorization details + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/authz.md b/docs/tools/clients/fcl-js/packages-docs/fcl/authz.md new file mode 100644 index 0000000000..61c5e50d08 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/authz.md @@ -0,0 +1,70 @@ +--- +sidebar_position: 1 +title: "authz" +description: "authz function documentation." +--- + + + +# 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.authz() +``` + +Or import directly the specific function: + +```typescript +import { authz } from "@onflow/fcl" + +authz() +``` + +## Usage + +```typescript +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: auth(BorrowValue) &Account) { + account.storage.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] +}); +``` + + +## Returns + +```typescript +(account: Account) => Promise +``` + + +An object containing the necessary details from the current user to authorize a transaction in any role. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/block.md b/docs/tools/clients/fcl-js/packages-docs/fcl/block.md new file mode 100644 index 0000000000..c435e95aa4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/block.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "block" +description: "block function documentation." +--- + + + +# block + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.block(blockQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { block } from "@onflow/fcl" + +block(blockQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest block +const latestBlock = await fcl.block(); // Get the latest finalized block +const latestSealedBlock = await fcl.block({sealed: true}); // Get the latest sealed block + +// Get block by ID (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get block at height (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode) +``` + +## Parameters + +### `blockQueryOptions` (optional) + + +- Type: +```typescript +interface BlockQueryOptions { + sealed?: boolean + height?: number + id?: string +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#block) + + +A promise that resolves to a Block object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/build.md b/docs/tools/clients/fcl-js/packages-docs/fcl/build.md new file mode 100644 index 0000000000..49c16a48de --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/build.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "build" +description: "build function documentation." +--- + + + +# build + +A builder function that creates an interaction from an array of builder functions. + +The build function takes an array of builder functions and applies them to create a complete interaction object. This is the foundation for constructing all interactions in Flow, whether they're scripts, transactions, or queries. + +Each builder function modifies specific parts of the interaction object, such as adding Cadence code, arguments, authorization details, or other configuration. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.build(fns) +``` + +Or import directly the specific function: + +```typescript +import { build } from "@onflow/fcl" + +build(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Build a script interaction +const scriptInteraction = await fcl.build([ + fcl.script` + access(all) fun main(a: Int, b: Int): Int { + return a + b + } + `, + fcl.args([ + fcl.arg(1, fcl.t.Int), + fcl.arg(2, fcl.t.Int) + ]) +]); + +// Build a transaction interaction +const txInteraction = await fcl.build([ + fcl.transaction` + transaction(name: String) { + prepare(account: AuthAccount) { + log("Hello, " + name) + } + } + `, + fcl.args([fcl.arg("World", fcl.t.String)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `fns` (optional) + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: The functions to apply to the interaction + + +## Returns + +[`Promise`](../types#interaction) + + +A promise of an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/cadence.md b/docs/tools/clients/fcl-js/packages-docs/fcl/cadence.md new file mode 100644 index 0000000000..562cb607be --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/cadence.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cadence" +description: "cadence function documentation." +--- + + + +# cadence + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.cadence(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cadence } from "@onflow/fcl" + +cadence(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/cdc.md b/docs/tools/clients/fcl-js/packages-docs/fcl/cdc.md new file mode 100644 index 0000000000..009d60f237 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/cdc.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cdc" +description: "cdc function documentation." +--- + + + +# cdc + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.cdc(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cdc } from "@onflow/fcl" + +cdc(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/config.md b/docs/tools/clients/fcl-js/packages-docs/fcl/config.md new file mode 100644 index 0000000000..dd062dfbb4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/config.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "config" +description: "config function documentation." +--- + + + +# config + +Sets the config + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.config(values) +``` + +Or import directly the specific function: + +```typescript +import { config } from "@onflow/fcl" + +config(values) +``` + + +## Parameters + +### `values` (optional) + + +- Type: +```typescript +Record +``` +- Description: - The values to set + + +## Returns + +```typescript +{ put: typeof put; get: typeof get; all: typeof all; first: typeof first; update: typeof update; delete: typeof _delete; where: typeof where; subscribe: typeof subscribe; overload: typeof overload; load: typeof load; } +``` + + +The config object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/createSignableVoucher.md b/docs/tools/clients/fcl-js/packages-docs/fcl/createSignableVoucher.md new file mode 100644 index 0000000000..8c14c7378d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/createSignableVoucher.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "createSignableVoucher" +description: "createSignableVoucher function documentation." +--- + + + +# createSignableVoucher + +Creates a signable voucher object from an interaction for signing purposes. + +A voucher is a standardized representation of a transaction that contains all the necessary +information for signing and submitting to the Flow network. This function transforms an +interaction object into a voucher format. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.createSignableVoucher(ix) +``` + +Or import directly the specific function: + +```typescript +import { createSignableVoucher } from "@onflow/fcl" + +createSignableVoucher(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { createSignableVoucher } from "@onflow/sdk" + +// Build a transaction interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); + +// Create a voucher for signing +const voucher = createSignableVoucher(interaction); +console.log(voucher.cadence); // The Cadence script +console.log(voucher.arguments); // The transaction arguments +console.log(voucher.proposalKey); // Proposer account details +console.log(voucher.authorizers); // List of authorizer addresses + +// The voucher can now be signed and submitted +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing transaction details + + +## Returns + +```typescript +{ cadence: string; refBlock: string; computeLimit: number; arguments: any[]; proposalKey: { address: string; keyId: string | number; sequenceNum: number; } | { address?: undefined; keyId?: undefined; sequenceNum?: undefined; }; payer: string; authorizers: string[]; payloadSigs: { address: string; keyId: string | number; sig: string; }[]; envelopeSigs: { address: string; keyId: string | number; sig: string; }[]; } +``` + + +A voucher object containing all transaction data and signatures + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/currentUser.md b/docs/tools/clients/fcl-js/packages-docs/fcl/currentUser.md new file mode 100644 index 0000000000..d27b0f0eab --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/currentUser.md @@ -0,0 +1,106 @@ +--- +sidebar_position: 1 +title: "currentUser" +description: "currentUser function documentation." +--- + + + +# currentUser + +The main current user service for managing user authentication and authorization in Flow applications. +This service provides a complete interface for wallet connections, user sessions, transaction signing, and user data management. +It handles the complexity of connecting to various FCL-compatible wallets, managing authentication state, and providing +authorization functions for transaction signing. + +The currentUser service is configured for web platforms and uses the browser's localStorage by default for session persistence. +It integrates with Flow's discovery service to enable wallet selection and supports both authentication and re-authentication flows. + +This service is reactive and provides subscription capabilities to monitor authentication state changes in real-time. +All wallet interactions are handled through FCL's standardized protocols, ensuring compatibility with the Flow ecosystem. + +Returns an object with the following methods: +```typescript +{ +authenticate, // Authenticates the user via FCL-compatible wallets +unauthenticate, // Logs out the current user and clears session data +authorization, // Produces authorization details for transaction signing +signUserMessage, // Signs arbitrary messages with the user's wallet +subscribe, // Subscribes to authentication state changes +snapshot, // Returns the current user object snapshot +resolveArgument // Resolves the current user as a transaction argument +} +``` + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.currentUser() +``` + +Or import directly the specific function: + +```typescript +import { currentUser } from "@onflow/fcl" + +currentUser() +``` + +## Usage + +```typescript +// Basic authentication flow +import * as fcl from "@onflow/fcl" + +// Configure FCL +fcl.config({ + "accessNode.api": "https://rest-testnet.onflow.org", + "discovery.wallet": "https://fcl-discovery.onflow.org/testnet/authn", + "flow.network": "testnet" +}) + +// Authenticate user +const user = await fcl.currentUser.authenticate() +console.log("User authenticated:", user.addr) + +// Check authentication status +const currentUser = await fcl.currentUser.snapshot() +if (currentUser.loggedIn) { + console.log("User is logged in:", currentUser.addr) +} + +// Subscribe to authentication state changes +import * as fcl from "@onflow/fcl" + +const unsubscribe = fcl.currentUser.subscribe((user) => { + if (user.loggedIn) { + console.log("User logged in:", user.addr) + document.getElementById("login-btn").style.display = "none" + document.getElementById("logout-btn").style.display = "block" + } else { + console.log("User logged out") + document.getElementById("login-btn").style.display = "block" + document.getElementById("logout-btn").style.display = "none" + } +}) +// Clean up subscription when component unmounts +window.addEventListener("beforeunload", () => unsubscribe()) +``` + + +## Returns + +```typescript +export interface CurrentUserService extends CurrentUserServiceApi { + (): CurrentUserServiceApi +} +``` + + +A CurrentUserService object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/decode.md b/docs/tools/clients/fcl-js/packages-docs/fcl/decode.md new file mode 100644 index 0000000000..35807509aa --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/decode.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "decode" +description: "decode function documentation." +--- + + + +# decode + +Decodes the response from 'fcl.send()' into the appropriate JSON representation of any values returned from Cadence code. + +The response from Flow contains encoded values that need to be decoded into JavaScript types. This function handles that conversion, including complex types like structs, arrays, and dictionaries. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.decode(response) +``` + +Or import directly the specific function: + +```typescript +import { decode } from "@onflow/fcl" + +decode(response) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple script to add 2 numbers +const response = await fcl.send([ + fcl.script` + access(all) 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); +console.log(decoded); // 3 +console.log(typeof decoded); // "number" + +// Complex return types +const complexResponse = await fcl.send([ + fcl.script` + access(all) fun main(): {String: Int} { + return {"foo": 1, "bar": 2} + } + ` +]); + +const complexDecoded = await fcl.decode(complexResponse); +console.log(complexDecoded); // {foo: 1, bar: 2} +``` + +## Parameters + +### `response` + + +- Type: `any` +- Description: Should be the response returned from 'fcl.send([...])' + + +## Returns + +`Promise` + + +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. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/display.md b/docs/tools/clients/fcl-js/packages-docs/fcl/display.md new file mode 100644 index 0000000000..c1f62aab43 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/display.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "display" +description: "display function documentation." +--- + + + +# display + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.display(address) +``` + +Or import directly the specific function: + +```typescript +import { display } from "@onflow/fcl" + +display(address) +``` + + +## Parameters + +### `address` + + +- Type: `string` +- Description: - Flow address + + +## Returns + +`string` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/events.md b/docs/tools/clients/fcl-js/packages-docs/fcl/events.md new file mode 100644 index 0000000000..7a5ae1b896 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/events.md @@ -0,0 +1,99 @@ +--- +sidebar_position: 1 +title: "events" +description: "events function documentation." +--- + + + +# events + +Subscribes to Flow blockchain events in real-time. This function provides a way to listen +for specific events emitted by smart contracts on the Flow blockchain. It automatically handles +fallback to legacy polling for environments that don't support WebSocket subscriptions. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.events(filterOrType) +``` + +Or import directly the specific function: + +```typescript +import { events } from "@onflow/fcl" + +events(filterOrType) +``` + +## Usage + +```typescript +// Subscribe to a specific event type +import * as fcl from "@onflow/fcl" + +const unsubscribe = fcl.events("A.0x1654653399040a61.FlowToken.TokensWithdrawn") + .subscribe((event) => { + console.log("Event received:", event) + console.log("Event data:", event.data) + console.log("Transaction ID:", event.transactionId) + }) + +// Stop listening after 30 seconds +setTimeout(() => { + unsubscribe() +}, 30000) + +// Subscribe to multiple event types with error handling +const unsubscribe = fcl.events({ + eventTypes: [ + "A.0x1654653399040a61.FlowToken.TokensWithdrawn", + "A.0x1654653399040a61.FlowToken.TokensDeposited" + ] +}).subscribe( + (event) => { + console.log("Token event:", event.type, event.data) + }, + (error) => { + console.error("Event subscription error:", error) + } +) + +// Subscribe to events starting from a specific block height +const unsubscribe = fcl.events({ + eventTypes: ["A.CONTRACT.EVENT"], + startBlockHeight: 12345678 +}).subscribe((event) => { + console.log("Historical and new events:", event) +}) +``` + +## Parameters + +### `filterOrType` (optional) + + +- Type: `string` | [`EventFilter`](../types#eventfilter) +- Description: Event filter object or event type string. +If a string is provided, it will be treated as a single event type to subscribe to. +If an EventFilter object is provided, it can contain multiple event types and other filter criteria. + + +## Returns + +```typescript +{ subscribe: (onData: (event: Event) => void, onError?: (error: Error) => void) => () => void; } +``` + + +An object containing a subscribe method +• returns.subscribe Function to start the subscription +• returns.subscribe.onData Callback function called when an event is received +• returns.subscribe.onError Optional callback function called when an error occurs +• returns.subscribe.unsubscribe Function returned by subscribe() to stop the subscription + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getAccount.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getAccount.md new file mode 100644 index 0000000000..accfafea5f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getAccount.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getAccount" +description: "getAccount function documentation." +--- + + + +# 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. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getAccount(addr) +``` + +Or import directly the specific function: + +```typescript +import { getAccount } from "@onflow/fcl" + +getAccount(addr) +``` + +## Usage + +```typescript +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; +}; +``` + +## Parameters + +### `addr` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getBlock.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getBlock.md new file mode 100644 index 0000000000..3ad9be5f6f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getBlock.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getBlock" +description: "getBlock function documentation." +--- + + + +# 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.block(options)' if you do not need to pair with any other builders. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getBlock(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlock } from "@onflow/fcl" + +getBlock(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const latestSealedBlock = await fcl.send([ + fcl.getBlock(true) // isSealed = true +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: If the latest block should be sealed or not. See block states + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getBlockHeader.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getBlockHeader.md new file mode 100644 index 0000000000..3c97ad96a3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getBlockHeader.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getBlockHeader" +description: "getBlockHeader function documentation." +--- + + + +# getBlockHeader + +A builder function that returns the interaction to get a block header. + +A block header contains metadata about a block without the full transaction details, making it more +lightweight than fetching the entire block. This is useful when you only need block metadata like +timestamp, height, parent hash, etc. + +Use with 'fcl.atBlockId()' and 'fcl.atBlockHeight()' when building the interaction to get headers for specific blocks. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getBlockHeader(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlockHeader } from "@onflow/fcl" + +getBlockHeader(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest sealed block header +const sealedHeader = await fcl.send([ + fcl.getBlockHeader(true) +]).then(fcl.decode); + +console.log("Block height:", sealedHeader.height); +console.log("Block timestamp:", sealedHeader.timestamp); +console.log("Parent block ID:", sealedHeader.parentId); + +// Get header for specific block +const blockHeader = await fcl.send([ + fcl.getBlockHeader(), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Get latest finalized block header +const finalizedHeader = await fcl.send([ + fcl.getBlockHeader(false) +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: Block finality state, true for sealed blocks, false for finalized blocks, null for latest + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getChainId.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getChainId.md new file mode 100644 index 0000000000..680dfc666f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getChainId.md @@ -0,0 +1,64 @@ +--- +sidebar_position: 1 +title: "getChainId" +description: "getChainId function documentation." +--- + + + +# getChainId + +Gets the chain ID if its set, otherwise gets the chain ID from the access node + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getChainId(opts) +``` + +Or import directly the specific function: + +```typescript +import { getChainId } from "@onflow/fcl" + +getChainId(opts) +``` + +## Usage + +```typescript +// Get chain ID using configured access node +import * as fcl from "@onflow/fcl" + +const chainId = await fcl.getChainId() +console.log("Connected to:", chainId) // "testnet" or "mainnet" +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface GetChainIdOptions { + node?: unknown + enableRequestLogging?: boolean + [key: string]: any +} +``` +- Description: Optional configuration parameters + + +## Returns + +`Promise` + + +Promise that resolves to the chain ID string (e.g., "mainnet", "testnet", "local") + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getCollection.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getCollection.md new file mode 100644 index 0000000000..561fb21d8a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getCollection.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "getCollection" +description: "getCollection function documentation." +--- + + + +# getCollection + +A builder function that returns a collection containing a list of transaction IDs by its collection ID. + +A collection is a batch of transactions that have been included in a block. Each collection has a unique ID +which is the SHA3-256 hash of the collection payload. Collections are used to group related transactions +together for more efficient processing by the network. + +The collection ID provided must be from the current spork. Collections from past sporks are currently unavailable. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getCollection(id) +``` + +Or import directly the specific function: + +```typescript +import { getCollection } from "@onflow/fcl" + +getCollection(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get a collection and see what transactions it contains +const collection = await fcl.send([ + fcl.getCollection("cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5") +]).then(fcl.decode); + +console.log("Collection ID:", collection.id); +console.log("Transaction IDs:", collection.transactionIds); +console.log("Total transactions:", collection.transactionIds.length); + +// Process each transaction in the collection +for (const txId of collection.transactionIds) { + const transaction = await fcl.send([ + fcl.getTransaction(txId) + ]).then(fcl.decode); + console.log("Transaction:", transaction); +} +``` + +## Parameters + +### `id` (optional) + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getEvents.md new file mode 100644 index 0000000000..ade8b4fddd --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getEvents.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getEvents" +description: "getEvents function documentation." +--- + + + +# getEvents + +A builder function that returns the interaction to get events. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened during execution. +This function queries for events of a specific type within a range of block heights. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getEvents(eventType, start, end) +``` + +Or import directly the specific function: + +```typescript +import { getEvents } from "@onflow/fcl" + +getEvents(eventType, start, end) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get FlowToken transfer events from blocks 1000 to 2000 +const events = await fcl.send([ + fcl.getEvents("A.1654653399040a61.FlowToken.TokensDeposited", 1000, 2000) +]).then(fcl.decode); + +console.log("Found events:", events.length); +events.forEach(event => { + console.log("Event data:", event.data); + console.log("Transaction ID:", event.transactionId); +}); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get (e.g., "A.1654653399040a61.FlowToken.TokensWithdrawn") + +### `start` + + +- Type: `number` +- Description: The start block height to query from + +### `end` + + +- Type: `number` +- Description: The end block height to query to + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockHeightRange.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockHeightRange.md new file mode 100644 index 0000000000..9f0ce95714 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockHeightRange.md @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockHeightRange" +description: "getEventsAtBlockHeightRange function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +Block height range expresses the height of the start and end block in the chain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockHeightRange } from "@onflow/fcl" + +getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get events at block height range +await fcl + .send([ + fcl.getEventsAtBlockHeightRange( + "A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name + 35580624, // block to start looking for events at + 35580624 // block to stop looking for events at + ), + ]) + .then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `startHeight` + + +- Type: `number` +- Description: The height of the block to start looking for events (inclusive) + +### `endHeight` + + +- Type: `number` +- Description: The height of the block to stop looking for events (inclusive) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockIds.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockIds.md new file mode 100644 index 0000000000..232c21e3c2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getEventsAtBlockIds.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockIds" +description: "getEventsAtBlockIds function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getEventsAtBlockIds(eventType, blockIds) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockIds } from "@onflow/fcl" + +getEventsAtBlockIds(eventType, blockIds) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const events = await fcl.send([ + fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [ + "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7", + "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f" + ]) +]).then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `blockIds` + + +- Type: `string[]` +- Description: The ids of the blocks to scan for events + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getNetworkParameters.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getNetworkParameters.md new file mode 100644 index 0000000000..cf63076b50 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getNetworkParameters.md @@ -0,0 +1,68 @@ +--- +sidebar_position: 1 +title: "getNetworkParameters" +description: "getNetworkParameters function documentation." +--- + + + +# getNetworkParameters + +A builder function that returns the interaction to get network parameters. + +Network parameters contain important configuration information about the Flow network, +including the chain ID, which is essential for signing transactions correctly. +This information is crucial for ensuring transactions are submitted to the correct network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getNetworkParameters() +``` + +Or import directly the specific function: + +```typescript +import { getNetworkParameters } from "@onflow/fcl" + +getNetworkParameters() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get network parameters to verify chain ID +const params = await fcl.send([ + fcl.getNetworkParameters() +]).then(fcl.decode); + +console.log("Chain ID:", params.chainId); +console.log("Network:", params.name); + +// Use this to verify you're connected to the right network +if (params.chainId === "flow-mainnet") { + console.log("Connected to Flow Mainnet"); +} else if (params.chainId === "flow-testnet") { + console.log("Connected to Flow Testnet"); +} +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getNodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getNodeVersionInfo.md new file mode 100644 index 0000000000..030fc5a198 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getNodeVersionInfo.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getNodeVersionInfo" +description: "getNodeVersionInfo function documentation." +--- + + + +# getNodeVersionInfo + +A builder function for the Get Node Version Info interaction. + +Creates an interaction to retrieve version information from the connected Flow Access Node. +This includes details about the node's software version, protocol version, and spork information. + +Consider using the pre-built interaction 'fcl.nodeVersionInfo()' if you do not need to pair with any other builders. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getNodeVersionInfo() +``` + +Or import directly the specific function: + +```typescript +import { getNodeVersionInfo } from "@onflow/fcl" + +getNodeVersionInfo() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information using builder +const versionInfo = await fcl.send([ + fcl.getNodeVersionInfo() +]).then(fcl.decode); + +console.log("Node version:", versionInfo.semver); +console.log("Protocol version:", versionInfo.protocol_version); +console.log("Spork ID:", versionInfo.spork_id); + +// Use with other builders if needed +const interaction = await fcl.build([ + fcl.getNodeVersionInfo() + // other builders can be added here +]); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getTransaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getTransaction.md new file mode 100644 index 0000000000..7580cc8a97 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getTransaction.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getTransaction" +description: "getTransaction function documentation." +--- + + + +# getTransaction + +A builder function that returns the interaction to get a transaction by id. + +Transaction id is a hash of the encoded transaction payload and can be calculated before submitting the transaction to the network. +Transaction status represents the state of a transaction in the blockchain. Status can change until it is finalized. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id).onceExecuted()' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getTransaction(id) +``` + +Or import directly the specific function: + +```typescript +import { getTransaction } from "@onflow/fcl" + +getTransaction(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const tx = await fcl.send([ + fcl.getTransaction("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/getTransactionStatus.md b/docs/tools/clients/fcl-js/packages-docs/fcl/getTransactionStatus.md new file mode 100644 index 0000000000..a5e21e9c36 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/getTransactionStatus.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "getTransactionStatus" +description: "getTransactionStatus function documentation." +--- + + + +# getTransactionStatus + +A builder function that returns the status of transaction. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id)' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.getTransactionStatus(transactionId) +``` + +Or import directly the specific function: + +```typescript +import { getTransactionStatus } from "@onflow/fcl" + +getTransactionStatus(transactionId) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const status = await fcl.send([ + fcl.getTransactionStatus("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The id of the transaction to get the status of + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/index.md b/docs/tools/clients/fcl-js/packages-docs/fcl/index.md new file mode 100644 index 0000000000..eea682d343 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/index.md @@ -0,0 +1,297 @@ +--- +sidebar_position: 1 +title: "@onflow/fcl" +description: "High-level JavaScript/TypeScript library for building web applications on the Flow blockchain." +--- + + + +# @onflow/fcl + +## Overview + +The Flow fcl library provides a set of tools for developers to build applications on the Flow blockchain. + +## Installation + +You can install the @onflow/fcl package using npm or yarn: + +```bash +npm install @onflow/fcl +``` + +Or using yarn: + +```bash +yarn add @onflow/fcl +``` + +### Requirements + +- Node.js 14.x or later + +### Importing + +You can import the entire package: + +```typescript +import * as fcl from "@onflow/fcl" +``` + +Or import specific functions: + +```typescript +import { functionName } from "@onflow/fcl" +``` + +## 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. + +```javascript +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. + +```javascript +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 + +| 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](https://developers.onflow.org/http-api/). | +| `app.detail.title` | `Cryptokitties` | Your applications title, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.icon` | `https://fcl-discovery.onflow.org/images/blocto.png` | Url for your applications icon, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.description` | `Cryptokitties is a blockchain game` | Your applications description, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `app.detail.url` | `https://cryptokitties.co` | Your applications url, can be requested by wallets and other services. Used by WalletConnect plugin & Wallet Discovery service. | +| `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. | +| `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`, `testnet`, `mainnet`. | +| `walletconnect.projectId` | `YOUR_PROJECT_ID` | Your app's WalletConnect project ID. See [WalletConnect Cloud](https://cloud.walletconnect.com/sign-in) to obtain a project ID for your application. | +| `walletconnect.disableNotifications` | `false` | Optional flag to disable pending WalletConnect request notifications within the application's UI. | + +## Using Contracts in Scripts and Transactions + +### Address Replacement + +Configuration keys that start with `0x` will be replaced in FCL scripts and transactions, this allows you to write your script or transaction Cadence code once and not have to change it when you point your application at a difference instance of the Flow Blockchain. + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl.config().put('0xFungibleToken', '0xf233dcee88fe0abe'); + +async function myScript() { + return fcl + .send([ + fcl.script` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + access(all) fun main() { /* Rest of the script goes here */ } + `, + ]) + .then(fcl.decode); +} + +async function myTransaction() { + return fcl + .send([ + fcl.transaction` + import FungibleToken from 0xFungibleToken // will be replaced with 0xf233dcee88fe0abe because of the configuration + + transaction { /* Rest of the transaction goes here */ } + `, + ]) + .then(fcl.decode); +} +``` + +#### Example + +```javascript +import * as fcl from '@onflow/fcl'; + +fcl + .config() + .put('flow.network', 'testnet') + .put('walletconnect.projectId', 'YOUR_PROJECT_ID') + .put('accessNode.api', 'https://rest-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('app.detail.description', 'A test harness for FCL') + .put('app.detail.url', 'https://myapp.com') + .put('service.OpenID.scopes', 'email email_verified name zoneinfo') + .put('0xFlowToken', '0x7e60df042a9c0868'); +``` + +### Using `flow.json` for Contract Imports + +A simpler and more flexible way to manage contract imports in scripts and transactions is by using the `config.load` method in FCL. This lets you load contract configurations from a `flow.json` file, keeping your import syntax clean and allowing FCL to pick the correct contract addresses based on the network you're using. + +#### 1. Define Your Contracts in `flow.json` + +Here’s an example of a `flow.json` file with aliases for multiple networks: + +```json +{ + "contracts": { + "HelloWorld": { + "source": "./cadence/contracts/HelloWorld.cdc", + "aliases": { + "testnet": "0x1cf0e2f2f715450", + "mainnet": "0xf8d6e0586b0a20c7" + } + } + } +} +``` + +- **`source`**: Points to the contract file in your project. +- **`aliases`**: Maps each network to the correct contract address. + +#### 2. Configure FCL + +Load the `flow.json` file and set up FCL to use it: + +```javascript +import { config } from '@onflow/fcl'; +import flowJSON from '../flow.json'; + +config({ + 'flow.network': 'testnet', // Choose your network, e.g., testnet or mainnet + 'accessNode.api': 'https://rest-testnet.onflow.org', // Access node for the network + 'discovery.wallet': `https://fcl-discovery.onflow.org/testnet/authn`, // Wallet discovery +}).load({ flowJSON }); +``` + +With this setup, FCL will automatically use the correct contract address based on the selected network (e.g., `testnet` or `mainnet`). + +#### 3. Use Contract Names in Scripts and Transactions + +After setting up `flow.json`, you can import contracts by name in your Cadence scripts or transactions: + +```cadence +import "HelloWorld" + +access(all) fun main(): String { + return HelloWorld.sayHello() +} +``` + +FCL replaces `"HelloWorld"` with the correct address from the `flow.json` configuration. + +> **Note**: Don’t store private keys in your `flow.json`. Instead, keep sensitive keys in a separate, `.gitignore`-protected file. + +## API Reference + +This section contains documentation for all of the functions and namespaces in the fcl package. + +- [account](./account.md) - Retrieve any account from Flow network's latest block or from a specified block... +- [arg](./arg.md) - A utility builder to be used with fcl.args[...] to create FCL supported... +- [args](./args.md) - A utility builder to be used with other builders to pass in arguments with a... +- [atBlockHeight](./atBlockHeight.md) - A builder function that returns a partial interaction to a block at a specific... +- [atBlockId](./atBlockId.md) - A builder function that returns a partial interaction to a block at a specific... +- [authenticate](./authenticate.md) - Calling this method will authenticate the current user via any wallet that... +- [authorization](./authorization.md) - Creates an authorization function for use in transactions. An authorization... +- [authorizations](./authorizations.md) - A utility builder to set the authorizations on a transaction. Authorizations... +- [authz](./authz.md) - A convenience method that produces the needed authorization details for the... +- [block](./block.md) - Query the network for block by id, height or get the latest block. Block ID is... +- [build](./build.md) - A builder function that creates an interaction from an array of builder... +- [cadence](./cadence.md) - Creates a template function +- [cdc](./cdc.md) - Creates a template function +- [config](./config.md) - Sets the config +- [createSignableVoucher](./createSignableVoucher.md) - Creates a signable voucher object from an interaction for signing purposes. A... +- [currentUser](./currentUser.md) - The main current user service for managing user authentication and authorization... +- [decode](./decode.md) - Decodes the response from 'fcl.send()' into the appropriate JSON representation... +- [display](./display.md) - Adds 0x to address if not already present +- [events](./events.md) - Subscribes to Flow blockchain events in real-time. This function provides a way... +- [getAccount](./getAccount.md) - A builder function that returns the interaction to get an account by address.... +- [getBlock](./getBlock.md) - A builder function that returns the interaction to get the latest block. Use... +- [getBlockHeader](./getBlockHeader.md) - A builder function that returns the interaction to get a block header. A block... +- [getChainId](./getChainId.md) - Gets the chain ID if its set, otherwise gets the chain ID from the access node +- [getCollection](./getCollection.md) - A builder function that returns a collection containing a list of transaction... +- [getEvents](./getEvents.md) - A builder function that returns the interaction to get events. Events are... +- [getEventsAtBlockHeightRange](./getEventsAtBlockHeightRange.md) - A builder function that returns all instances of a particular event (by name)... +- [getEventsAtBlockIds](./getEventsAtBlockIds.md) - A builder function that returns all instances of a particular event (by name)... +- [getNetworkParameters](./getNetworkParameters.md) - A builder function that returns the interaction to get network parameters.... +- [getNodeVersionInfo](./getNodeVersionInfo.md) - A builder function for the Get Node Version Info interaction. Creates an... +- [getTransaction](./getTransaction.md) - A builder function that returns the interaction to get a transaction by id.... +- [getTransactionStatus](./getTransactionStatus.md) - A builder function that returns the status of transaction. The transaction id... +- [invariant](./invariant.md) +- [isBad](./isBad.md) - Checks if an interaction has a failed status. +- [isOk](./isOk.md) - Checks if an interaction has a successful status. +- [limit](./limit.md) - A utility builder to set the compute limit on a transaction. The compute limit... +- [logIn](./logIn.md) - A convenience method that calls and is equivalent to `fcl.authenticate()`. This... +- [mutate](./mutate.md) - A transaction execution function that allows you to submit Cadence transactions... +- [nodeVersionInfo](./nodeVersionInfo.md) - Retrieve version information from the connected Flow Access Node. This function... +- [param](./param.md) - Legacy function for setting a single parameter on an interaction. +- [params](./params.md) - Legacy function for setting parameters on an interaction. +- [payer](./payer.md) - A builder function that adds payer account(s) to a transaction. Every... +- [ping](./ping.md) - A builder function that creates a ping interaction to test connectivity to the... +- [pipe](./pipe.md) - Async pipe function to compose interactions. The pipe function is the foundation... +- [pluginRegistry](./pluginRegistry.md) - Global plugin registry instance for managing FCL plugins. This registry handles... +- [proposer](./proposer.md) - A builder function that adds the proposer to a transaction. The proposer is... +- [query](./query.md) - Allows you to submit scripts to query the blockchain. +- [queryRaw](./queryRaw.md) - Allows you to submit scripts to query the blockchain and get raw response data. +- [reauthenticate](./reauthenticate.md) - A convenience method that calls `fcl.unauthenticate()` and then `fcl.authenticat... +- [ref](./ref.md) - A builder function that sets the reference block for a transaction. The... +- [sansPrefix](./sansPrefix.md) - Removes 0x from address if present +- [script](./script.md) - A builder function that creates a script interaction. Scripts allow you to write... +- [send](./send.md) - Sends arbitrary scripts, transactions, and requests to Flow. This method... +- [serialize](./serialize.md) - Serializes a Flow transaction or script to a JSON-formatted signable voucher... +- [signUp](./signUp.md) - A convenience method that calls and is equivalent to `fcl.authenticate()`. This... +- [subscribe](./subscribe.md) - Subscribe to real-time data from the Flow blockchain and automatically decode... +- [subscribeEvents](./subscribeEvents.md) - Subscribe to events with the given filter and parameters. Creates a subscription... +- [subscribeRaw](./subscribeRaw.md) - Subscribe to a topic without decoding the data. This function creates a raw... +- [transaction](./transaction.md) - A template builder to use a Cadence transaction for an interaction. FCL "mutate"... +- [tx](./tx.md) - Creates a transaction monitor that provides methods for tracking and subscribing... +- [unauthenticate](./unauthenticate.md) - Logs out the current user and sets the values on the current user object to... +- [validator](./validator.md) - A builder function that adds a validator to a transaction. Validators are... +- [verifyUserSignatures](./verifyUserSignatures.md) - Verify a valid signature/s for an account on Flow. +- [voucherIntercept](./voucherIntercept.md) - A builder function that intercepts and modifies a voucher. This function is... +- [voucherToTxId](./voucherToTxId.md) - Converts a voucher object to a transaction ID. This function computes the... +- [why](./why.md) - Returns the reason for an interaction failure. +- [withPrefix](./withPrefix.md) - Adds 0x to address if not already present + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/invariant.md b/docs/tools/clients/fcl-js/packages-docs/fcl/invariant.md new file mode 100644 index 0000000000..041d473981 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/invariant.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +title: "invariant" +description: "invariant function documentation." +--- + + + +# invariant + + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.invariant(args) +``` + +Or import directly the specific function: + +```typescript +import { invariant } from "@onflow/fcl" + +invariant(args) +``` + + +## Parameters + +### `args` (optional) + + +- Type: `any[]` + + +## Returns + +```typescript +(ix: any) => any +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/isBad.md b/docs/tools/clients/fcl-js/packages-docs/fcl/isBad.md new file mode 100644 index 0000000000..a0d0d7cf8e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/isBad.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 1 +title: "isBad" +description: "isBad function documentation." +--- + + + +# isBad + +Checks if an interaction has a failed status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.isBad(ix) +``` + +Or import directly the specific function: + +```typescript +import { isBad } from "@onflow/fcl" + +isBad(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isBad, why } from "@onflow/sdk" + +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isBad(response)) { + console.log("Transaction failed:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is BAD, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/isOk.md b/docs/tools/clients/fcl-js/packages-docs/fcl/isOk.md new file mode 100644 index 0000000000..b6e8492fa3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/isOk.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "isOk" +description: "isOk function documentation." +--- + + + +# isOk + +Checks if an interaction has a successful status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.isOk(ix) +``` + +Or import directly the specific function: + +```typescript +import { isOk } from "@onflow/fcl" + +isOk(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isOk } from "@onflow/sdk" + +// Check if a transaction was successful +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isOk(response)) { + console.log("Transaction was successful"); +} else { + console.log("Transaction failed"); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is OK, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/limit.md b/docs/tools/clients/fcl-js/packages-docs/fcl/limit.md new file mode 100644 index 0000000000..0dd376ff83 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/limit.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "limit" +description: "limit function documentation." +--- + + + +# limit + +A utility builder to set the compute limit on a transaction. + +The compute limit is the maximum amount of computation that can be performed during transaction execution. +Setting an appropriate compute limit helps prevent infinite loops and ensures predictable transaction costs. + +Read more about [computation cost](https://docs.onflow.org/concepts/fees/#computation-cost) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.limit(limit) +``` + +Or import directly the specific function: + +```typescript +import { limit } from "@onflow/fcl" + +limit(limit) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + // Complex transaction logic here + } + } + `, + limit: 1000 // Set compute limit to 1000 +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.limit(9999) // Set higher limit for complex operations +]); +``` + +## Parameters + +### `limit` + + +- Type: `number` +- Description: The maximum amount of computation for the transaction + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/logIn.md b/docs/tools/clients/fcl-js/packages-docs/fcl/logIn.md new file mode 100644 index 0000000000..7699d7d7d4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/logIn.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "logIn" +description: "logIn function documentation." +--- + + + +# logIn + +A convenience method that calls and is equivalent to `fcl.authenticate()`. + +This method can only be used in web browsers. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.logIn(opts) +``` + +Or import directly the specific function: + +```typescript +import { logIn } from "@onflow/fcl" + +logIn(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; +fcl.config() + .put('accessNode.api', 'https://rest-testnet.onflow.org') + .put('discovery.wallet', 'https://fcl-discovery.onflow.org/testnet/authn'); + +// User clicks log in button +fcl.logIn(); +``` + +## Parameters + +### `opts` (optional) + + +- Type: `{}` +- Description: Authentication options passed to authenticate method + + +## Returns + +[`Promise`](../types#currentuser) + + +Promise that resolves to the authenticated CurrentUser object or undefined + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/mutate.md b/docs/tools/clients/fcl-js/packages-docs/fcl/mutate.md new file mode 100644 index 0000000000..27fe51a58f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/mutate.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: "mutate" +description: "mutate function documentation." +--- + + + +# mutate + +A transaction execution function that allows you to submit Cadence transactions to the Flow blockchain +to mutate on-chain state. This function handles the complete transaction lifecycle including building, signing, and +sending transactions to Flow. It provides a high-level interface that abstracts the complexity of transaction +construction while offering flexibility for advanced use cases. + +The mutate function automatically handles authorization using the current authenticated user by default, but allows +for custom authorization functions to be specified for different transaction roles (proposer, payer, authorizer). +It supports both simple single-party transactions and complex multi-party transactions with different signatories. + +This function integrates with FCL's address replacement system, allowing you to use placeholder addresses in your +Cadence code that are replaced with actual addresses at execution time. It also supports Interaction Templates +for standardized transaction execution patterns. + +The mutate function accepts a configuration object with the following structure: +```typescript +{ +cadence?: string, // The Cadence transaction code to execute (required if template not provided) +args?: Function, // Function that returns an array of arguments for the transaction +template?: any, // Interaction Template object or URL for standardized transactions +limit?: number, // Compute (gas) limit for the transaction execution +authz?: AccountAuthorization, // Authorization function for all signatory roles (proposer, payer, authorizer) +proposer?: AccountAuthorization, // Specific authorization function for the proposer role +payer?: AccountAuthorization, // Specific authorization function for the payer role +authorizations?: AccountAuthorization[] // Array of authorization functions for authorizer roles +} +``` + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.mutate(opts) +``` + +Or import directly the specific function: + +```typescript +import { mutate } from "@onflow/fcl" + +mutate(opts) +``` + +## Usage + +```typescript +// Basic transaction submission +import * as fcl from "@onflow/fcl" + +// Configure FCL first +fcl.config({ + "accessNode.api": "https://rest-testnet.onflow.org", + "discovery.wallet": "https://fcl-discovery.onflow.org/testnet/authn", + "flow.network": "testnet" +}) + +// Authenticate user +await fcl.authenticate() + +// Submit a basic transaction +const txId = await fcl.mutate({ + cadence: ` + transaction(message: String) { + prepare(account: AuthAccount) { + log("Transaction executed by: ".concat(account.address.toString())) + log("Message: ".concat(message)) + } + } + `, + args: (arg, t) => [ + arg("Hello Flow!", t.String) + ], + limit: 50 +}) + +console.log("Transaction submitted:", txId) +``` + +## Parameters + +### `opts` + + +- Type: `any` +- Description: Transaction configuration options + + +## Returns + +```typescript +(opts?: MutateOptions) => Promise +``` + + +Promise that resolves to the transaction ID (txId) when the transaction is submitted + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/nodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/fcl/nodeVersionInfo.md new file mode 100644 index 0000000000..fe7439024c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/nodeVersionInfo.md @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +title: "nodeVersionInfo" +description: "nodeVersionInfo function documentation." +--- + + + +# nodeVersionInfo + +Retrieve version information from the connected Flow Access Node. + +This function returns detailed information about the Flow node's version, including the protocol version, spork information, and node-specific details. This is useful for debugging, compatibility checks, and understanding the network state. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.nodeVersionInfo(opts) +``` + +Or import directly the specific function: + +```typescript +import { nodeVersionInfo } from "@onflow/fcl" + +nodeVersionInfo(opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information +const versionInfo = await fcl.nodeVersionInfo(); +console.log(versionInfo); +// { +// semver: "v0.37.13", +// commit: "12345abcd", +// spork_id: "mainnet-23", +// protocol_version: "2.13.10", +// spork_root_block_height: "88483760", +// node_root_block_height: "88483760" +// } + +// Check compatibility +const info = await fcl.nodeVersionInfo(); +if (info.protocol_version.startsWith("2.13")) { + console.log("Compatible with current protocol version"); +} +``` + +## Parameters + +### `opts` (optional) + + +- Type: `any` +- Description: Optional parameters for the request + + +## Returns + +[`Promise`](../types#nodeversioninfo) + + +A promise that resolves to a block response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/param.md b/docs/tools/clients/fcl-js/packages-docs/fcl/param.md new file mode 100644 index 0000000000..747a9cfd79 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/param.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "param" +description: "param function documentation." +--- + + + +# param + +Legacy function for setting a single parameter on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.param(params) +``` + +Or import directly the specific function: + +```typescript +import { param } from "@onflow/fcl" + +param(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameter to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/params.md b/docs/tools/clients/fcl-js/packages-docs/fcl/params.md new file mode 100644 index 0000000000..696cac9d04 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/params.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "params" +description: "params function documentation." +--- + + + +# params + +Legacy function for setting parameters on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.params(params) +``` + +Or import directly the specific function: + +```typescript +import { params } from "@onflow/fcl" + +params(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameters to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/payer.md b/docs/tools/clients/fcl-js/packages-docs/fcl/payer.md new file mode 100644 index 0000000000..104f335911 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/payer.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "payer" +description: "payer function documentation." +--- + + + +# payer + +A builder function that adds payer account(s) to a transaction. + +Every transaction requires at least one payer. + +The payer is the account that pays the transaction fee for executing the transaction on the network. +The payer account must have sufficient Flow tokens to cover the transaction fees. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#payer) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.payer(ax) +``` + +Or import directly the specific function: + +```typescript +import { payer } from "@onflow/fcl" + +payer(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using current user as payer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Transaction fees paid by: ".concat(acct.address.toString())) + } + } + `, + payer: fcl.authz // Current user as payer +}); + +// Using custom payer with builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.proposer(fcl.authz), // Current user as proposer + fcl.authorizations([fcl.authz]), // Current user as authorizer + fcl.payer(customPayerAuthz) // Custom payer pays fees +]); + +// Multiple payers (advanced use case) +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.payer([payerAuthz1, payerAuthz2]) // Multiple payers split fees +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An account address or an array of account addresses + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that takes an interaction object and returns a new interaction object with the payer(s) added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/ping.md b/docs/tools/clients/fcl-js/packages-docs/fcl/ping.md new file mode 100644 index 0000000000..97d7fb28ea --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/ping.md @@ -0,0 +1,72 @@ +--- +sidebar_position: 1 +title: "ping" +description: "ping function documentation." +--- + + + +# ping + +A builder function that creates a ping interaction to test connectivity to the Flow Access Node. + +The ping interaction is a simple way to test if the Flow Access Node is reachable and responding. This is useful for health checks, connectivity testing, and debugging network issues. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.ping() +``` + +Or import directly the specific function: + +```typescript +import { ping } from "@onflow/fcl" + +ping() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple ping to test connectivity +try { + const response = await fcl.send([fcl.ping()]); + console.log("Access Node is reachable"); +} catch (error) { + console.error("Access Node is not reachable:", error); +} + +// Use ping for health checks +const healthCheck = async () => { + try { + await fcl.send([fcl.ping()]); + return { status: "healthy", timestamp: new Date().toISOString() }; + } catch (error) { + return { status: "unhealthy", error: error.message, timestamp: new Date().toISOString() }; + } +}; + +const health = await healthCheck(); +console.log("Health status:", health); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/pipe.md b/docs/tools/clients/fcl-js/packages-docs/fcl/pipe.md new file mode 100644 index 0000000000..60237acdb3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/pipe.md @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +title: "pipe" +description: "pipe function documentation." +--- + + + +# pipe + +Async pipe function to compose interactions. + +The pipe function is the foundation for composing multiple interaction builder functions together. +It sequentially applies builder functions to an interaction, allowing for complex interaction construction. +Each function in the pipe receives the result of the previous function and can modify or validate the interaction. + +Pipe has two main forms: +1. `pipe(builderFunctions)`: Returns a builder function +2. `pipe(interaction, builderFunctions)`: Directly executes the pipe on an interaction + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.pipe(fns) +``` + +Or import directly the specific function: + +```typescript +import { pipe } from "@onflow/fcl" + +pipe(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using pipe to create a reusable builder +const myTransactionBuilder = fcl.pipe([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Use the builder +const interaction = await fcl.build([myTransactionBuilder]); + +// Pipe is used internally by build() and send() +await fcl.send([ + fcl.script`access(all) fun main(): Int { return 42 }` +]); // This uses pipe internally +``` + +## Parameters + +### `fns` + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: Array of builder functions to apply + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +An interaction builder function when called with just functions, or a Promise<Interaction> when called with an interaction and functions + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/pluginRegistry.md b/docs/tools/clients/fcl-js/packages-docs/fcl/pluginRegistry.md new file mode 100644 index 0000000000..097d569628 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/pluginRegistry.md @@ -0,0 +1,54 @@ +--- +sidebar_position: 1 +title: "pluginRegistry" +description: "pluginRegistry function documentation." +--- + + + +# pluginRegistry + +Global plugin registry instance for managing FCL plugins. This registry handles +the registration and management of various FCL plugins including service plugins that add +new wallet services and strategies. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.pluginRegistry() +``` + +Or import directly the specific function: + +```typescript +import { pluginRegistry } from "@onflow/fcl" + +pluginRegistry() +``` + +## Usage + +```typescript +// Add a plugin to the registry +pluginRegistry.add({ + name: "MyWalletPlugin", + f_type: "ServicePlugin", + type: "discovery-service", + services: [...], + serviceStrategy: { method: "CUSTOM/RPC", exec: customExecFunction } +}) +``` + + +## Returns + +```typescript +Readonly<{ add: (plugins: any) => void; getPlugins: () => Map; }> +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/proposer.md b/docs/tools/clients/fcl-js/packages-docs/fcl/proposer.md new file mode 100644 index 0000000000..7b8e6ae203 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/proposer.md @@ -0,0 +1,94 @@ +--- +sidebar_position: 1 +title: "proposer" +description: "proposer function documentation." +--- + + + +# proposer + +A builder function that adds the proposer to a transaction. + +The proposer is responsible for providing the proposal key and paying the network fee for the transaction. +The proposer key is used to specify the sequence number and prevent replay attacks. + +Every transaction requires exactly one proposer. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#proposer) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.proposer(authz) +``` + +Or import directly the specific function: + +```typescript +import { proposer } from "@onflow/fcl" + +proposer(authz) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using the current user as proposer +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + log("Hello from proposer!") + } + } + `, + proposer: fcl.authz +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `authz` + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: The authorization object for the proposer + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction object and returns a new interaction object with the proposer added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/query.md b/docs/tools/clients/fcl-js/packages-docs/fcl/query.md new file mode 100644 index 0000000000..da46988cf6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/query.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "query" +description: "query function documentation." +--- + + + +# query + +Allows you to submit scripts to query the blockchain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.query(opts) +``` + +Or import directly the specific function: + +```typescript +import { query } from "@onflow/fcl" + +query(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface QueryOptions { + cadence?: string + args?: ArgsFn + template?: any + isSealed?: boolean + limit?: number +} +``` +- Description: Query options configuration + + +## Returns + +`Promise` + + +A JSON representation of the response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/queryRaw.md b/docs/tools/clients/fcl-js/packages-docs/fcl/queryRaw.md new file mode 100644 index 0000000000..4c21f7a110 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/queryRaw.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "queryRaw" +description: "queryRaw function documentation." +--- + + + +# queryRaw + +Allows you to submit scripts to query the blockchain and get raw response data. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.queryRaw(opts) +``` + +Or import directly the specific function: + +```typescript +import { queryRaw } from "@onflow/fcl" + +queryRaw(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; + +const result = await fcl.queryRaw({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +export interface QueryOptions { + cadence?: string + args?: ArgsFn + template?: any + isSealed?: boolean + limit?: number +} +``` +- Description: Query Options and configuration + + +## Returns + +`Promise` + + +A promise that resolves to the raw query result + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/reauthenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl/reauthenticate.md new file mode 100644 index 0000000000..5012ba905d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/reauthenticate.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 1 +title: "reauthenticate" +description: "reauthenticate function documentation." +--- + + + +# reauthenticate + +A convenience method that calls `fcl.unauthenticate()` and then `fcl.authenticate()` for the current user. + +This method can only be used in web browsers. + +The current user must be authenticated first. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.reauthenticate(opts) +``` + +Or import directly the specific function: + +```typescript +import { reauthenticate } from "@onflow/fcl" + +reauthenticate(opts) +``` + +## Usage + +```typescript +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 +``` + +## Parameters + +### `opts` (optional) + + +- Type: `{}` +- Description: Authentication options passed to authenticate method + + +## Returns + +[`Promise`](../types#currentuser) + + +Promise that resolves to the authenticated CurrentUser object or undefined + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/ref.md b/docs/tools/clients/fcl-js/packages-docs/fcl/ref.md new file mode 100644 index 0000000000..40e4bc263c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/ref.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "ref" +description: "ref function documentation." +--- + + + +# ref + +A builder function that sets the reference block for a transaction. + +The 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.ref(refBlock) +``` + +Or import directly the specific function: + +```typescript +import { ref } from "@onflow/fcl" + +ref(refBlock) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Set specific reference block for transaction +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction with custom reference block") + } + } + `, + fcl.ref("a1b2c3d4e5f6789..."), // Custom reference block ID + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Usually, you don't need to set reference block manually +// as FCL will automatically set it to the latest block +``` + +## Parameters + +### `refBlock` + + +- Type: `string` +- Description: The reference block ID + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/sansPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl/sansPrefix.md new file mode 100644 index 0000000000..5c82f4f229 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/sansPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "sansPrefix" +description: "sansPrefix function documentation." +--- + + + +# sansPrefix + +Removes 0x from address if present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.sansPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { sansPrefix } from "@onflow/fcl" + +sansPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address without 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/script.md b/docs/tools/clients/fcl-js/packages-docs/fcl/script.md new file mode 100644 index 0000000000..a48a7ad9d0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/script.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "script" +description: "script function documentation." +--- + + + +# script + +A builder function that creates a script interaction. Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. + +You can learn more about [Cadence here](https://cadence-lang.org/docs/language), 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.script(args) +``` + +Or import directly the specific function: + +```typescript +import { script } from "@onflow/fcl" + +script(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray | ((x?: unknown) => string), ...unknown[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/send.md b/docs/tools/clients/fcl-js/packages-docs/fcl/send.md new file mode 100644 index 0000000000..7210518ab8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/send.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "send" +description: "send function documentation." +--- + + + +# 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. + +WARNING: Must be used in conjunction with 'fcl.decode(response)' to get back correct keys and all values in JSON. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.send(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { send } from "@onflow/fcl" + +send(args, opts) +``` + +## Usage + +```typescript +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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +false | Function | (false | Function)[] +``` +- Description: An array of builders (functions that take an interaction object and return a new interaction object) + +### `opts` (optional) + + +- Type: `any` +- Description: Additional optional options for the request + + +## Returns + +`Promise` + + +A promise that resolves to a ResponseObject containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/serialize.md b/docs/tools/clients/fcl-js/packages-docs/fcl/serialize.md new file mode 100644 index 0000000000..51d52180e3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/serialize.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "serialize" +description: "serialize function documentation." +--- + + + +# serialize + +Serializes a Flow transaction or script to a JSON-formatted signable voucher that can be +used for offline signing or inspection. This is useful for creating signable transactions that can be +signed by external wallets or hardware devices. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.serialize(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { serialize } from "@onflow/fcl" + +serialize(args, opts) +``` + +## Usage + +```typescript +// Serialize a simple transaction +import * as fcl from "@onflow/fcl" + +const voucher = await fcl.serialize([ + fcl.transaction` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // Transaction logic here + } + } + `, + fcl.args([ + fcl.arg("10.0", fcl.t.UFix64), + fcl.arg("0x01", fcl.t.Address) + ]), + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]) +``` + +## Parameters + +### `args` + + +- Type: `(false` | `InteractionBuilderFn)[]` | [`Interaction`](../types#interaction) +- Description: Array of interaction builder functions or a pre-built interaction object. Builder functions are typically from + +### `opts` (optional) + + +- Type: +```typescript +export interface SerializeOptions { + resolve?: InteractionBuilderFn +} +``` +- Description: Optional configuration object + + +## Returns + +`Promise` + + +A JSON string representation of the signable voucher that contains all +the transaction details needed for signing + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/signUp.md b/docs/tools/clients/fcl-js/packages-docs/fcl/signUp.md new file mode 100644 index 0000000000..9dbad30eea --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/signUp.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "signUp" +description: "signUp function documentation." +--- + + + +# signUp + +A convenience method that calls and is equivalent to `fcl.authenticate()`. + +This method can only be used in web browsers. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.signUp(opts) +``` + +Or import directly the specific function: + +```typescript +import { signUp } from "@onflow/fcl" + +signUp(opts) +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; +fcl.config() + .put('accessNode.api', 'https://rest-testnet.onflow.org') + .put('discovery.wallet', 'https://fcl-discovery.onflow.org/testnet/authn'); + +// User clicks sign up button +fcl.signUp(); +``` + +## Parameters + +### `opts` (optional) + + +- Type: `{}` +- Description: Authentication options passed to authenticate method + + +## Returns + +[`Promise`](../types#currentuser) + + +Promise that resolves to the authenticated CurrentUser object or undefined + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/subscribe.md b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribe.md new file mode 100644 index 0000000000..29727c1ac0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribe.md @@ -0,0 +1,101 @@ +--- +sidebar_position: 1 +title: "subscribe" +description: "subscribe function documentation." +--- + + + +# subscribe + +Subscribe to real-time data from the Flow blockchain and automatically decode the responses. + +This is a utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the 'decode' function. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.subscribe(subscribeParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribe } from "@onflow/fcl" + +subscribe(subscribeParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to events +const subscription = fcl.subscribe({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (events) => { + console.log("Received events:", events); + }, + onError: (error) => { + console.error("Subscription error:", error); + } +}); + +// Subscribe to blocks +const blockSubscription = fcl.subscribe({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (block) => { + console.log("New block:", block); + }, + onError: (error) => { + console.error("Block subscription error:", error); + } +}); + +// Later, to unsubscribe: +subscription.unsubscribe(); +blockSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeParams` + + +- Type: +```typescript +SubscribeParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +[`Subscription`](../types#subscription) + + +A subscription object that allows you to manage the subscription (e.g., to unsubscribe later) + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeEvents.md b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeEvents.md new file mode 100644 index 0000000000..6dec393bb2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeEvents.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "subscribeEvents" +description: "subscribeEvents function documentation." +--- + + + +# subscribeEvents + +Subscribe to events with the given filter and parameters. + +Creates a subscription to listen for real-time events from the Flow blockchain. This function configures +the subscription parameters for filtering specific events based on type, addresses, contracts, and other criteria. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened. +Subscriptions allow you to listen for these events in real-time without polling. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.subscribeEvents(eventFilter) +``` + +Or import directly the specific function: + +```typescript +import { subscribeEvents } from "@onflow/fcl" + +subscribeEvents(eventFilter) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Subscribe to FlowToken transfer events +const subscription = await fcl.send([ + fcl.subscribeEvents({ + eventTypes: [ + "A.1654653399040a61.FlowToken.TokensWithdrawn", + "A.1654653399040a61.FlowToken.TokensDeposited" + ], + startHeight: 1000000, // Start from specific block height + heartbeatInterval: 3000 // 3 second heartbeat + }) +]); + +// Subscribe to events from specific contracts +const contractSubscription = await fcl.send([ + fcl.subscribeEvents({ + contracts: ["FlowToken", "FungibleToken"], + addresses: ["0x1654653399040a61"] + }) +]); + +// Handle the subscription data elsewhere using fcl.subscribe() +``` + +## Parameters + +### `eventFilter` + + +- Type: [`EventFilter`](../types#eventfilter) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeRaw.md b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeRaw.md new file mode 100644 index 0000000000..3bb46bd821 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/subscribeRaw.md @@ -0,0 +1,105 @@ +--- +sidebar_position: 1 +title: "subscribeRaw" +description: "subscribeRaw function documentation." +--- + + + +# subscribeRaw + +Subscribe to a topic without decoding the data. + +This function creates a raw subscription to Flow blockchain data streams without automatic decoding. +It's useful when you need more control over data processing or want to handle raw responses directly. +For most use cases, consider using the `subscribe()` function instead which provides automatic decoding. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.subscribeRaw(subscribeRawParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribeRaw } from "@onflow/fcl" + +subscribeRaw(subscribeRawParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to raw event data without automatic decoding +const rawSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (rawData) => { + console.log("Raw event data:", rawData); + // Handle raw data manually - no automatic decoding + }, + onError: (error) => { + console.error("Raw subscription error:", error); + } +}); + +// Subscribe to raw block data +const blockSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (rawBlock) => { + console.log("Raw block data:", rawBlock); + }, + onError: (error) => { + console.error("Error:", error); + } +}); + +// Unsubscribe when done +rawSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeRawParams` + + +- Type: +```typescript +SubscribeRawParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +```typescript +{ unsubscribe: () => void; } +``` + + +A subscription object with an unsubscribe method + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/transaction.md b/docs/tools/clients/fcl-js/packages-docs/fcl/transaction.md new file mode 100644 index 0000000000..b612f4751b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/transaction.md @@ -0,0 +1,104 @@ +--- +sidebar_position: 1 +title: "transaction" +description: "transaction function documentation." +--- + + + +# transaction + +A template builder to use a Cadence transaction for an interaction. FCL "mutate" does the work of building, signing, and sending a transaction behind the scenes. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.transaction(args) +``` + +Or import directly the specific function: + +```typescript +import { transaction } from "@onflow/fcl" + +transaction(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +// Basic transaction usage +await fcl.mutate({ + cadence: ` + transaction(a: Int) { + prepare(acct: &Account) { + log(acct) + log(a) + } + } + `, + args: (arg, t) => [ + arg(6, t.Int) + ], + limit: 50 +}) + +// Single party, single signature +// Proposer, payer and authorizer are the same account +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + authz: currentUser, // Optional. Will default to currentUser if not provided. + limit: 50, +}) + +// Multiple parties +// Proposer and authorizer are the same account, but different payer +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + proposer: authzFn, + payer: authzTwoFn, + authorizations: [authzFn], + limit: 50, +}) +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray, ...any[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/tx.md b/docs/tools/clients/fcl-js/packages-docs/fcl/tx.md new file mode 100644 index 0000000000..f6522606b4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/tx.md @@ -0,0 +1,120 @@ +--- +sidebar_position: 1 +title: "tx" +description: "tx function documentation." +--- + + + +# tx + +Creates a transaction monitor that provides methods for tracking and subscribing to +transaction status updates on the Flow blockchain. This function returns an object with methods +to get snapshots, subscribe to status changes, and wait for specific transaction states. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.tx(transactionId, opts) +``` + +Or import directly the specific function: + +```typescript +import { tx } from "@onflow/fcl" + +tx(transactionId, opts) +``` + +## Usage + +```typescript +// Basic transaction monitoring +import * as fcl from "@onflow/fcl" + +const txId = await fcl.mutate({ + cadence: ` + transaction { + execute { log("Hello, World!") } + } + ` +}) + +// Get current status +const status = await fcl.tx(txId).snapshot() +console.log("Current status:", status.status) + +// Subscribe to all status changes +const unsubscribe = fcl.tx(txId).subscribe((status) => { + console.log("Status update:", status.status) + if (status.status === fcl.transaction.isSealed) { + console.log("Transaction sealed!") + console.log("Events:", status.events) + } +}) +// Clean up subscription when done +setTimeout(() => unsubscribe(), 60000) + +// Wait for specific transaction states +try { + // Wait for finalization (consensus reached) + const finalizedStatus = await fcl.tx(txId).onceFinalized() + console.log("Transaction finalized") + + // Wait for execution (transaction executed) + const executedStatus = await fcl.tx(txId).onceExecuted() + console.log("Transaction executed") + + // Wait for sealing (transaction sealed in block) + const sealedStatus = await fcl.tx(txId).onceSealed() + console.log("Transaction sealed:", sealedStatus.events) +} catch (error) { + console.error("Transaction failed:", error.message) +} + +// Handle transaction errors +fcl.tx(txId).subscribe( + (status) => { + if (status.statusCode === 1) { + console.error("Transaction error:", status.errorMessage) + } + }, + (error) => { + console.error("Subscription error:", error) + } +) +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The 64-character hex transaction ID to monitor. Must be a valid +Flow transaction hash (64 bytes represented as hex string). + +### `opts` (optional) + + +- Type: +```typescript +{ pollRate?: number; txNotFoundTimeout?: number; } +``` +- Description: Optional configuration parameters + + +## Returns + +```typescript +{ snapshot: () => Promise; subscribe: (onData: (txStatus: TransactionStatus) => void, onError?: (err: Error) => void) => () => void; onceFinalized: () => Promise; onceExecuted: () => Promise; onceSealed: () => Promise; } +``` + + +Transaction monitor object with methods for tracking transaction status + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/unauthenticate.md b/docs/tools/clients/fcl-js/packages-docs/fcl/unauthenticate.md new file mode 100644 index 0000000000..8596856b71 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/unauthenticate.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "unauthenticate" +description: "unauthenticate function documentation." +--- + + + +# unauthenticate + +Logs out the current user and sets the values on the current user object to null. + +This method can only be used in web browsers. + +The current user must be authenticated first. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.unauthenticate() +``` + +Or import directly the specific function: + +```typescript +import { unauthenticate } from "@onflow/fcl" + +unauthenticate() +``` + +## Usage + +```typescript +import * as fcl from '@onflow/fcl'; +fcl.config().put('accessNode.api', 'https://rest-testnet.onflow.org'); +// first authenticate to set current user +fcl.authenticate(); +// ... somewhere else & sometime later +fcl.unauthenticate(); +// fcl.currentUser.loggedIn === null +``` + + +## Returns + +`void` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/validator.md b/docs/tools/clients/fcl-js/packages-docs/fcl/validator.md new file mode 100644 index 0000000000..6b9874a2bf --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/validator.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "validator" +description: "validator function documentation." +--- + + + +# validator + +A builder function that adds a validator to a transaction. + +Validators are functions that run during transaction building to check for invalid configurations or parameters. +They help catch errors early before submitting transactions to the network, preventing failed transactions +and wasted compute costs. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.validator(cb) +``` + +Or import directly the specific function: + +```typescript +import { validator } from "@onflow/fcl" + +validator(cb) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Custom validator to ensure account has sufficient balance +const validateBalance = (ix) => { + if (ix.message.computeLimit > 1000) { + throw new Error("Compute limit too high for this account"); + } + return ix; +}; + +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.validator(validateBalance), + fcl.limit(500) // This will pass validation +]); +``` + +## Parameters + +### `cb` + + +- Type: `Function` +- Description: The validator function that takes an interaction and returns it (or throws an error if invalid) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/verifyUserSignatures.md b/docs/tools/clients/fcl-js/packages-docs/fcl/verifyUserSignatures.md new file mode 100644 index 0000000000..4ce9c84836 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/verifyUserSignatures.md @@ -0,0 +1,40 @@ +--- +sidebar_position: 1 +title: "verifyUserSignatures" +description: "verifyUserSignatures function documentation." +--- + + + +# verifyUserSignatures + +Verify a valid signature/s for an account on Flow. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.verifyUserSignatures() +``` + +Or import directly the specific function: + +```typescript +import { verifyUserSignatures } from "@onflow/fcl" + +verifyUserSignatures() +``` + + + +## Returns + +```typescript +Promise | ((...args: any[]) => Promise>) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/voucherIntercept.md b/docs/tools/clients/fcl-js/packages-docs/fcl/voucherIntercept.md new file mode 100644 index 0000000000..167d9a0b0f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/voucherIntercept.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "voucherIntercept" +description: "voucherIntercept function documentation." +--- + + + +# voucherIntercept + +A builder function that intercepts and modifies a voucher. + +This function is useful for debugging, logging, or making modifications to +the transaction data. The voucher contains all the transaction details in their final form. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.voucherIntercept(fn) +``` + +Or import directly the specific function: + +```typescript +import { voucherIntercept } from "@onflow/fcl" + +voucherIntercept(fn) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Intercept voucher for logging +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.voucherIntercept((voucher) => { + console.log("Voucher details:", { + cadence: voucher.cadence, + proposalKey: voucher.proposalKey, + payer: voucher.payer, + authorizers: voucher.authorizers, + computeLimit: voucher.computeLimit + }); + }), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]) +]); +``` + +## Parameters + +### `fn` + + +- Type: +```typescript +type VoucherInterceptFn = (voucher: Voucher) => any | Promise +``` +- Description: The function to intercept and potentially modify the voucher + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/voucherToTxId.md b/docs/tools/clients/fcl-js/packages-docs/fcl/voucherToTxId.md new file mode 100644 index 0000000000..baf2779134 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/voucherToTxId.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: "voucherToTxId" +description: "voucherToTxId function documentation." +--- + + + +# voucherToTxId + +Converts a voucher object to a transaction ID. + +This function computes the transaction ID by encoding and hashing the voucher. +The transaction ID can be used to track the transaction status on the Flow network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.voucherToTxId(voucher) +``` + +Or import directly the specific function: + +```typescript +import { voucherToTxId } from "@onflow/fcl" + +voucherToTxId(voucher) +``` + +## Usage + +```typescript +import { voucherToTxId, createSignableVoucher } from "@onflow/sdk" +import * as fcl from "@onflow/fcl"; + +// Create a voucher from an interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Hello, Flow!") + } + } + `, + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]); + +const voucher = createSignableVoucher(interaction); + +// Calculate the transaction ID +const txId = voucherToTxId(voucher); +console.log("Transaction ID:", txId); +// Returns something like: "a1b2c3d4e5f6789..." + +// You can use this ID to track the transaction +const txStatus = await fcl.tx(txId).onceSealed(); +console.log("Transaction status:", txStatus); +``` + +## Parameters + +### `voucher` + + +- Type: +```typescript +export interface Voucher { + cadence: string + refBlock: string + computeLimit: number + arguments: VoucherArgument[] + proposalKey: VoucherProposalKey + payer: string + authorizers: string[] + payloadSigs: Sig[] + envelopeSigs: Sig[] +} +``` +- Description: The voucher object to convert + + +## Returns + +`string` + + +A transaction ID string + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/why.md b/docs/tools/clients/fcl-js/packages-docs/fcl/why.md new file mode 100644 index 0000000000..d9d8a1a3ab --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/why.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "why" +description: "why function documentation." +--- + + + +# why + +Returns the reason for an interaction failure. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.why(ix) +``` + +Or import directly the specific function: + +```typescript +import { why } from "@onflow/fcl" + +why(ix) +``` + +## Usage + +```typescript +import { Bad, why, initInteraction } from "@onflow/sdk" + +const interaction = Bad(initInteraction(), "Network timeout"); +console.log(why(interaction)); // "Network timeout" + +// Used with error handling +if (isBad(response)) { + console.error("Error occurred:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to get the failure reason from + + +## Returns + +`string` + + +The reason string or undefined if no reason is set + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/fcl/withPrefix.md b/docs/tools/clients/fcl-js/packages-docs/fcl/withPrefix.md new file mode 100644 index 0000000000..6d2ab122bc --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/fcl/withPrefix.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "withPrefix" +description: "withPrefix function documentation." +--- + + + +# withPrefix + +Adds 0x to address if not already present + +## Import + +You can import the entire package and access the function: + +```typescript +import * as fcl from "@onflow/fcl" + +fcl.withPrefix(address) +``` + +Or import directly the specific function: + +```typescript +import { withPrefix } from "@onflow/fcl" + +withPrefix(address) +``` + + +## Parameters + +### `address` + + +- Type: `null` +- Description: - Flow address + + +## Returns + +`null` + + +Flow address with 0x prefix + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/index.md b/docs/tools/clients/fcl-js/packages-docs/index.md new file mode 100644 index 0000000000..f2837f2ff2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/index.md @@ -0,0 +1,20 @@ +--- +sidebar_position: 1 +title: Packages Docs +description: Packages documentation. +--- + + + +# Packages Docs + +A list of all packages available inside Flow Client Library (FCL) with functions and type definitions. + +- [@onflow/fcl](./fcl/index.md) - High-level JavaScript/TypeScript library for building web applications on the Flow blockchain. +- [@onflow/fcl-core](./fcl-core/index.md) - Core JavaScript/TypeScript library providing shared functionality for Flow blockchain interactions. +- [@onflow/fcl-react-native](./fcl-react-native/index.md) - React Native JavaScript/TypeScript library for building mobile applications on the Flow blockchain. +- [@onflow/sdk](./sdk/index.md) - Low-level JavaScript/TypeScript SDK for interacting with the Flow blockchain. + +- [Type Definitions](./types/index.md) - Type definitions for the Flow Client Library (FCL) packages. + +--- diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/account.md b/docs/tools/clients/fcl-js/packages-docs/sdk/account.md new file mode 100644 index 0000000000..5819671cb6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/account.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "account" +description: "account function documentation." +--- + + + +# 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.account(address, accountQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { account } from "@onflow/sdk" + +account(address, accountQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get account from latest block height +const account = await fcl.account("0x1d007d755706c469"); +console.log("Address:", account.address); +console.log("Balance:", account.balance); +console.log("Keys:", account.keys); +console.log("Contracts:", Object.keys(account.contracts)); + +// Get account at a specific block height +const historicalAccount = await fcl.account("0x1d007d755706c469", { + height: 12345 +}); + +// Get account at a specific block ID +const accountAtBlock = await fcl.account("0x1d007d755706c469", { + id: "9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3" +}); + +// Get account from sealed block +const sealedAccount = await fcl.account("0x1d007d755706c469", { + isSealed: true +}); + +// Alternative using builder pattern +fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(123) +]).then(fcl.decode); +``` + +## Parameters + +### `address` + + +- Type: `string` +- Description: Address of the account + +### `accountQueryOptions` (optional) + + +- Type: +```typescript +interface AccountQueryOptions { + height?: number + id?: string + isSealed?: boolean +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#account) + + +A promise that resolves to an Account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/arg.md b/docs/tools/clients/fcl-js/packages-docs/sdk/arg.md new file mode 100644 index 0000000000..738f8ed4ed --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/arg.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "arg" +description: "arg function documentation." +--- + + + +# arg + +A utility builder to be used with fcl.args[...] to create FCL supported arguments for interactions. + +Arguments are used to pass data to Cadence scripts and transactions. The arguments must match the number and order declared in the Cadence script. +This function creates an ArgumentObject that holds the value and type passed in. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.arg(value, xform) +``` + +Or import directly the specific function: + +```typescript +import { arg } from "@onflow/sdk" + +arg(value, xform) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +const result = await fcl.query({ + cadence: ` + access(all) 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 + ], +}); +``` + +## Parameters + +### `value` + + +- Type: +```typescript +TypeDescriptorInput +``` +- Description: Any value that you are looking to pass to other builders + +### `xform` + + +- Type: `T` +- Description: A type supported by Flow (FType descriptor) + + +## Returns + +```typescript +CadenceArgument +``` + + +An ArgumentObject that holds the value and type passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/args.md b/docs/tools/clients/fcl-js/packages-docs/sdk/args.md new file mode 100644 index 0000000000..bfe5e7ed34 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/args.md @@ -0,0 +1,77 @@ +--- +sidebar_position: 1 +title: "args" +description: "args function documentation." +--- + + + +# args + +A utility builder to be used with other builders to pass in arguments with a value and supported type. + +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. +This function returns a Partial Interaction that contains the arguments and types passed in. This alone is a partial and incomplete interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.args(ax) +``` + +Or import directly the specific function: + +```typescript +import { args } from "@onflow/sdk" + +args(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +await fcl.mutate({ + cadence: ` + transaction(amount: UFix64, to: Address) { + prepare(signer: AuthAccount) { + // transaction logic + } + } + `, + args: (arg, t) => [ + arg("10.0", t.UFix64), // Will be the first argument `amount: UFix64` + arg("0xba1132bc08f82fe2", t.Address), // Will be the second argument `to: Address` + ], +}) +``` + +## Parameters + +### `ax` + + +- Type: +```typescript +CadenceArgument[] +``` +- Description: An array of argument objects created with fcl.arg() + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A Partial Interaction object containing the arguments and types passed in + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockHeight.md b/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockHeight.md new file mode 100644 index 0000000000..69fa838bb6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockHeight.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockHeight" +description: "atBlockHeight function documentation." +--- + + + +# 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. + +Block height expresses the height of the block on the chain. The latest block height increases by one for every valid block produced. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.atBlockHeight(height) +``` + +Or import directly the specific function: + +```typescript +import { atBlockHeight } from "@onflow/sdk" + +atBlockHeight(height) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block at specific height +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode); + +// Get account at specific block height +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Execute script at specific block height +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().height + } + `, + fcl.atBlockHeight(100) +]).then(fcl.decode); +``` + +## Parameters + +### `height` + + +- Type: `number` +- Description: The height of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockId.md b/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockId.md new file mode 100644 index 0000000000..4ce09d040f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/atBlockId.md @@ -0,0 +1,80 @@ +--- +sidebar_position: 1 +title: "atBlockId" +description: "atBlockId function documentation." +--- + + + +# 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. + +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'). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.atBlockId(id) +``` + +Or import directly the specific function: + +```typescript +import { atBlockId } from "@onflow/sdk" + +atBlockId(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get block by ID +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get account at specific block ID +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atBlockId("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); + +// Execute script at specific block +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().timestamp + } + `, + fcl.atBlockId("a1b2c3d4e5f6") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` +- Description: The ID of the block to execute the interaction at + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A partial interaction to be paired with another interaction such as 'fcl.getBlock()' or 'fcl.getAccount()' + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/atLatestBlock.md b/docs/tools/clients/fcl-js/packages-docs/sdk/atLatestBlock.md new file mode 100644 index 0000000000..dc4701330e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/atLatestBlock.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "atLatestBlock" +description: "atLatestBlock function documentation." +--- + + + +# atLatestBlock + +A builder function that returns a partial interaction to query the latest block with the given finality state. + +Use with other interactions like 'fcl.getBlock()' to get the latest block information. +Block finality determines whether you get the latest executed block or the latest sealed block. + +- Executed blocks (soft-finality): Latest block that has been executed but may not be final +- Sealed blocks (hard-finality): Latest block that has been sealed and is considered final + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.atLatestBlock(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { atLatestBlock } from "@onflow/sdk" + +atLatestBlock(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest executed block (soft finality) +await fcl.send([fcl.getBlock(), fcl.atLatestBlock()]).then(fcl.decode); + +// Get latest sealed block (hard finality) +await fcl.send([fcl.getBlock(), fcl.atLatestBlock(true)]).then(fcl.decode); + +// Get account from latest sealed block +await fcl.send([ + fcl.getAccount("0x1d007d755706c469"), + fcl.atLatestBlock(true) +]).then(fcl.decode); + +// Execute script against latest executed block +await fcl.send([ + fcl.script` + access(all) fun main(): UFix64 { + return getCurrentBlock().height + } + `, + fcl.atLatestBlock() +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: Block finality state, defaults to latest executed block ("soft-finality"), set to true for sealed blocks ("hard-finality") + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes a partial interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/authorization.md b/docs/tools/clients/fcl-js/packages-docs/sdk/authorization.md new file mode 100644 index 0000000000..a8bff24c03 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/authorization.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: "authorization" +description: "authorization function documentation." +--- + + + +# authorization + +Creates an authorization function for use in transactions. + +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. + +Read more about [authorization functions](https://docs.onflow.org/fcl/reference/authorization-function/) and [transaction roles](https://docs.onflow.org/concepts/transaction-signing/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.authorization(addr, signingFunction, keyId, sequenceNum) +``` + +Or import directly the specific function: + +```typescript +import { authorization } from "@onflow/sdk" + +authorization(addr, signingFunction, keyId, sequenceNum) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { ec as EC } from "elliptic"; + +// Create a signing function +const signingFunction = ({ message }) => { + // Your signing logic here + return { + addr: "0x123456789abcdef0", + keyId: 0, + signature: "your_signature_here" + }; +}; + +// Create authorization +const authz = fcl.authorization( + "0x123456789abcdef0", // account address + signingFunction, // signing function + 0, // key ID + 42 // sequence number +); + +// Use in transaction +await fcl.mutate({ + cadence: `transaction { prepare(acct: AuthAccount) {} }`, + proposer: authz, + payer: authz, + authorizations: [authz] +}); +``` + +## Parameters + +### `addr` + + +- Type: `string` +- Description: The address of the account that will sign the transaction + +### `signingFunction` + + +- Type: +```typescript +type SigningFn = ( + signable?: SignableMessage +) => SigningResult | Promise +``` +- Description: A function that produces signatures for the account + +### `keyId` (optional) + + +- Type: `string | number` +- Description: The index of the key to use for signing (optional) + +### `sequenceNum` (optional) + + +- Type: `number` +- Description: The sequence number for the account key (optional) + + +## Returns + +```typescript +Partial +``` + + +A partial interaction account object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/authorizations.md b/docs/tools/clients/fcl-js/packages-docs/sdk/authorizations.md new file mode 100644 index 0000000000..40befbfeda --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/authorizations.md @@ -0,0 +1,106 @@ +--- +sidebar_position: 1 +title: "authorizations" +description: "authorizations function documentation." +--- + + + +# authorizations + +A utility builder to set the authorizations on a transaction. + +Authorizations define the accounts that are responsible for paying the transaction fees and providing signatures for the transaction. +You can have multiple authorizers in a single transaction (multi-signature transactions). + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.authorizations(ax) +``` + +Or import directly the specific function: + +```typescript +import { authorizations } from "@onflow/sdk" + +authorizations(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Single authorizer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Hello from: ".concat(acct.address.toString())) + } + } + `, + authorizations: [fcl.authz] // Current user authorization +}); + +// Multiple authorizers - both accounts must approve +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct1: AuthAccount, acct2: AuthAccount) { + log("Transaction signed by both accounts") + } + } + `, + authorizations: [userOneAuthz, userTwoAuthz] +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + acct.save("Hello, World!", to: /storage/greeting) + } + } + `, + fcl.authorizations([fcl.authz]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.limit(100) +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An array of authorization functions that produce account authorization details + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/block.md b/docs/tools/clients/fcl-js/packages-docs/sdk/block.md new file mode 100644 index 0000000000..50cede0655 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/block.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "block" +description: "block function documentation." +--- + + + +# block + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.block(blockQueryOptions, opts) +``` + +Or import directly the specific function: + +```typescript +import { block } from "@onflow/sdk" + +block(blockQueryOptions, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest block +const latestBlock = await fcl.block(); // Get the latest finalized block +const latestSealedBlock = await fcl.block({sealed: true}); // Get the latest sealed block + +// Get block by ID (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); + +// Get block at height (uses builder function) +await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode) +``` + +## Parameters + +### `blockQueryOptions` (optional) + + +- Type: +```typescript +interface BlockQueryOptions { + sealed?: boolean + height?: number + id?: string +} +``` + +### `opts` (optional) + + +- Type: `object` +- Description: Optional parameters + + +## Returns + +[`Promise`](../types#block) + + +A promise that resolves to a Block object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/build.md b/docs/tools/clients/fcl-js/packages-docs/sdk/build.md new file mode 100644 index 0000000000..26a547b501 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/build.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "build" +description: "build function documentation." +--- + + + +# build + +A builder function that creates an interaction from an array of builder functions. + +The build function takes an array of builder functions and applies them to create a complete interaction object. This is the foundation for constructing all interactions in Flow, whether they're scripts, transactions, or queries. + +Each builder function modifies specific parts of the interaction object, such as adding Cadence code, arguments, authorization details, or other configuration. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.build(fns) +``` + +Or import directly the specific function: + +```typescript +import { build } from "@onflow/sdk" + +build(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Build a script interaction +const scriptInteraction = await fcl.build([ + fcl.script` + access(all) fun main(a: Int, b: Int): Int { + return a + b + } + `, + fcl.args([ + fcl.arg(1, fcl.t.Int), + fcl.arg(2, fcl.t.Int) + ]) +]); + +// Build a transaction interaction +const txInteraction = await fcl.build([ + fcl.transaction` + transaction(name: String) { + prepare(account: AuthAccount) { + log("Hello, " + name) + } + } + `, + fcl.args([fcl.arg("World", fcl.t.String)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `fns` (optional) + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: The functions to apply to the interaction + + +## Returns + +[`Promise`](../types#interaction) + + +A promise of an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/cadence.md b/docs/tools/clients/fcl-js/packages-docs/sdk/cadence.md new file mode 100644 index 0000000000..6fec54e09a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/cadence.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cadence" +description: "cadence function documentation." +--- + + + +# cadence + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.cadence(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cadence } from "@onflow/sdk" + +cadence(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/cdc.md b/docs/tools/clients/fcl-js/packages-docs/sdk/cdc.md new file mode 100644 index 0000000000..bd3b0e8488 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/cdc.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 1 +title: "cdc" +description: "cdc function documentation." +--- + + + +# cdc + +Creates a template function + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.cdc(head, rest) +``` + +Or import directly the specific function: + +```typescript +import { cdc } from "@onflow/sdk" + +cdc(head, rest) +``` + +## Usage + +```typescript +import { template } from "@onflow/util-template" + +// String template +const simpleTemplate = template("Hello, World!"); +console.log(simpleTemplate()); // "Hello, World!" + +// Template literal with interpolation +const name = "Alice"; +const greeting = template`Hello, ${name}!`; +console.log(greeting()); // "Hello, Alice!" + +// Cadence script template +const cadenceScript = template` + access(all) fun main(greeting: String): String { + return greeting.concat(", from Flow!") + } +`; +console.log(cadenceScript()); // The Cadence script as a string + +// Used with FCL for dynamic Cadence code +import * as fcl from "@onflow/fcl"; + +const contractAddress = "0x123456789abcdef0"; +const scriptTemplate = fcl.cadence` + import MyContract from ${contractAddress} + + access(all) fun main(): String { + return MyContract.getMessage() + } +`; +``` + +## Parameters + +### `head` + + +- Type: +```typescript +string | TemplateStringsArray | ((x?: unknown) => string) +``` +- Description: - A string, template string array, or template function + +### `rest` (optional) + + +- Type: `unknown[]` +- Description: - The rest of the arguments + + +## Returns + +```typescript +(x?: unknown) => string +``` + + +A template function + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/config.md b/docs/tools/clients/fcl-js/packages-docs/sdk/config.md new file mode 100644 index 0000000000..84a6950b79 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/config.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "config" +description: "config function documentation." +--- + + + +# config + +Sets the config + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.config(values) +``` + +Or import directly the specific function: + +```typescript +import { config } from "@onflow/sdk" + +config(values) +``` + + +## Parameters + +### `values` (optional) + + +- Type: +```typescript +Record +``` +- Description: - The values to set + + +## Returns + +```typescript +{ put: typeof put; get: typeof get; all: typeof all; first: typeof first; update: typeof update; delete: typeof _delete; where: typeof where; subscribe: typeof subscribe; overload: typeof overload; load: typeof load; } +``` + + +The config object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/createSignableVoucher.md b/docs/tools/clients/fcl-js/packages-docs/sdk/createSignableVoucher.md new file mode 100644 index 0000000000..7155336095 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/createSignableVoucher.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "createSignableVoucher" +description: "createSignableVoucher function documentation." +--- + + + +# createSignableVoucher + +Creates a signable voucher object from an interaction for signing purposes. + +A voucher is a standardized representation of a transaction that contains all the necessary +information for signing and submitting to the Flow network. This function transforms an +interaction object into a voucher format. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.createSignableVoucher(ix) +``` + +Or import directly the specific function: + +```typescript +import { createSignableVoucher } from "@onflow/sdk" + +createSignableVoucher(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { createSignableVoucher } from "@onflow/sdk" + +// Build a transaction interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); + +// Create a voucher for signing +const voucher = createSignableVoucher(interaction); +console.log(voucher.cadence); // The Cadence script +console.log(voucher.arguments); // The transaction arguments +console.log(voucher.proposalKey); // Proposer account details +console.log(voucher.authorizers); // List of authorizer addresses + +// The voucher can now be signed and submitted +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing transaction details + + +## Returns + +```typescript +{ cadence: string; refBlock: string; computeLimit: number; arguments: any[]; proposalKey: { address: string; keyId: string | number; sequenceNum: number; } | { address?: undefined; keyId?: undefined; sequenceNum?: undefined; }; payer: string; authorizers: string[]; payloadSigs: { address: string; keyId: string | number; sig: string; }[]; envelopeSigs: { address: string; keyId: string | number; sig: string; }[]; } +``` + + +A voucher object containing all transaction data and signatures + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/decode.md b/docs/tools/clients/fcl-js/packages-docs/sdk/decode.md new file mode 100644 index 0000000000..0257f16e3a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/decode.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "decode" +description: "decode function documentation." +--- + + + +# decode + +Decodes the response from 'fcl.send()' into the appropriate JSON representation of any values returned from Cadence code. + +The response from Flow contains encoded values that need to be decoded into JavaScript types. This function handles that conversion, including complex types like structs, arrays, and dictionaries. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.decode(response) +``` + +Or import directly the specific function: + +```typescript +import { decode } from "@onflow/sdk" + +decode(response) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple script to add 2 numbers +const response = await fcl.send([ + fcl.script` + access(all) 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); +console.log(decoded); // 3 +console.log(typeof decoded); // "number" + +// Complex return types +const complexResponse = await fcl.send([ + fcl.script` + access(all) fun main(): {String: Int} { + return {"foo": 1, "bar": 2} + } + ` +]); + +const complexDecoded = await fcl.decode(complexResponse); +console.log(complexDecoded); // {foo: 1, bar: 2} +``` + +## Parameters + +### `response` + + +- Type: `any` +- Description: Should be the response returned from 'fcl.send([...])' + + +## Returns + +`Promise` + + +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. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/destroy.md b/docs/tools/clients/fcl-js/packages-docs/sdk/destroy.md new file mode 100644 index 0000000000..d137d53e71 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/destroy.md @@ -0,0 +1,70 @@ +--- +sidebar_position: 1 +title: "destroy" +description: "destroy function documentation." +--- + + + +# destroy + +Removes a property from an interaction object using a dot-notation key path. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.destroy(key) +``` + +Or import directly the specific function: + +```typescript +import { destroy } from "@onflow/sdk" + +destroy(key) +``` + +## Usage + +```typescript +import { destroy, put, get, initInteraction } from "@onflow/sdk" + +const interaction = initInteraction(); + +// Set some values +put("user.name", "Alice")(interaction); +put("user.email", "alice@example.com")(interaction); +put("user.temp", "temporary data")(interaction); + +console.log(get(interaction, "user.temp")); // "temporary data" + +// Remove temporary data +destroy("user.temp")(interaction); + +console.log(get(interaction, "user.temp")); // undefined +console.log(get(interaction, "user.name")); // "Alice" (still exists) +``` + +## Parameters + +### `key` + + +- Type: `string` +- Description: The dot-notation key path to remove + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction and removes the property + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/encodeMessageFromSignable.md b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeMessageFromSignable.md new file mode 100644 index 0000000000..84ac1f0e8e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeMessageFromSignable.md @@ -0,0 +1,103 @@ +--- +sidebar_position: 1 +title: "encodeMessageFromSignable" +description: "encodeMessageFromSignable function documentation." +--- + + + +# encodeMessageFromSignable + +Encodes a message from a signable object for a specific signer address. + +This function determines whether the signer should sign the transaction payload or envelope +based on their role in the transaction (authorizer, proposer, or payer), then encodes the +appropriate message for signing. + +Payload signers include authorizers and proposers (but not payers) +Envelope signers include only payers + +The encoded message is what gets signed by the account's private key to create the transaction signature. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.encodeMessageFromSignable(signable, signerAddress) +``` + +Or import directly the specific function: + +```typescript +import { encodeMessageFromSignable } from "@onflow/sdk" + +encodeMessageFromSignable(signable, signerAddress) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// This function is typically used internally by authorization functions +// when implementing custom wallet connectors or signing flows + +const signable = { + voucher: { + cadence: "transaction { prepare(acct: AuthAccount) {} }", + authorizers: ["0x01"], + proposalKey: { address: "0x01", keyId: 0, sequenceNum: 42 }, + payer: "0x02", + refBlock: "a1b2c3", + computeLimit: 100, + arguments: [], + payloadSigs: [] + } +}; + +// For an authorizer (payload signer) +const authorizerMessage = fcl.encodeMessageFromSignable(signable, "0x01"); +console.log("Authorizer signs:", authorizerMessage); + +// For a payer (envelope signer) +const payerMessage = fcl.encodeMessageFromSignable(signable, "0x02"); +console.log("Payer signs:", payerMessage); +``` + +## Parameters + +### `signable` + + +- Type: +```typescript +export interface Signable { + message: string + addr?: string + keyId?: number + signature?: string + roles: Record + voucher: Voucher + [key: string]: any +} +``` +- Description: The signable object containing transaction data and voucher + +### `signerAddress` + + +- Type: `string` +- Description: The address of the signer to encode the message for + + +## Returns + +`string` + + +An encoded message string suitable for signing with the account's private key + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionEnvelope.md b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionEnvelope.md new file mode 100644 index 0000000000..783a6cf5a0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionEnvelope.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "encodeTransactionEnvelope" +description: "encodeTransactionEnvelope function documentation." +--- + + + +# encodeTransactionEnvelope + +Encodes a complete transaction envelope including payload and signatures. + +This function encodes the full transaction including both the payload and all signatures. +This is the final step before submitting a transaction to the Flow network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.encodeTransactionEnvelope(tx) +``` + +Or import directly the specific function: + +```typescript +import { encodeTransactionEnvelope } from "@onflow/sdk" + +encodeTransactionEnvelope(tx) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { encodeTransactionEnvelope } from "@onflow/sdk" + +// Assuming you have a fully built and signed transaction +const signedTransaction = await fcl.build([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Hello, Flow!") + } + } + `, + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]), + fcl.limit(100) +]); + +// Add signatures to the transaction (this is usually done automatically) +// signedTransaction.payloadSigs = [...]; +// signedTransaction.envelopeSigs = [...]; + +// Encode the complete transaction envelope +const encodedEnvelope = encodeTransactionEnvelope(signedTransaction); +console.log("Encoded envelope:", encodedEnvelope); +// Returns a hex string ready for network submission +``` + +## Parameters + +### `tx` + + +- Type: [`Transaction`](../types#transaction) +- Description: The transaction object to encode + + +## Returns + +`string` + + +A hex-encoded string representing the complete transaction envelope + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionPayload.md b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionPayload.md new file mode 100644 index 0000000000..03924f1b05 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTransactionPayload.md @@ -0,0 +1,78 @@ +--- +sidebar_position: 1 +title: "encodeTransactionPayload" +description: "encodeTransactionPayload function documentation." +--- + + + +# encodeTransactionPayload + +Encodes a transaction payload for signing. + +This function takes a transaction object and encodes it into a format suitable for signing. +The encoded payload contains all the transaction details except for the signatures. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.encodeTransactionPayload(tx) +``` + +Or import directly the specific function: + +```typescript +import { encodeTransactionPayload } from "@onflow/sdk" + +encodeTransactionPayload(tx) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { encodeTransactionPayload } from "@onflow/sdk" + +// Build a transaction +const transaction = await fcl.build([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log("Transferring: ".concat(amount.toString())) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); + +// Encode the transaction payload for signing +const encodedPayload = encodeTransactionPayload(transaction); +console.log("Encoded payload:", encodedPayload); +// Returns a hex string like "f90145b90140..." +``` + +## Parameters + +### `tx` + + +- Type: [`Transaction`](../types#transaction) +- Description: The transaction object to encode + + +## Returns + +`string` + + +A hex-encoded string representing the transaction payload + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTxIdFromVoucher.md b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTxIdFromVoucher.md new file mode 100644 index 0000000000..a665edad96 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/encodeTxIdFromVoucher.md @@ -0,0 +1,98 @@ +--- +sidebar_position: 1 +title: "encodeTxIdFromVoucher" +description: "encodeTxIdFromVoucher function documentation." +--- + + + +# encodeTxIdFromVoucher + +Encodes a transaction ID from a voucher by computing its hash. + +A voucher is an intermediary object that contains transaction details before final encoding. +This function computes the transaction ID that would result from submitting the transaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.encodeTxIdFromVoucher(voucher) +``` + +Or import directly the specific function: + +```typescript +import { encodeTxIdFromVoucher } from "@onflow/sdk" + +encodeTxIdFromVoucher(voucher) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { encodeTxIdFromVoucher } from "@onflow/sdk" + +// Create a voucher (usually done internally by FCL) +const voucher = { + cadence: ` + transaction { + prepare(account: AuthAccount) { + log("Hello") + } + } + `, + arguments: [], + refBlock: "abc123...", + computeLimit: 100, + proposalKey: { + address: "0x123456789abcdef0", + keyId: 0, + sequenceNum: 42 + }, + payer: "0x123456789abcdef0", + authorizers: ["0x123456789abcdef0"], + payloadSigs: [], + envelopeSigs: [] +}; + +// Calculate the transaction ID +const txId = encodeTxIdFromVoucher(voucher); +console.log("Transaction ID:", txId); +// Returns a transaction ID that can be used to track the transaction +``` + +## Parameters + +### `voucher` + + +- Type: +```typescript +export interface Voucher { + cadence: string + refBlock: string + computeLimit: number + arguments: VoucherArgument[] + proposalKey: VoucherProposalKey + payer: string + authorizers: string[] + payloadSigs: Sig[] + envelopeSigs: Sig[] +} +``` +- Description: The voucher object containing transaction details + + +## Returns + +`string` + + +A hex-encoded string representing the transaction ID + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/get.md b/docs/tools/clients/fcl-js/packages-docs/sdk/get.md new file mode 100644 index 0000000000..63517d9164 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/get.md @@ -0,0 +1,78 @@ +--- +sidebar_position: 1 +title: "get" +description: "get function documentation." +--- + + + +# get + +Gets a value from an interaction object using a dot-notation key path. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.get(ix, key, fallback) +``` + +Or import directly the specific function: + +```typescript +import { get } from "@onflow/sdk" + +get(ix, key, fallback) +``` + +## Usage + +```typescript +import { get, put, initInteraction } from "@onflow/sdk" + +const interaction = initInteraction(); + +// Set a value first +put("user.name", "Alice")(interaction); + +// Get the value +const userName = get(interaction, "user.name"); // "Alice" +const userAge = get(interaction, "user.age", 25); // 25 (fallback) + +// Get nested values +put("config.network.url", "https://access.mainnet.onflow.org")(interaction); +const networkUrl = get(interaction, "config.network.url"); +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object + +### `key` + + +- Type: `string` +- Description: The dot-notation key path (e.g., "message.arguments") + +### `fallback` (optional) + + +- Type: `any` +- Description: The fallback value if the key is not found + + +## Returns + +`any` + + +The value at the key path or the fallback value + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getAccount.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getAccount.md new file mode 100644 index 0000000000..3f3fda6947 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getAccount.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getAccount" +description: "getAccount function documentation." +--- + + + +# 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. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getAccount(addr) +``` + +Or import directly the specific function: + +```typescript +import { getAccount } from "@onflow/sdk" + +getAccount(addr) +``` + +## Usage + +```typescript +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; +}; +``` + +## Parameters + +### `addr` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getBlock.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getBlock.md new file mode 100644 index 0000000000..4091917776 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getBlock.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getBlock" +description: "getBlock function documentation." +--- + + + +# 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.block(options)' if you do not need to pair with any other builders. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getBlock(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlock } from "@onflow/sdk" + +getBlock(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const latestSealedBlock = await fcl.send([ + fcl.getBlock(true) // isSealed = true +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: If the latest block should be sealed or not. See block states + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getBlockHeader.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getBlockHeader.md new file mode 100644 index 0000000000..da6306dd30 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getBlockHeader.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getBlockHeader" +description: "getBlockHeader function documentation." +--- + + + +# getBlockHeader + +A builder function that returns the interaction to get a block header. + +A block header contains metadata about a block without the full transaction details, making it more +lightweight than fetching the entire block. This is useful when you only need block metadata like +timestamp, height, parent hash, etc. + +Use with 'fcl.atBlockId()' and 'fcl.atBlockHeight()' when building the interaction to get headers for specific blocks. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getBlockHeader(isSealed) +``` + +Or import directly the specific function: + +```typescript +import { getBlockHeader } from "@onflow/sdk" + +getBlockHeader(isSealed) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get latest sealed block header +const sealedHeader = await fcl.send([ + fcl.getBlockHeader(true) +]).then(fcl.decode); + +console.log("Block height:", sealedHeader.height); +console.log("Block timestamp:", sealedHeader.timestamp); +console.log("Parent block ID:", sealedHeader.parentId); + +// Get header for specific block +const blockHeader = await fcl.send([ + fcl.getBlockHeader(), + fcl.atBlockHeight(12345) +]).then(fcl.decode); + +// Get latest finalized block header +const finalizedHeader = await fcl.send([ + fcl.getBlockHeader(false) +]).then(fcl.decode); +``` + +## Parameters + +### `isSealed` (optional) + + +- Type: `boolean` +- Description: Block finality state, true for sealed blocks, false for finalized blocks, null for latest + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getCollection.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getCollection.md new file mode 100644 index 0000000000..680c4edff4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getCollection.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "getCollection" +description: "getCollection function documentation." +--- + + + +# getCollection + +A builder function that returns a collection containing a list of transaction IDs by its collection ID. + +A collection is a batch of transactions that have been included in a block. Each collection has a unique ID +which is the SHA3-256 hash of the collection payload. Collections are used to group related transactions +together for more efficient processing by the network. + +The collection ID provided must be from the current spork. Collections from past sporks are currently unavailable. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getCollection(id) +``` + +Or import directly the specific function: + +```typescript +import { getCollection } from "@onflow/sdk" + +getCollection(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get a collection and see what transactions it contains +const collection = await fcl.send([ + fcl.getCollection("cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5") +]).then(fcl.decode); + +console.log("Collection ID:", collection.id); +console.log("Transaction IDs:", collection.transactionIds); +console.log("Total transactions:", collection.transactionIds.length); + +// Process each transaction in the collection +for (const txId of collection.transactionIds) { + const transaction = await fcl.send([ + fcl.getTransaction(txId) + ]).then(fcl.decode); + console.log("Transaction:", transaction); +} +``` + +## Parameters + +### `id` (optional) + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getEvents.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getEvents.md new file mode 100644 index 0000000000..045753e4e4 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getEvents.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "getEvents" +description: "getEvents function documentation." +--- + + + +# getEvents + +A builder function that returns the interaction to get events. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened during execution. +This function queries for events of a specific type within a range of block heights. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getEvents(eventType, start, end) +``` + +Or import directly the specific function: + +```typescript +import { getEvents } from "@onflow/sdk" + +getEvents(eventType, start, end) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get FlowToken transfer events from blocks 1000 to 2000 +const events = await fcl.send([ + fcl.getEvents("A.1654653399040a61.FlowToken.TokensDeposited", 1000, 2000) +]).then(fcl.decode); + +console.log("Found events:", events.length); +events.forEach(event => { + console.log("Event data:", event.data); + console.log("Transaction ID:", event.transactionId); +}); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get (e.g., "A.1654653399040a61.FlowToken.TokensWithdrawn") + +### `start` + + +- Type: `number` +- Description: The start block height to query from + +### `end` + + +- Type: `number` +- Description: The end block height to query to + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockHeightRange.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockHeightRange.md new file mode 100644 index 0000000000..8ae75ed217 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockHeightRange.md @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockHeightRange" +description: "getEventsAtBlockHeightRange function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +Block height range expresses the height of the start and end block in the chain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockHeightRange } from "@onflow/sdk" + +getEventsAtBlockHeightRange(eventType, startHeight, endHeight) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get events at block height range +await fcl + .send([ + fcl.getEventsAtBlockHeightRange( + "A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name + 35580624, // block to start looking for events at + 35580624 // block to stop looking for events at + ), + ]) + .then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `startHeight` + + +- Type: `number` +- Description: The height of the block to start looking for events (inclusive) + +### `endHeight` + + +- Type: `number` +- Description: The height of the block to stop looking for events (inclusive) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockIds.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockIds.md new file mode 100644 index 0000000000..ad77642a01 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getEventsAtBlockIds.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "getEventsAtBlockIds" +description: "getEventsAtBlockIds function documentation." +--- + + + +# 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. + +Event type is a string that follow a standard format: A.\{AccountAddress\}.\{ContractName\}.\{EventName\} + +Please read more about [events in the documentation](https://docs.onflow.org/cadence/language/events/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getEventsAtBlockIds(eventType, blockIds) +``` + +Or import directly the specific function: + +```typescript +import { getEventsAtBlockIds } from "@onflow/sdk" + +getEventsAtBlockIds(eventType, blockIds) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const events = await fcl.send([ + fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [ + "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7", + "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f" + ]) +]).then(fcl.decode); +``` + +## Parameters + +### `eventType` + + +- Type: `string` +- Description: The type of event to get + +### `blockIds` + + +- Type: `string[]` +- Description: The ids of the blocks to scan for events + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getNetworkParameters.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getNetworkParameters.md new file mode 100644 index 0000000000..faf4da54af --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getNetworkParameters.md @@ -0,0 +1,68 @@ +--- +sidebar_position: 1 +title: "getNetworkParameters" +description: "getNetworkParameters function documentation." +--- + + + +# getNetworkParameters + +A builder function that returns the interaction to get network parameters. + +Network parameters contain important configuration information about the Flow network, +including the chain ID, which is essential for signing transactions correctly. +This information is crucial for ensuring transactions are submitted to the correct network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getNetworkParameters() +``` + +Or import directly the specific function: + +```typescript +import { getNetworkParameters } from "@onflow/sdk" + +getNetworkParameters() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get network parameters to verify chain ID +const params = await fcl.send([ + fcl.getNetworkParameters() +]).then(fcl.decode); + +console.log("Chain ID:", params.chainId); +console.log("Network:", params.name); + +// Use this to verify you're connected to the right network +if (params.chainId === "flow-mainnet") { + console.log("Connected to Flow Mainnet"); +} else if (params.chainId === "flow-testnet") { + console.log("Connected to Flow Testnet"); +} +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getNodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getNodeVersionInfo.md new file mode 100644 index 0000000000..5fa7da7bb0 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getNodeVersionInfo.md @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +title: "getNodeVersionInfo" +description: "getNodeVersionInfo function documentation." +--- + + + +# getNodeVersionInfo + +A builder function for the Get Node Version Info interaction. + +Creates an interaction to retrieve version information from the connected Flow Access Node. +This includes details about the node's software version, protocol version, and spork information. + +Consider using the pre-built interaction 'fcl.nodeVersionInfo()' if you do not need to pair with any other builders. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getNodeVersionInfo() +``` + +Or import directly the specific function: + +```typescript +import { getNodeVersionInfo } from "@onflow/sdk" + +getNodeVersionInfo() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information using builder +const versionInfo = await fcl.send([ + fcl.getNodeVersionInfo() +]).then(fcl.decode); + +console.log("Node version:", versionInfo.semver); +console.log("Protocol version:", versionInfo.protocol_version); +console.log("Spork ID:", versionInfo.spork_id); + +// Use with other builders if needed +const interaction = await fcl.build([ + fcl.getNodeVersionInfo() + // other builders can be added here +]); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getTransaction.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getTransaction.md new file mode 100644 index 0000000000..dfb1fc4ef8 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getTransaction.md @@ -0,0 +1,67 @@ +--- +sidebar_position: 1 +title: "getTransaction" +description: "getTransaction function documentation." +--- + + + +# getTransaction + +A builder function that returns the interaction to get a transaction by id. + +Transaction id is a hash of the encoded transaction payload and can be calculated before submitting the transaction to the network. +Transaction status represents the state of a transaction in the blockchain. Status can change until it is finalized. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id).onceExecuted()' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getTransaction(id) +``` + +Or import directly the specific function: + +```typescript +import { getTransaction } from "@onflow/sdk" + +getTransaction(id) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const tx = await fcl.send([ + fcl.getTransaction("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `id` + + +- Type: `string` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/getTransactionStatus.md b/docs/tools/clients/fcl-js/packages-docs/sdk/getTransactionStatus.md new file mode 100644 index 0000000000..67fb14b246 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/getTransactionStatus.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "getTransactionStatus" +description: "getTransactionStatus function documentation." +--- + + + +# getTransactionStatus + +A builder function that returns the status of transaction. + +The transaction id provided must be from the current spork. + +Consider using 'fcl.tx(id)' instead of calling this method directly for real-time transaction monitoring. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.getTransactionStatus(transactionId) +``` + +Or import directly the specific function: + +```typescript +import { getTransactionStatus } from "@onflow/sdk" + +getTransactionStatus(transactionId) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const status = await fcl.send([ + fcl.getTransactionStatus("9dda5f281897389b99f103a1c6b180eec9dac870de846449a302103ce38453f3") +]).then(fcl.decode); +``` + +## Parameters + +### `transactionId` + + +- Type: `string` +- Description: The id of the transaction to get the status of + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/index.md b/docs/tools/clients/fcl-js/packages-docs/sdk/index.md new file mode 100644 index 0000000000..2348789d4b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/index.md @@ -0,0 +1,203 @@ +--- +sidebar_position: 1 +title: "@onflow/sdk" +description: "Low-level JavaScript/TypeScript SDK for interacting with the Flow blockchain." +--- + + + +# @onflow/sdk + +## Overview + +The Flow sdk library 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: + +```bash +npm install @onflow/sdk +``` + +Or using yarn: + +```bash +yarn add @onflow/sdk +``` + +### Requirements + +- Node.js 14.x or later + +### Importing + +You can import the entire package: + +```typescript +import * as sdk from "@onflow/sdk" +``` + +Or import specific functions: + +```typescript +import { 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: + +```typescript +import { config } from "@onflow/fcl" + +config({ + "accessNode.api": "https://rest-testnet.onflow.org" +}) +``` + +## 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](https://cadence-lang.org/docs). Here is an example transaction script: + +```typescript +transaction(greeting: string) { + execute { + log(greeting.concat(", World!")) + } +} +``` + +**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: + +```typescript +transaction { + prepare(authorizer1: &Account, authorizer2: &Account) { } +} +``` + +**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](https://cadence-lang.org/docs). + +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 and namespaces in the sdk package. + +- [account](./account.md) - Retrieve any account from Flow network's latest block or from a specified block... +- [arg](./arg.md) - A utility builder to be used with fcl.args[...] to create FCL supported... +- [args](./args.md) - A utility builder to be used with other builders to pass in arguments with a... +- [atBlockHeight](./atBlockHeight.md) - A builder function that returns a partial interaction to a block at a specific... +- [atBlockId](./atBlockId.md) - A builder function that returns a partial interaction to a block at a specific... +- [atLatestBlock](./atLatestBlock.md) - A builder function that returns a partial interaction to query the latest block... +- [authorization](./authorization.md) - Creates an authorization function for use in transactions. An authorization... +- [authorizations](./authorizations.md) - A utility builder to set the authorizations on a transaction. Authorizations... +- [block](./block.md) - Query the network for block by id, height or get the latest block. Block ID is... +- [build](./build.md) - A builder function that creates an interaction from an array of builder... +- [cadence](./cadence.md) - Creates a template function +- [cdc](./cdc.md) - Creates a template function +- [config](./config.md) - Sets the config +- [createSignableVoucher](./createSignableVoucher.md) - Creates a signable voucher object from an interaction for signing purposes. A... +- [decode](./decode.md) - Decodes the response from 'fcl.send()' into the appropriate JSON representation... +- [destroy](./destroy.md) - Removes a property from an interaction object using a dot-notation key path. +- [encodeMessageFromSignable](./encodeMessageFromSignable.md) - Encodes a message from a signable object for a specific signer address. This... +- [encodeTransactionEnvelope](./encodeTransactionEnvelope.md) - Encodes a complete transaction envelope including payload and signatures. This... +- [encodeTransactionPayload](./encodeTransactionPayload.md) - Encodes a transaction payload for signing. This function takes a transaction... +- [encodeTxIdFromVoucher](./encodeTxIdFromVoucher.md) - Encodes a transaction ID from a voucher by computing its hash. A voucher is an... +- [get](./get.md) - Gets a value from an interaction object using a dot-notation key path. +- [getAccount](./getAccount.md) - A builder function that returns the interaction to get an account by address.... +- [getBlock](./getBlock.md) - A builder function that returns the interaction to get the latest block. Use... +- [getBlockHeader](./getBlockHeader.md) - A builder function that returns the interaction to get a block header. A block... +- [getCollection](./getCollection.md) - A builder function that returns a collection containing a list of transaction... +- [getEvents](./getEvents.md) - A builder function that returns the interaction to get events. Events are... +- [getEventsAtBlockHeightRange](./getEventsAtBlockHeightRange.md) - A builder function that returns all instances of a particular event (by name)... +- [getEventsAtBlockIds](./getEventsAtBlockIds.md) - A builder function that returns all instances of a particular event (by name)... +- [getNetworkParameters](./getNetworkParameters.md) - A builder function that returns the interaction to get network parameters.... +- [getNodeVersionInfo](./getNodeVersionInfo.md) - A builder function for the Get Node Version Info interaction. Creates an... +- [getTransaction](./getTransaction.md) - A builder function that returns the interaction to get a transaction by id.... +- [getTransactionStatus](./getTransactionStatus.md) - A builder function that returns the status of transaction. The transaction id... +- [initInteraction](./initInteraction.md) - Creates a new interaction object with default values. +- [interaction](./interaction.md) - Creates a new interaction object with default values. +- [isBad](./isBad.md) - Checks if an interaction has a failed status. +- [isOk](./isOk.md) - Checks if an interaction has a successful status. +- [limit](./limit.md) - A utility builder to set the compute limit on a transaction. The compute limit... +- [nodeVersionInfo](./nodeVersionInfo.md) - Retrieve version information from the connected Flow Access Node. This function... +- [param](./param.md) - Legacy function for setting a single parameter on an interaction. +- [params](./params.md) - Legacy function for setting parameters on an interaction. +- [payer](./payer.md) - A builder function that adds payer account(s) to a transaction. Every... +- [ping](./ping.md) - A builder function that creates a ping interaction to test connectivity to the... +- [pipe](./pipe.md) - Async pipe function to compose interactions. The pipe function is the foundation... +- [proposer](./proposer.md) - A builder function that adds the proposer to a transaction. The proposer is... +- [put](./put.md) - Sets a value in an interaction object using a dot-notation key path. +- [ref](./ref.md) - A builder function that sets the reference block for a transaction. The... +- [resolve](./resolve.md) - Resolves an interaction by applying a series of resolvers in sequence. This is... +- [resolveAccounts](./resolveAccounts.md) - Resolves account authorization functions and validates account configurations... +- [resolveArguments](./resolveArguments.md) - Resolves transaction arguments by evaluating argument functions and converting... +- [resolveCadence](./resolveCadence.md) - Resolves Cadence code by evaluating functions and replacing contract... +- [resolveFinalNormalization](./resolveFinalNormalization.md) - Normalizes account addresses by removing the "0x" prefix from all account... +- [resolveProposerSequenceNumber](./resolveProposerSequenceNumber.md) - Resolves the sequence number for the proposer account by querying the... +- [resolveRefBlockId](./resolveRefBlockId.md) - Resolves the reference block ID for a transaction by querying the latest block... +- [resolveSignatures](./resolveSignatures.md) - Resolves signatures for a transaction by coordinating the signing process for... +- [resolveValidators](./resolveValidators.md) - Executes validator functions that have been attached to an interaction to... +- [resolveVoucherIntercept](./resolveVoucherIntercept.md) - Resolves voucher intercept functions by calling them with the current voucher. +- [response](./response.md) - Creates a default response object +- [script](./script.md) - A builder function that creates a script interaction. Scripts allow you to write... +- [send](./send.md) - Sends arbitrary scripts, transactions, and requests to Flow. This method... +- [subscribe](./subscribe.md) - Subscribe to real-time data from the Flow blockchain and automatically decode... +- [subscribeEvents](./subscribeEvents.md) - Subscribe to events with the given filter and parameters. Creates a subscription... +- [subscribeRaw](./subscribeRaw.md) - Subscribe to a topic without decoding the data. This function creates a raw... +- [TestUtils](./testUtils.md) (namespace) - Namespace containing TestUtils utilities +- [TestUtils.authzDeepResolveMany](./testUtils.md#authzDeepResolveMany) - Creates a deep test authorization resolver with nested resolution for complex... +- [TestUtils.authzFn](./testUtils.md#authzFn) - Creates a test authorization function for testing transactions. +- [TestUtils.authzResolve](./testUtils.md#authzResolve) - Creates a test authorization resolver that can be used for testing account... +- [TestUtils.authzResolveMany](./testUtils.md#authzResolveMany) - Creates a test authorization resolver that handles multiple accounts with... +- [TestUtils.idof](./testUtils.md#idof) - Generates a unique identifier for an account based on its address and key ID. +- [TestUtils.run](./testUtils.md#run) - Runs a set of functions on an interaction This is a utility function for testing... +- [TestUtils.sig](./testUtils.md#sig) - Generates a test signature string for an account. +- [transaction](./transaction.md) - A template builder to use a Cadence transaction for an interaction. FCL "mutate"... +- [update](./update.md) - Updates a value in an interaction object using a transformation function. +- [validator](./validator.md) - A builder function that adds a validator to a transaction. Validators are... +- [voucherIntercept](./voucherIntercept.md) - A builder function that intercepts and modifies a voucher. This function is... +- [voucherToTxId](./voucherToTxId.md) - Converts a voucher object to a transaction ID. This function computes the... +- [why](./why.md) - Returns the reason for an interaction failure. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/initInteraction.md b/docs/tools/clients/fcl-js/packages-docs/sdk/initInteraction.md new file mode 100644 index 0000000000..022b7d2fd9 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/initInteraction.md @@ -0,0 +1,40 @@ +--- +sidebar_position: 1 +title: "initInteraction" +description: "initInteraction function documentation." +--- + + + +# initInteraction + +Creates a new interaction object with default values. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.initInteraction() +``` + +Or import directly the specific function: + +```typescript +import { initInteraction } from "@onflow/sdk" + +initInteraction() +``` + + + +## Returns + +[`Interaction`](../types#interaction) + + +A new interaction object initialized with default values + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/interaction.md b/docs/tools/clients/fcl-js/packages-docs/sdk/interaction.md new file mode 100644 index 0000000000..35e30702a3 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/interaction.md @@ -0,0 +1,40 @@ +--- +sidebar_position: 1 +title: "interaction" +description: "interaction function documentation." +--- + + + +# interaction + +Creates a new interaction object with default values. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.interaction() +``` + +Or import directly the specific function: + +```typescript +import { interaction } from "@onflow/sdk" + +interaction() +``` + + + +## Returns + +[`Interaction`](../types#interaction) + + +A new interaction object initialized with default values + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/isBad.md b/docs/tools/clients/fcl-js/packages-docs/sdk/isBad.md new file mode 100644 index 0000000000..9932ad442d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/isBad.md @@ -0,0 +1,62 @@ +--- +sidebar_position: 1 +title: "isBad" +description: "isBad function documentation." +--- + + + +# isBad + +Checks if an interaction has a failed status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.isBad(ix) +``` + +Or import directly the specific function: + +```typescript +import { isBad } from "@onflow/sdk" + +isBad(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isBad, why } from "@onflow/sdk" + +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isBad(response)) { + console.log("Transaction failed:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is BAD, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/isOk.md b/docs/tools/clients/fcl-js/packages-docs/sdk/isOk.md new file mode 100644 index 0000000000..126178eb45 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/isOk.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: "isOk" +description: "isOk function documentation." +--- + + + +# isOk + +Checks if an interaction has a successful status. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.isOk(ix) +``` + +Or import directly the specific function: + +```typescript +import { isOk } from "@onflow/sdk" + +isOk(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { isOk } from "@onflow/sdk" + +// Check if a transaction was successful +const response = await fcl.send([ + fcl.transaction`transaction { prepare(account: AuthAccount) {} }` +]); + +if (isOk(response)) { + console.log("Transaction was successful"); +} else { + console.log("Transaction failed"); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to check + + +## Returns + +`boolean` + + +True if the interaction status is OK, false otherwise + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/limit.md b/docs/tools/clients/fcl-js/packages-docs/sdk/limit.md new file mode 100644 index 0000000000..65cf8ef1f2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/limit.md @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +title: "limit" +description: "limit function documentation." +--- + + + +# limit + +A utility builder to set the compute limit on a transaction. + +The compute limit is the maximum amount of computation that can be performed during transaction execution. +Setting an appropriate compute limit helps prevent infinite loops and ensures predictable transaction costs. + +Read more about [computation cost](https://docs.onflow.org/concepts/fees/#computation-cost) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.limit(limit) +``` + +Or import directly the specific function: + +```typescript +import { limit } from "@onflow/sdk" + +limit(limit) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + // Complex transaction logic here + } + } + `, + limit: 1000 // Set compute limit to 1000 +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.limit(9999) // Set higher limit for complex operations +]); +``` + +## Parameters + +### `limit` + + +- Type: `number` +- Description: The maximum amount of computation for the transaction + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/nodeVersionInfo.md b/docs/tools/clients/fcl-js/packages-docs/sdk/nodeVersionInfo.md new file mode 100644 index 0000000000..41402507ae --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/nodeVersionInfo.md @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +title: "nodeVersionInfo" +description: "nodeVersionInfo function documentation." +--- + + + +# nodeVersionInfo + +Retrieve version information from the connected Flow Access Node. + +This function returns detailed information about the Flow node's version, including the protocol version, spork information, and node-specific details. This is useful for debugging, compatibility checks, and understanding the network state. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.nodeVersionInfo(opts) +``` + +Or import directly the specific function: + +```typescript +import { nodeVersionInfo } from "@onflow/sdk" + +nodeVersionInfo(opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Get node version information +const versionInfo = await fcl.nodeVersionInfo(); +console.log(versionInfo); +// { +// semver: "v0.37.13", +// commit: "12345abcd", +// spork_id: "mainnet-23", +// protocol_version: "2.13.10", +// spork_root_block_height: "88483760", +// node_root_block_height: "88483760" +// } + +// Check compatibility +const info = await fcl.nodeVersionInfo(); +if (info.protocol_version.startsWith("2.13")) { + console.log("Compatible with current protocol version"); +} +``` + +## Parameters + +### `opts` (optional) + + +- Type: `any` +- Description: Optional parameters for the request + + +## Returns + +[`Promise`](../types#nodeversioninfo) + + +A promise that resolves to a block response + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/param.md b/docs/tools/clients/fcl-js/packages-docs/sdk/param.md new file mode 100644 index 0000000000..220bb62b50 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/param.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "param" +description: "param function documentation." +--- + + + +# param + +Legacy function for setting a single parameter on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.param(params) +``` + +Or import directly the specific function: + +```typescript +import { param } from "@onflow/sdk" + +param(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameter to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/params.md b/docs/tools/clients/fcl-js/packages-docs/sdk/params.md new file mode 100644 index 0000000000..5d6dab9009 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/params.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "params" +description: "params function documentation." +--- + + + +# params + +Legacy function for setting parameters on an interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.params(params) +``` + +Or import directly the specific function: + +```typescript +import { params } from "@onflow/sdk" + +params(params) +``` + + +## Parameters + +### `params` + + +- Type: `never` +- Description: The parameters to set + + +## Returns + +```typescript +Promise | ((...args: unknown[]) => Promise) +``` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/payer.md b/docs/tools/clients/fcl-js/packages-docs/sdk/payer.md new file mode 100644 index 0000000000..7f3e51d8eb --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/payer.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 1 +title: "payer" +description: "payer function documentation." +--- + + + +# payer + +A builder function that adds payer account(s) to a transaction. + +Every transaction requires at least one payer. + +The payer is the account that pays the transaction fee for executing the transaction on the network. +The payer account must have sufficient Flow tokens to cover the transaction fees. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#payer) and [transaction fees](https://docs.onflow.org/concepts/fees/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.payer(ax) +``` + +Or import directly the specific function: + +```typescript +import { payer } from "@onflow/sdk" + +payer(ax) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using current user as payer (most common case) +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: AuthAccount) { + log("Transaction fees paid by: ".concat(acct.address.toString())) + } + } + `, + payer: fcl.authz // Current user as payer +}); + +// Using custom payer with builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.proposer(fcl.authz), // Current user as proposer + fcl.authorizations([fcl.authz]), // Current user as authorizer + fcl.payer(customPayerAuthz) // Custom payer pays fees +]); + +// Multiple payers (advanced use case) +await fcl.send([ + fcl.transaction` + transaction { + prepare(acct: AuthAccount) { + // Transaction logic + } + } + `, + fcl.payer([payerAuthz1, payerAuthz2]) // Multiple payers split fees +]); +``` + +## Parameters + +### `ax` (optional) + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: An account address or an array of account addresses + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that takes an interaction object and returns a new interaction object with the payer(s) added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/ping.md b/docs/tools/clients/fcl-js/packages-docs/sdk/ping.md new file mode 100644 index 0000000000..4a44c8ed9f --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/ping.md @@ -0,0 +1,72 @@ +--- +sidebar_position: 1 +title: "ping" +description: "ping function documentation." +--- + + + +# ping + +A builder function that creates a ping interaction to test connectivity to the Flow Access Node. + +The ping interaction is a simple way to test if the Flow Access Node is reachable and responding. This is useful for health checks, connectivity testing, and debugging network issues. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.ping() +``` + +Or import directly the specific function: + +```typescript +import { ping } from "@onflow/sdk" + +ping() +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Simple ping to test connectivity +try { + const response = await fcl.send([fcl.ping()]); + console.log("Access Node is reachable"); +} catch (error) { + console.error("Access Node is not reachable:", error); +} + +// Use ping for health checks +const healthCheck = async () => { + try { + await fcl.send([fcl.ping()]); + return { status: "healthy", timestamp: new Date().toISOString() }; + } catch (error) { + return { status: "unhealthy", error: error.message, timestamp: new Date().toISOString() }; + } +}; + +const health = await healthCheck(); +console.log("Health status:", health); +``` + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/pipe.md b/docs/tools/clients/fcl-js/packages-docs/sdk/pipe.md new file mode 100644 index 0000000000..15aa427ff2 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/pipe.md @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +title: "pipe" +description: "pipe function documentation." +--- + + + +# pipe + +Async pipe function to compose interactions. + +The pipe function is the foundation for composing multiple interaction builder functions together. +It sequentially applies builder functions to an interaction, allowing for complex interaction construction. +Each function in the pipe receives the result of the previous function and can modify or validate the interaction. + +Pipe has two main forms: +1. `pipe(builderFunctions)`: Returns a builder function +2. `pipe(interaction, builderFunctions)`: Directly executes the pipe on an interaction + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.pipe(fns) +``` + +Or import directly the specific function: + +```typescript +import { pipe } from "@onflow/sdk" + +pipe(fns) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using pipe to create a reusable builder +const myTransactionBuilder = fcl.pipe([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Use the builder +const interaction = await fcl.build([myTransactionBuilder]); + +// Pipe is used internally by build() and send() +await fcl.send([ + fcl.script`access(all) fun main(): Int { return 42 }` +]); // This uses pipe internally +``` + +## Parameters + +### `fns` + + +- Type: `(false | InteractionBuilderFn)[]` +- Description: Array of builder functions to apply + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +An interaction builder function when called with just functions, or a Promise<Interaction> when called with an interaction and functions + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/proposer.md b/docs/tools/clients/fcl-js/packages-docs/sdk/proposer.md new file mode 100644 index 0000000000..c6872b6093 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/proposer.md @@ -0,0 +1,94 @@ +--- +sidebar_position: 1 +title: "proposer" +description: "proposer function documentation." +--- + + + +# proposer + +A builder function that adds the proposer to a transaction. + +The proposer is responsible for providing the proposal key and paying the network fee for the transaction. +The proposer key is used to specify the sequence number and prevent replay attacks. + +Every transaction requires exactly one proposer. + +Read more about [transaction roles](https://docs.onflow.org/concepts/transaction-signing/#proposer) and [signing transactions](https://docs.onflow.org/concepts/accounts-and-keys/). + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.proposer(authz) +``` + +Or import directly the specific function: + +```typescript +import { proposer } from "@onflow/sdk" + +proposer(authz) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Using the current user as proposer +await fcl.mutate({ + cadence: ` + transaction { + prepare(account: AuthAccount) { + log("Hello from proposer!") + } + } + `, + proposer: fcl.authz +}); + +// Using builder pattern +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.proposer(proposerAuthz), + fcl.payer(payerAuthz), + fcl.authorizations([authorizerAuthz]), + fcl.limit(100) +]); +``` + +## Parameters + +### `authz` + + +- Type: +```typescript +export type AccountAuthorization = + | (AuthorizationFn & Partial) + | Partial +``` +- Description: The authorization object for the proposer + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction object and returns a new interaction object with the proposer added + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/put.md b/docs/tools/clients/fcl-js/packages-docs/sdk/put.md new file mode 100644 index 0000000000..94b0c7fffc --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/put.md @@ -0,0 +1,74 @@ +--- +sidebar_position: 1 +title: "put" +description: "put function documentation." +--- + + + +# put + +Sets a value in an interaction object using a dot-notation key path. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.put(key, value) +``` + +Or import directly the specific function: + +```typescript +import { put } from "@onflow/sdk" + +put(key, value) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { put } from "@onflow/sdk" + +// Using put in a custom builder function +const setCustomData = (data) => put("custom.data", data); + +await fcl.send([ + fcl.script`access(all) fun main(): String { return "Hello" }`, + setCustomData({ userId: 123, timestamp: Date.now() }) +]); + +// Direct usage +const interaction = initInteraction(); +put("network.endpoint", "https://access.mainnet.onflow.org")(interaction); +``` + +## Parameters + +### `key` + + +- Type: `string` +- Description: The dot-notation key path (e.g., "message.arguments") + +### `value` + + +- Type: `any` +- Description: The value to set + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction and sets the value + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/ref.md b/docs/tools/clients/fcl-js/packages-docs/sdk/ref.md new file mode 100644 index 0000000000..39b619f290 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/ref.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "ref" +description: "ref function documentation." +--- + + + +# ref + +A builder function that sets the reference block for a transaction. + +The 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.ref(refBlock) +``` + +Or import directly the specific function: + +```typescript +import { ref } from "@onflow/sdk" + +ref(refBlock) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Set specific reference block for transaction +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction with custom reference block") + } + } + `, + fcl.ref("a1b2c3d4e5f6789..."), // Custom reference block ID + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]), + fcl.limit(100) +]); + +// Usually, you don't need to set reference block manually +// as FCL will automatically set it to the latest block +``` + +## Parameters + +### `refBlock` + + +- Type: `string` +- Description: The reference block ID + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolve.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolve.md new file mode 100644 index 0000000000..b3405d67a5 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolve.md @@ -0,0 +1,74 @@ +--- +sidebar_position: 1 +title: "resolve" +description: "resolve function documentation." +--- + + + +# resolve + +Resolves an interaction by applying a series of resolvers in sequence. + +This is the main resolver function that takes a built interaction and prepares it +for submission to the Flow blockchain by applying all necessary resolvers. + +The resolve function uses a pipeline approach, applying each resolver in sequence +to transform the interaction from its initial built state to a fully resolved state +ready for transmission to the Flow Access API. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolve(interaction) +``` + +Or import directly the specific function: + +```typescript +import { resolve } from "@onflow/sdk" + +resolve(interaction) +``` + +## Usage + +```typescript +import { resolve, build, script } from "@onflow/sdk" + +const interaction = await build([ + script` + access(all) fun main(): String { + return "Hello, World!" + } + ` +]) + +const resolved = await resolve(interaction) +``` + +## Parameters + +### `interaction` + + +- Type: `any` +- Description: The interaction object to resolve + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A promise that resolves to the fully resolved interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveAccounts.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveAccounts.md new file mode 100644 index 0000000000..ba72f394cc --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveAccounts.md @@ -0,0 +1,57 @@ +--- +sidebar_position: 1 +title: "resolveAccounts" +description: "resolveAccounts function documentation." +--- + + + +# resolveAccounts + +Resolves account authorization functions and validates account configurations for transactions. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveAccounts(ix, opts) +``` + +Or import directly the specific function: + +```typescript +import { resolveAccounts } from "@onflow/sdk" + +resolveAccounts(ix, opts) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing accounts to resolve + +### `opts` (optional) + + +- Type: +```typescript +Record +``` +- Description: Configuration options for resolution + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction with resolved accounts + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveArguments.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveArguments.md new file mode 100644 index 0000000000..75242fc068 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveArguments.md @@ -0,0 +1,76 @@ +--- +sidebar_position: 1 +title: "resolveArguments" +description: "resolveArguments function documentation." +--- + + + +# resolveArguments + +Resolves transaction arguments by evaluating argument functions and converting them to appropriate types. + +This function processes all arguments in a transaction or script interaction, calling their transform functions +to convert JavaScript values into Cadence-compatible argument formats that can be sent to the Flow network. + +The resolution process includes: +- Calling argument resolver functions if present +- Applying type transformations using the xform field +- Handling recursive argument resolution up to a depth limit + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveArguments(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveArguments } from "@onflow/sdk" + +resolveArguments(ix) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Arguments are automatically resolved during send() +await fcl.send([ + fcl.script` + access(all) fun main(amount: UFix64, recipient: Address): String { + return "Sending ".concat(amount.toString()).concat(" to ").concat(recipient.toString()) + } + `, + fcl.args([ + fcl.arg("100.0", fcl.t.UFix64), // Will be resolved to Cadence UFix64 + fcl.arg("0x01", fcl.t.Address) // Will be resolved to Cadence Address + ]) +]).then(fcl.decode); + +// The resolveArguments function handles the conversion automatically +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing arguments to resolve + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction with resolved arguments ready for network transmission + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveCadence.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveCadence.md new file mode 100644 index 0000000000..28f6e81b22 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveCadence.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "resolveCadence" +description: "resolveCadence function documentation." +--- + + + +# resolveCadence + +Resolves Cadence code by evaluating functions and replacing contract placeholders with addresses. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveCadence(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveCadence } from "@onflow/sdk" + +resolveCadence(ix) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing Cadence code to resolve + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction with resolved Cadence code + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveFinalNormalization.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveFinalNormalization.md new file mode 100644 index 0000000000..825f93493c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveFinalNormalization.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "resolveFinalNormalization" +description: "resolveFinalNormalization function documentation." +--- + + + +# resolveFinalNormalization + +Normalizes account addresses by removing the "0x" prefix from all account addresses in the interaction. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveFinalNormalization(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveFinalNormalization } from "@onflow/sdk" + +resolveFinalNormalization(ix) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object to normalize + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction with normalized account addresses + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveProposerSequenceNumber.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveProposerSequenceNumber.md new file mode 100644 index 0000000000..76f53ae17c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveProposerSequenceNumber.md @@ -0,0 +1,54 @@ +--- +sidebar_position: 1 +title: "resolveProposerSequenceNumber" +description: "resolveProposerSequenceNumber function documentation." +--- + + + +# resolveProposerSequenceNumber + +Resolves the sequence number for the proposer account by querying the blockchain. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveProposerSequenceNumber(nodeConfig) +``` + +Or import directly the specific function: + +```typescript +import { resolveProposerSequenceNumber } from "@onflow/sdk" + +resolveProposerSequenceNumber(nodeConfig) +``` + + +## Parameters + +### `nodeConfig` + + +- Type: +```typescript +interface NodeConfig { + node: string +} +``` + + +## Returns + +```typescript +(ix: Interaction) => Promise +``` + + +A function that resolves the proposer sequence number for an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveRefBlockId.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveRefBlockId.md new file mode 100644 index 0000000000..2eb55fcfc6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveRefBlockId.md @@ -0,0 +1,53 @@ +--- +sidebar_position: 1 +title: "resolveRefBlockId" +description: "resolveRefBlockId function documentation." +--- + + + +# resolveRefBlockId + +Resolves the reference block ID for a transaction by querying the latest block from the network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveRefBlockId(opts) +``` + +Or import directly the specific function: + +```typescript +import { resolveRefBlockId } from "@onflow/sdk" + +resolveRefBlockId(opts) +``` + + +## Parameters + +### `opts` (optional) + + +- Type: +```typescript +{ [key: string]: any; } +``` +- Description: Optional configuration parameters + + +## Returns + +```typescript +(ix: any) => Promise +``` + + +A function that resolves the reference block ID for an interaction + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveSignatures.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveSignatures.md new file mode 100644 index 0000000000..9aaebe9c9c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveSignatures.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "resolveSignatures" +description: "resolveSignatures function documentation." +--- + + + +# resolveSignatures + +Resolves signatures for a transaction by coordinating the signing process for inside and outside signers. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveSignatures(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveSignatures } from "@onflow/sdk" + +resolveSignatures(ix) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing transaction details + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction object with resolved signatures + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveValidators.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveValidators.md new file mode 100644 index 0000000000..7b0826693c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveValidators.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "resolveValidators" +description: "resolveValidators function documentation." +--- + + + +# resolveValidators + +Executes validator functions that have been attached to an interaction to perform validation checks. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveValidators(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveValidators } from "@onflow/sdk" + +resolveValidators(ix) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object containing validators to execute + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction after running all validators + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/resolveVoucherIntercept.md b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveVoucherIntercept.md new file mode 100644 index 0000000000..3fcc669d93 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/resolveVoucherIntercept.md @@ -0,0 +1,48 @@ +--- +sidebar_position: 1 +title: "resolveVoucherIntercept" +description: "resolveVoucherIntercept function documentation." +--- + + + +# resolveVoucherIntercept + +Resolves voucher intercept functions by calling them with the current voucher. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.resolveVoucherIntercept(ix) +``` + +Or import directly the specific function: + +```typescript +import { resolveVoucherIntercept } from "@onflow/sdk" + +resolveVoucherIntercept(ix) +``` + + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction object to resolve voucher intercepts for + + +## Returns + +[`Promise`](../types#interaction) + + +The interaction after voucher intercept processing + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/response.md b/docs/tools/clients/fcl-js/packages-docs/sdk/response.md new file mode 100644 index 0000000000..ccc195266c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/response.md @@ -0,0 +1,56 @@ +--- +sidebar_position: 1 +title: "response" +description: "response function documentation." +--- + + + +# response + +Creates a default response object + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.response() +``` + +Or import directly the specific function: + +```typescript +import { response } from "@onflow/sdk" + +response() +``` + +## Usage + +```typescript +import { response } from "@onflow/sdk" + +// Create a default response object +const defaultResponse = response(); +console.log(defaultResponse.transaction); // null +console.log(defaultResponse.account); // null +console.log(defaultResponse.block); // null + +// Typically used internally by the SDK to initialize responses +// You'll rarely need to use this directly in application code +``` + + +## Returns + +```typescript +{ tag: any; transaction: any; transactionStatus: any; transactionId: any; encodedData: any; events: any; event: any; accountStatusEvent: any; account: any; block: any; blockHeader: any; blockDigest: any; latestBlock: any; collection: any; networkParameters: any; streamConnection: any; heartbeat: any; nodeVersionInfo: any; } +``` + + +A default response object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/script.md b/docs/tools/clients/fcl-js/packages-docs/sdk/script.md new file mode 100644 index 0000000000..4b32ba702c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/script.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "script" +description: "script function documentation." +--- + + + +# script + +A builder function that creates a script interaction. Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. + +You can learn more about [Cadence here](https://cadence-lang.org/docs/language), 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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.script(args) +``` + +Or import directly the specific function: + +```typescript +import { script } from "@onflow/sdk" + +script(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +const result = await fcl.query({ + cadence: ` + access(all) 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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray | ((x?: unknown) => string), ...unknown[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/send.md b/docs/tools/clients/fcl-js/packages-docs/sdk/send.md new file mode 100644 index 0000000000..e564981d65 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/send.md @@ -0,0 +1,83 @@ +--- +sidebar_position: 1 +title: "send" +description: "send function documentation." +--- + + + +# 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. + +WARNING: Must be used in conjunction with 'fcl.decode(response)' to get back correct keys and all values in JSON. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.send(args, opts) +``` + +Or import directly the specific function: + +```typescript +import { send } from "@onflow/sdk" + +send(args, opts) +``` + +## Usage + +```typescript +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 +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +false | Function | (false | Function)[] +``` +- Description: An array of builders (functions that take an interaction object and return a new interaction object) + +### `opts` (optional) + + +- Type: `any` +- Description: Additional optional options for the request + + +## Returns + +`Promise` + + +A promise that resolves to a ResponseObject containing the data returned from the chain. Should always be decoded with fcl.decode() to get back appropriate JSON keys and values. + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/subscribe.md b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribe.md new file mode 100644 index 0000000000..4d21aaef0e --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribe.md @@ -0,0 +1,101 @@ +--- +sidebar_position: 1 +title: "subscribe" +description: "subscribe function documentation." +--- + + + +# subscribe + +Subscribe to real-time data from the Flow blockchain and automatically decode the responses. + +This is a utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the 'decode' function. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.subscribe(subscribeParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribe } from "@onflow/sdk" + +subscribe(subscribeParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to events +const subscription = fcl.subscribe({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (events) => { + console.log("Received events:", events); + }, + onError: (error) => { + console.error("Subscription error:", error); + } +}); + +// Subscribe to blocks +const blockSubscription = fcl.subscribe({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (block) => { + console.log("New block:", block); + }, + onError: (error) => { + console.error("Block subscription error:", error); + } +}); + +// Later, to unsubscribe: +subscription.unsubscribe(); +blockSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeParams` + + +- Type: +```typescript +SubscribeParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +[`Subscription`](../types#subscription) + + +A subscription object that allows you to manage the subscription (e.g., to unsubscribe later) + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeEvents.md b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeEvents.md new file mode 100644 index 0000000000..57f4ac8289 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeEvents.md @@ -0,0 +1,84 @@ +--- +sidebar_position: 1 +title: "subscribeEvents" +description: "subscribeEvents function documentation." +--- + + + +# subscribeEvents + +Subscribe to events with the given filter and parameters. + +Creates a subscription to listen for real-time events from the Flow blockchain. This function configures +the subscription parameters for filtering specific events based on type, addresses, contracts, and other criteria. + +Events are emitted by Cadence code during transaction execution and provide insights into what happened. +Subscriptions allow you to listen for these events in real-time without polling. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.subscribeEvents(eventFilter) +``` + +Or import directly the specific function: + +```typescript +import { subscribeEvents } from "@onflow/sdk" + +subscribeEvents(eventFilter) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Subscribe to FlowToken transfer events +const subscription = await fcl.send([ + fcl.subscribeEvents({ + eventTypes: [ + "A.1654653399040a61.FlowToken.TokensWithdrawn", + "A.1654653399040a61.FlowToken.TokensDeposited" + ], + startHeight: 1000000, // Start from specific block height + heartbeatInterval: 3000 // 3 second heartbeat + }) +]); + +// Subscribe to events from specific contracts +const contractSubscription = await fcl.send([ + fcl.subscribeEvents({ + contracts: ["FlowToken", "FungibleToken"], + addresses: ["0x1654653399040a61"] + }) +]); + +// Handle the subscription data elsewhere using fcl.subscribe() +``` + +## Parameters + +### `eventFilter` + + +- Type: [`EventFilter`](../types#eventfilter) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeRaw.md b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeRaw.md new file mode 100644 index 0000000000..d0051be62d --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/subscribeRaw.md @@ -0,0 +1,105 @@ +--- +sidebar_position: 1 +title: "subscribeRaw" +description: "subscribeRaw function documentation." +--- + + + +# subscribeRaw + +Subscribe to a topic without decoding the data. + +This function creates a raw subscription to Flow blockchain data streams without automatic decoding. +It's useful when you need more control over data processing or want to handle raw responses directly. +For most use cases, consider using the `subscribe()` function instead which provides automatic decoding. + +Available topics include: `events`, `blocks`, `block_headers`, `block_digests`, `transaction_statuses`, `account_statuses`. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.subscribeRaw(subscribeRawParams, opts) +``` + +Or import directly the specific function: + +```typescript +import { subscribeRaw } from "@onflow/sdk" + +subscribeRaw(subscribeRawParams, opts) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; +import { SubscriptionTopic } from "@onflow/sdk"; + +// Subscribe to raw event data without automatic decoding +const rawSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.EVENTS, + args: { + eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"] + }, + onData: (rawData) => { + console.log("Raw event data:", rawData); + // Handle raw data manually - no automatic decoding + }, + onError: (error) => { + console.error("Raw subscription error:", error); + } +}); + +// Subscribe to raw block data +const blockSubscription = fcl.subscribeRaw({ + topic: SubscriptionTopic.BLOCKS, + args: { + blockStatus: "finalized" + }, + onData: (rawBlock) => { + console.log("Raw block data:", rawBlock); + }, + onError: (error) => { + console.error("Error:", error); + } +}); + +// Unsubscribe when done +rawSubscription.unsubscribe(); +``` + +## Parameters + +### `subscribeRawParams` + + +- Type: +```typescript +SubscribeRawParams +``` + +### `opts` (optional) + + +- Type: +```typescript +{ node?: string; transport?: SdkTransport; } +``` +- Description: Additional options for the subscription + + +## Returns + +```typescript +{ unsubscribe: () => void; } +``` + + +A subscription object with an unsubscribe method + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/testUtils.md b/docs/tools/clients/fcl-js/packages-docs/sdk/testUtils.md new file mode 100644 index 0000000000..4562e949a6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/testUtils.md @@ -0,0 +1,341 @@ +--- +sidebar_position: 1 +title: "TestUtils" +description: "Namespace containing TestUtils utilities" +--- + + + +# TestUtils + +## Overview + +Namespace containing TestUtils utilities + +## Functions + +### authzDeepResolveMany + +Creates a deep test authorization resolver with nested resolution for complex testing scenarios. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.authzDeepResolveMany(opts, depth) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.authzDeepResolveMany(opts, depth) +``` + + +#### Parameters + +##### `opts` (optional) + + +- Type: +```typescript +interface IAuthzResolveMany { + tempId?: string + authorizations: any[] + proposer?: any + payer?: any +} +``` +- Description: Configuration including authorizations array and optional proposer/payer + +##### `depth` (optional) + + +- Type: `number` +- Description: The depth of nesting for the resolver (default: 1) + +#### Returns + +```typescript +(account: InteractionAccount) => InteractionAccount +``` + +### authzFn + +Creates a test authorization function for testing transactions. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.authzFn(opts) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.authzFn(opts) +``` + + +#### Parameters + +##### `opts` (optional) + + +- Type: +```typescript +interface IAuthzOpts { + signingFunction?: (signable: any) => any +} +``` +- Description: Optional configuration including custom signing function + +#### Returns + +```typescript +(account: Partial) => Partial +``` + +### authzResolve + +Creates a test authorization resolver that can be used for testing account resolution. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.authzResolve(opts) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.authzResolve(opts) +``` + + +#### Parameters + +##### `opts` (optional) + + +- Type: +```typescript +interface IAuthzResolveOpts { + tempId?: string +} +``` +- Description: Optional configuration including temporary ID + +#### Returns + +```typescript +(account: InteractionAccount) => { tempId: string; resolve: (account: Partial) => Partial; kind: InteractionResolverKind.ACCOUNT; addr: string; keyId: string | number; sequenceNum: number; signature: string; signingFunction: any; role: { proposer: boolean; authorizer: boolean; payer: boolean; param?: boolean; }; authorization: any; } +``` + +### authzResolveMany + +Creates a test authorization resolver that handles multiple accounts with different roles. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.authzResolveMany(opts) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.authzResolveMany(opts) +``` + + +#### Parameters + +##### `opts` (optional) + + +- Type: +```typescript +interface IAuthzResolveMany { + tempId?: string + authorizations: any[] + proposer?: any + payer?: any +} +``` +- Description: Configuration including authorizations array and optional proposer/payer + +#### Returns + +```typescript +(account: InteractionAccount) => InteractionAccount +``` + +### idof + +Generates a unique identifier for an account based on its address and key ID. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.idof(acct) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.idof(acct) +``` + + +#### Parameters + +##### `acct` + + +- Type: [`InteractionAccount`](../types#interactionaccount) +- Description: The account object + +#### Returns + +`string` + +### run + +Runs a set of functions on an interaction + +This is a utility function for testing that builds and resolves an interaction with the provided builder functions. +It automatically adds a reference block and then resolves the interaction for testing purposes. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.run(fns) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.run(fns) +``` + +#### Usage + +```typescript +import { run } from "@onflow/sdk" +import * as fcl from "@onflow/fcl"; + +// Test a simple script interaction +const result = await run([ + fcl.script` + access(all) fun main(): Int { + return 42 + } + ` +]); + +console.log(result.cadence); // The Cadence script +console.log(result.tag); // "SCRIPT" + +// Test a transaction with arguments +const txResult = await run([ + fcl.transaction` + transaction(amount: UFix64) { + prepare(account: AuthAccount) { + log(amount) + } + } + `, + fcl.args([fcl.arg("10.0", fcl.t.UFix64)]) +]); + +console.log(txResult.message.arguments); // The resolved arguments +``` + +#### Parameters + +##### `fns` (optional) + + +- Type: +```typescript +((ix: Interaction) => Interaction | Promise)[] +``` +- Description: An array of functions to run on the interaction + +#### Returns + +[`Promise`](../types#interaction) + +### sig + +Generates a test signature string for an account. + +#### Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.TestUtils.sig(opts) +``` + +Or import the namespace directly: + +```typescript +import { TestUtils } from "@onflow/sdk" + +TestUtils.sig(opts) +``` + + +#### Parameters + +##### `opts` + + +- Type: `Partial` +- Description: Partial account object containing address and keyId + +#### Returns + +`string` + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/transaction.md b/docs/tools/clients/fcl-js/packages-docs/sdk/transaction.md new file mode 100644 index 0000000000..84623ed097 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/transaction.md @@ -0,0 +1,104 @@ +--- +sidebar_position: 1 +title: "transaction" +description: "transaction function documentation." +--- + + + +# transaction + +A template builder to use a Cadence transaction for an interaction. FCL "mutate" does the work of building, signing, and sending a transaction behind the scenes. + +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. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.transaction(args) +``` + +Or import directly the specific function: + +```typescript +import { transaction } from "@onflow/sdk" + +transaction(args) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl" + +// Basic transaction usage +await fcl.mutate({ + cadence: ` + transaction(a: Int) { + prepare(acct: &Account) { + log(acct) + log(a) + } + } + `, + args: (arg, t) => [ + arg(6, t.Int) + ], + limit: 50 +}) + +// Single party, single signature +// Proposer, payer and authorizer are the same account +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + authz: currentUser, // Optional. Will default to currentUser if not provided. + limit: 50, +}) + +// Multiple parties +// Proposer and authorizer are the same account, but different payer +await fcl.mutate({ + cadence: ` + transaction { + prepare(acct: &Account) {} + } + `, + proposer: authzFn, + payer: authzTwoFn, + authorizations: [authzFn], + limit: 50, +}) +``` + +## Parameters + +### `args` (optional) + + +- Type: +```typescript +[string | TemplateStringsArray, ...any[]] +``` +- Description: The arguments to pass to the template + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/update.md b/docs/tools/clients/fcl-js/packages-docs/sdk/update.md new file mode 100644 index 0000000000..682394aa97 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/update.md @@ -0,0 +1,79 @@ +--- +sidebar_position: 1 +title: "update" +description: "update function documentation." +--- + + + +# update + +Updates a value in an interaction object using a transformation function. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.update(key, fn) +``` + +Or import directly the specific function: + +```typescript +import { update } from "@onflow/sdk" + +update(key, fn) +``` + +## Usage + +```typescript +import { update, put, initInteraction } from "@onflow/sdk" + +const interaction = initInteraction(); + +// Set initial value +put("counter", 0)(interaction); + +// Increment counter +const increment = update("counter", (current) => (current || 0) + 1); +increment(interaction); // counter becomes 1 +increment(interaction); // counter becomes 2 + +// Update array +put("tags", ["flow", "blockchain"])(interaction); +const addTag = update("tags", (tags) => [...(tags || []), "web3"]); +addTag(interaction); // tags becomes ["flow", "blockchain", "web3"] +``` + +## Parameters + +### `key` + + +- Type: `string` +- Description: The dot-notation key path to update + +### `fn` (optional) + + +- Type: +```typescript +(v: T | T[], ...args: any[]) => T | T[] +``` +- Description: The transformation function to apply to the existing value + + +## Returns + +```typescript +(ix: Interaction) => Interaction +``` + + +A function that takes an interaction and updates the value + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/validator.md b/docs/tools/clients/fcl-js/packages-docs/sdk/validator.md new file mode 100644 index 0000000000..5ee333a70a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/validator.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 1 +title: "validator" +description: "validator function documentation." +--- + + + +# validator + +A builder function that adds a validator to a transaction. + +Validators are functions that run during transaction building to check for invalid configurations or parameters. +They help catch errors early before submitting transactions to the network, preventing failed transactions +and wasted compute costs. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.validator(cb) +``` + +Or import directly the specific function: + +```typescript +import { validator } from "@onflow/sdk" + +validator(cb) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Custom validator to ensure account has sufficient balance +const validateBalance = (ix) => { + if (ix.message.computeLimit > 1000) { + throw new Error("Compute limit too high for this account"); + } + return ix; +}; + +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + // Transaction logic + } + } + `, + fcl.validator(validateBalance), + fcl.limit(500) // This will pass validation +]); +``` + +## Parameters + +### `cb` + + +- Type: `Function` +- Description: The validator function that takes an interaction and returns it (or throws an error if invalid) + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/voucherIntercept.md b/docs/tools/clients/fcl-js/packages-docs/sdk/voucherIntercept.md new file mode 100644 index 0000000000..0a8d63734c --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/voucherIntercept.md @@ -0,0 +1,86 @@ +--- +sidebar_position: 1 +title: "voucherIntercept" +description: "voucherIntercept function documentation." +--- + + + +# voucherIntercept + +A builder function that intercepts and modifies a voucher. + +This function is useful for debugging, logging, or making modifications to +the transaction data. The voucher contains all the transaction details in their final form. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.voucherIntercept(fn) +``` + +Or import directly the specific function: + +```typescript +import { voucherIntercept } from "@onflow/sdk" + +voucherIntercept(fn) +``` + +## Usage + +```typescript +import * as fcl from "@onflow/fcl"; + +// Intercept voucher for logging +await fcl.send([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Transaction executed") + } + } + `, + fcl.voucherIntercept((voucher) => { + console.log("Voucher details:", { + cadence: voucher.cadence, + proposalKey: voucher.proposalKey, + payer: voucher.payer, + authorizers: voucher.authorizers, + computeLimit: voucher.computeLimit + }); + }), + fcl.proposer(fcl.authz), + fcl.payer(fcl.authz), + fcl.authorizations([fcl.authz]) +]); +``` + +## Parameters + +### `fn` + + +- Type: +```typescript +type VoucherInterceptFn = (voucher: Voucher) => any | Promise +``` +- Description: The function to intercept and potentially modify the voucher + + +## Returns + +```typescript +export type InteractionBuilderFn = ( + ix: Interaction +) => Interaction | Promise +``` + + +A function that processes an interaction object + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/voucherToTxId.md b/docs/tools/clients/fcl-js/packages-docs/sdk/voucherToTxId.md new file mode 100644 index 0000000000..83d098d26b --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/voucherToTxId.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: "voucherToTxId" +description: "voucherToTxId function documentation." +--- + + + +# voucherToTxId + +Converts a voucher object to a transaction ID. + +This function computes the transaction ID by encoding and hashing the voucher. +The transaction ID can be used to track the transaction status on the Flow network. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.voucherToTxId(voucher) +``` + +Or import directly the specific function: + +```typescript +import { voucherToTxId } from "@onflow/sdk" + +voucherToTxId(voucher) +``` + +## Usage + +```typescript +import { voucherToTxId, createSignableVoucher } from "@onflow/sdk" +import * as fcl from "@onflow/fcl"; + +// Create a voucher from an interaction +const interaction = await fcl.build([ + fcl.transaction` + transaction { + prepare(account: AuthAccount) { + log("Hello, Flow!") + } + } + `, + fcl.proposer(authz), + fcl.payer(authz), + fcl.authorizations([authz]) +]); + +const voucher = createSignableVoucher(interaction); + +// Calculate the transaction ID +const txId = voucherToTxId(voucher); +console.log("Transaction ID:", txId); +// Returns something like: "a1b2c3d4e5f6789..." + +// You can use this ID to track the transaction +const txStatus = await fcl.tx(txId).onceSealed(); +console.log("Transaction status:", txStatus); +``` + +## Parameters + +### `voucher` + + +- Type: +```typescript +export interface Voucher { + cadence: string + refBlock: string + computeLimit: number + arguments: VoucherArgument[] + proposalKey: VoucherProposalKey + payer: string + authorizers: string[] + payloadSigs: Sig[] + envelopeSigs: Sig[] +} +``` +- Description: The voucher object to convert + + +## Returns + +`string` + + +A transaction ID string + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/sdk/why.md b/docs/tools/clients/fcl-js/packages-docs/sdk/why.md new file mode 100644 index 0000000000..43aa1a129a --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/sdk/why.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +title: "why" +description: "why function documentation." +--- + + + +# why + +Returns the reason for an interaction failure. + +## Import + +You can import the entire package and access the function: + +```typescript +import * as sdk from "@onflow/sdk" + +sdk.why(ix) +``` + +Or import directly the specific function: + +```typescript +import { why } from "@onflow/sdk" + +why(ix) +``` + +## Usage + +```typescript +import { Bad, why, initInteraction } from "@onflow/sdk" + +const interaction = Bad(initInteraction(), "Network timeout"); +console.log(why(interaction)); // "Network timeout" + +// Used with error handling +if (isBad(response)) { + console.error("Error occurred:", why(response)); +} +``` + +## Parameters + +### `ix` + + +- Type: [`Interaction`](../types#interaction) +- Description: The interaction to get the failure reason from + + +## Returns + +`string` + + +The reason string or undefined if no reason is set + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/packages-docs/types/index.md b/docs/tools/clients/fcl-js/packages-docs/types/index.md new file mode 100644 index 0000000000..edad73a6c6 --- /dev/null +++ b/docs/tools/clients/fcl-js/packages-docs/types/index.md @@ -0,0 +1,714 @@ +--- +title: Type Definitions +description: Type definitions for the Flow Client Library (FCL) packages. +--- + + + +# Type Definitions + +Documentation for core types used throughout the Flow Client Library (FCL). + +## Interfaces + +### Account + +```typescript +import { type Account } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `address` | `string` | The address of the account | +| `balance` | `number` | The FLOW balance of the account in 10^8 | +| `code` | `number` | The code of any Cadence contracts stored in the account | +| `contracts` | `Record` | Any contracts deployed to this account | +| `keys` | `AccountKey[]` | The keys associated with the account | + +### AccountKey + +```typescript +import { type AccountKey } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `index` | `number` | The index of the key in the account | +| `publicKey` | `string` | The public key of the account key | +| `signAlgo` | `SignatureAlgorithm` | The signature algorithm used by the key | +| `signAlgoString` | `string` | The signature algorithm used by the key as a string | +| `hashAlgo` | `HashAlgorithm` | The hashing algorithm used by the key | +| `hashAlgoString` | `string` | The hashing algorithm used by the key as a string | +| `sequenceNumber` | `number` | The sequence number of the key | +| `weight` | `number` | The weight of the key | +| `revoked` | `boolean` | Whether or not the key has been revoked | + +### AccountStatusEvent + +```typescript +import { type AccountStatusEvent } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `accountAddress` | `string` | The address of the account which the event is associated with. | + +### Block + +```typescript +import { type Block } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | 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` | `string` | Time related fields | +| `parentVoterSignature` | `string` | The parent voter signature of the block | +| `collectionGuarantees` | `CollectionGuarantee[]` | Contains the ids of collections included in the block | +| `blockSeals` | `BlockSeal[]` | The details of which nodes executed and sealed the blocks | + +### BlockDigest + +```typescript +import { type BlockDigest } from "@onflow/fcl" +``` + +BlockDigest holds lightweight block information which includes only block id, block height and block timestamp. + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `id` | `string` | The id of the block | +| `height` | `number` | The height of the block | +| `timestamp` | `string` | Timestamp of the block | + +### BlockHeader + +```typescript +import { type BlockHeader } from "@onflow/fcl" +``` + +Header contains all meta-data for a block, as well as a hash representing +the combined payload of the entire block. It is what consensus nodes agree +on after validating the contents against the payload hash. + +**Properties:** + +| Name | 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` | `string` | The timestamp of the block | +| `parentVoterSignature` | `string` | The parent voter signature of the block | + +### BlockHeartbeat + +```typescript +import { type BlockHeartbeat } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `blockId` | `string` | The ID of the block | +| `blockHeight` | `number` | The height of the block | +| `timestamp` | `string` | The timestamp of the block | + +### BlockSeal + +```typescript +import { type BlockSeal } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `blockId` | `string` | The id of the block | +| `executionReceiptId` | `string` | The execution receipt id of the block | + +### CollectionGuarantee + +```typescript +import { type CollectionGuarantee } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `collectionId` | `string` | The id of the block | +| `signerIds` | `string[]` | The signer ids of the block | + +### CompositeSignature + +```typescript +import { type CompositeSignature } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `f_type` | `string` | A type identifier used internally by FCL | +| `f_vsn` | `string` | FCL protocol version | +| `addr` | `string` | Flow Address (sans prefix) | +| `keyId` | `number` | Key ID | +| `signature` | `string` | Signature as a hex string | + +### CurrentUser + +```typescript +import { type CurrentUser } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `addr` | `string` | The public address of the current user | +| `cid` | `string` | A wallet specified content identifier for user metadata | +| `expiresAt` | `number` | A wallet specified time-frame for a valid session | +| `f_type` | `string` | A type identifier used internally by FCL | +| `f_vsn` | `string` | FCL protocol version | +| `loggedIn` | `boolean` | Whether or not the current user is logged in | +| `services` | `Service[]` | A list of trusted services that express ways of interacting with the current user's identity | + +### Event + +```typescript +import { type Event } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | 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` | `string` | 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. | + +### EventFilter + +```typescript +import { type EventFilter } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `eventTypes` | `string[]` | The event types to listen for | +| `addresses` | `string[]` | The addresses to listen for | +| `contracts` | `string[]` | The contracts to listen for | +| `startBlockId` | `string` | The block ID to start listening for events | +| `startHeight` | `number` | The block height to start listening for events | +| `heartbeatInterval` | `number` | The interval in milliseconds to send a heartbeat to the Access Node | + +### Interaction + +```typescript +import { type Interaction } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `tag` | `InteractionTag` | The type of interaction | +| `assigns` | `Record` | Assigned values for the interaction | +| `status` | `InteractionStatus` | The status of the interaction | +| `reason` | `string` | Reason for the current status | +| `accounts` | `Record` | Accounts involved in the interaction | +| `params` | `Record` | Parameters for the interaction | +| `arguments` | `Record` | Arguments for the interaction | +| `message` | `{ cadence: string; refBlock: string; computeLimit: number; proposer: string; payer: string; authorizations: string[]; params: Record[]; arguments: string[]; }` | Message details for the interaction | +| `proposer` | `string` | The proposer of the transaction | +| `authorizations` | `string[]` | The authorizations for the transaction | +| `payer` | `string[]` | The payer(s) of the transaction | +| `events` | `{ eventType: string; start: string \| number; end: string \| number; blockIds: string[]; }` | Event-related information | +| `transaction` | `{ id: string; }` | Transaction-related information | +| `block` | `{ id: string; height: string \| number; isSealed: boolean; }` | Block-related information | +| `account` | `{ addr: string; }` | Account-related information | +| `collection` | `{ id: string; }` | Collection-related information | +| `subscribeEvents` | `{ eventTypes: string[]; addresses: string[]; contracts: string[]; startBlockId: string; startHeight: number; heartbeatInterval: number; }` | Event subscription information | + +### InteractionAccount + +```typescript +import { type InteractionAccount } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `kind` | `InteractionResolverKind.ACCOUNT` | The kind of interaction resolver | +| `tempId` | `string` | Temporary identifier for the account | +| `addr` | `string` | The address of the account | +| `keyId` | `string \| number` | The key ID used for signing | +| `sequenceNum` | `number` | The sequence number for the account key | +| `signature` | `string` | The signature for the account | +| `signingFunction` | `any` | Function used for signing | +| `resolve` | `any` | Resolver function for the account | +| `role` | `{ proposer: boolean; authorizer: boolean; payer: boolean; param?: boolean; }` | Role of the account in the transaction | +| `authorization` | `any` | Authorization details for the account | + +### Key + +```typescript +import { type Key } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `sequenceNumber` | `number` | Sequence number of key used by the proposer of this transaction | +| `keyId` | `number` | The ID of the key in the account used by the proposer of this transaction | +| `address` | `string` | The address of the proposer of this transaction | + +### NodeVersionInfo + +```typescript +import { type NodeVersionInfo } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `semver` | `string` | The semver version of the node. | +| `commit` | `string` | The commit hash of the node. | +| `sporkId` | `string` | The spork id of the node. | +| `protocolVersion` | `number` | The protocol version of the node. | +| `sporkRootBlockHeight` | `number` | The spork root block height of the node. | +| `nodeRootBlockHeight` | `number` | The node root block height of the node. | + +### Provider + +```typescript +import { type Provider } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `address` | `string` | The blockchain address of the Wallet provider. | +| `name` | `string` | The name of the Wallet provider. | +| `icon` | `string` | The icon of the Wallet provider (may be a URL or a data URI). | +| `description` | `string` | A brief description of the Wallet provider. | +| `color` | `string` | The preferred color to represent the Wallet provider (e.g., for UI styling). | +| `supportEmail` | `string` | The support email address of the Wallet provider. | +| `website` | `string` | The website URL of the Wallet provider. | +| `is_installed` | `boolean` | Indicates whether the Wallet provider is installed (if applicable). | +| `requires_install` | `boolean` | Indicates whether the Wallet provider requires installation (if applicable). | +| `install_link` | `string` | The install link for the Wallet provider. | + +### Service + +```typescript +import { type Service } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `f_type` | `string` | A type identifier used internally by FCL | +| `f_vsn` | `string` | FCL protocol version | +| `type` | `string` | Service type | +| `method` | `string` | Service method | +| `uid` | `string` | Service uid | +| `endpoint` | `string` | Service endpoint | +| `provider` | `Provider` | Service provider object | +| `params` | `Record` | Service parameters | +| `data` | `Record` | Service data | +| `headers` | `Record` | Service headers | + +### Signature + +```typescript +import { type Signature } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `sequenceNumber` | `string` | Sequence number of the key used to perform this signature. | +| `keyId` | `number` | ID of the key in the account used to perform this signature. | +| `signature` | `string` | The signature represented as a hex string. | + +### StreamConnection + +```typescript +import { type StreamConnection } from "@onflow/fcl" +``` + + + +### Transaction + +```typescript +import { type Transaction } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `script` | `string` | The Cadence code used to execute this transaction. | +| `args` | `string[]` | The JSON-CDC encoded arguments passed in to the transaction. | +| `referenceBlockId` | `string` | The reference block id for this transaction. | +| `gasLimit` | `number` | The gas limit for the transaction. | +| `proposalKey` | `Key` | The key used by the proposer of this transaction. | +| `sequenceNumber` | `string` | Sequence number of the key used by the proposer of this transaction. | +| `keyId` | `number` | The ID of the key in the account used by the proposer of this transaction. | +| `address` | `string` | The address of the proposer of this transaction. | +| `payer` | `string` | Address of the payer of the transaction. | +| `proposer` | `string` | Address of the proposer of this transaction. | +| `authorizers` | `string[]` | Array of addresses of authorizers of this transaction. | +| `payloadSignatures` | `Signature[]` | The payload signatures for the transaction. | +| `envelopeSignatures` | `Signature[]` | The envelope signatures for the transaction. | + +### TransactionStatus + +```typescript +import { type TransactionStatus } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `blockId` | `string` | The ID of the Block the transaction is included in. | +| `status` | `TransactionExecutionStatus` | The execution status of the transaction | +| `statusString` | `string` | The status as as descriptive text (e.g. "FINALIZED"). | +| `statusCode` | `0 \| 1` | The result of the transaction, if executed (i.e. 0 for success, 1 for failure) | +| `errorMessage` | `string` | The error message of the transaction. | +| `events` | `Event[]` | The events for this result. | + + +## Types + +### EventStream + +```typescript +import { type EventStream } from "@onflow/fcl" +``` + + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `on` | `{ (channel: C, listener: (data: { events: Event[]; heartbeat: BlockHeartbeat; }[C]) => void): EventStream; (event: "close", listener: () => void): EventStream; (event: "error", listener: (err: any) => void): EventStream; }` | | +| `off` | `{ (event: C, listener: (data: { events: Event[]; heartbeat: BlockHeartbeat; }[C]) => void): EventStream; (event: "close", listener: () => void): EventStream; (event: "error", listener: (err: any) => void): EventStream; }` | | +| `close` | `() => void` | | + +### RawSubscriptionData + +```typescript +import { type RawSubscriptionData } from "@onflow/fcl" +``` + +Raw data returned by a subscription, which will vary depending on the topic and is not decoded + + +### SdkTransport + +```typescript +import { type SdkTransport } from "@onflow/fcl" +``` + +Transport interface for the Flow SDK that provides methods for sending interactions and subscribing to data + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `send` | `SendFn` | Function to send an interaction to the Flow blockchain | +| `subscribe` | `SubscribeFn` | Function to subscribe to real-time data from the Flow blockchain | + +### Subscription + +```typescript +import { type Subscription } from "@onflow/fcl" +``` + +A subscription object that allows managing the subscription lifecycle + +**Properties:** + +| Name | Type | Description | +| ---- | ---- | ----------- | +| `unsubscribe` | `() => void` | Function to unsubscribe from the subscription | + +### SubscriptionArgs + +```typescript +import { type SubscriptionArgs } from "@onflow/fcl" +``` + +Arguments for a subscription, which will vary depending on the topic + + +### SubscriptionData + +```typescript +import { type SubscriptionData } from "@onflow/fcl" +``` + +The data returned by a subscription, which will vary depending on the topic + + + +## Enums + +### FvmErrorCode + +```typescript +import { FvmErrorCode } from "@onflow/fcl" +``` + +Error codes defined by the Flow Virtual Machine (FVM) for various types of errors that can occur during transaction execution + +**Members:** + +| Name | Value | +| ---- | ----- | +| `UNKNOWN_ERROR` | -1 | +| `TX_VALIDATION_ERROR` | 1000 | +| `INVALID_TX_BYTE_SIZE_ERROR` | 1001 | +| `INVALID_REFERENCE_BLOCK_ERROR` | 1002 | +| `EXPIRED_TRANSACTION_ERROR` | 1003 | +| `INVALID_SCRIPT_ERROR` | 1004 | +| `INVALID_GAS_LIMIT_ERROR` | 1005 | +| `INVALID_PROPOSAL_SIGNATURE_ERROR` | 1006 | +| `INVALID_PROPOSAL_SEQ_NUMBER_ERROR` | 1007 | +| `INVALID_PAYLOAD_SIGNATURE_ERROR` | 1008 | +| `INVALID_ENVELOPE_SIGNATURE_ERROR` | 1009 | +| `FVM_INTERNAL_ERROR` | 1050 | +| `VALUE_ERROR` | 1051 | +| `INVALID_ARGUMENT_ERROR` | 1052 | +| `INVALID_ADDRESS_ERROR` | 1053 | +| `INVALID_LOCATION_ERROR` | 1054 | +| `ACCOUNT_AUTHORIZATION_ERROR` | 1055 | +| `OPERATION_AUTHORIZATION_ERROR` | 1056 | +| `OPERATION_NOT_SUPPORTED_ERROR` | 1057 | +| `BLOCK_HEIGHT_OUT_OF_RANGE_ERROR` | 1058 | +| `EXECUTION_ERROR` | 1100 | +| `CADENCE_RUNTIME_ERROR` | 1101 | +| `ENCODING_UNSUPPORTED_VALUE` | 1102 | +| `STORAGE_CAPACITY_EXCEEDED` | 1103 | +| `GAS_LIMIT_EXCEEDED_ERROR` | 1104 | +| `EVENT_LIMIT_EXCEEDED_ERROR` | 1105 | +| `LEDGER_INTERACTION_LIMIT_EXCEEDED_ERROR` | 1106 | +| `STATE_KEY_SIZE_LIMIT_ERROR` | 1107 | +| `STATE_VALUE_SIZE_LIMIT_ERROR` | 1108 | +| `TRANSACTION_FEE_DEDUCTION_FAILED_ERROR` | 1109 | +| `COMPUTATION_LIMIT_EXCEEDED_ERROR` | 1110 | +| `MEMORY_LIMIT_EXCEEDED_ERROR` | 1111 | +| `COULD_NOT_DECODE_EXECUTION_PARAMETER_FROM_STATE` | 1112 | +| `SCRIPT_EXECUTION_TIMED_OUT_ERROR` | 1113 | +| `SCRIPT_EXECUTION_CANCELLED_ERROR` | 1114 | +| `EVENT_ENCODING_ERROR` | 1115 | +| `INVALID_INTERNAL_STATE_ACCESS_ERROR` | 1116 | +| `INSUFFICIENT_PAYER_BALANCE` | 1118 | +| `ACCOUNT_ERROR` | 1200 | +| `ACCOUNT_NOT_FOUND_ERROR` | 1201 | +| `ACCOUNT_PUBLIC_KEY_NOT_FOUND_ERROR` | 1202 | +| `ACCOUNT_ALREADY_EXISTS_ERROR` | 1203 | +| `FROZEN_ACCOUNT_ERROR` | 1204 | +| `ACCOUNT_STORAGE_NOT_INITIALIZED_ERROR` | 1205 | +| `ACCOUNT_PUBLIC_KEY_LIMIT_ERROR` | 1206 | +| `CONTRACT_ERROR` | 1250 | +| `CONTRACT_NOT_FOUND_ERROR` | 1251 | +| `CONTRACT_NAMES_NOT_FOUND_ERROR` | 1252 | +| `EVM_EXECUTION_ERROR` | 1300 | + +### HashAlgorithm + +```typescript +import { HashAlgorithm } from "@onflow/fcl" +``` + + +**Members:** + +| Name | Value | +| ---- | ----- | +| `SHA2_256` | 1 | +| `SHA2_384` | 2 | +| `SHA3_256` | 3 | +| `SHA3_384` | 4 | +| `KMAC128_BLS_BLS12_381` | 5 | + +### InteractionResolverKind + +```typescript +import { InteractionResolverKind } from "@onflow/fcl" +``` + +Represents different kinds of interaction resolvers + +**Members:** + +| Name | Value | +| ---- | ----- | +| `ARGUMENT` | "ARGUMENT" | +| `ACCOUNT` | "ACCOUNT" | + +### InteractionStatus + +```typescript +import { InteractionStatus } from "@onflow/fcl" +``` + +Status of an interaction with the Flow blockchain + +**Members:** + +| Name | Value | +| ---- | ----- | +| `BAD` | "BAD" | +| `OK` | "OK" | + +### InteractionTag + +```typescript +import { InteractionTag } from "@onflow/fcl" +``` + +Represents different types of interactions with the Flow blockchain + +**Members:** + +| Name | Value | +| ---- | ----- | +| `UNKNOWN` | "UNKNOWN" | +| `SCRIPT` | "SCRIPT" | +| `TRANSACTION` | "TRANSACTION" | +| `GET_TRANSACTION_STATUS` | "GET_TRANSACTION_STATUS" | +| `GET_ACCOUNT` | "GET_ACCOUNT" | +| `GET_EVENTS` | "GET_EVENTS" | +| `PING` | "PING" | +| `GET_TRANSACTION` | "GET_TRANSACTION" | +| `GET_BLOCK` | "GET_BLOCK" | +| `GET_BLOCK_HEADER` | "GET_BLOCK_HEADER" | +| `GET_COLLECTION` | "GET_COLLECTION" | +| `GET_NETWORK_PARAMETERS` | "GET_NETWORK_PARAMETERS" | +| `SUBSCRIBE_EVENTS` | "SUBSCRIBE_EVENTS" | +| `GET_NODE_VERSION_INFO` | "GET_NODE_VERSION_INFO" | + +### SignatureAlgorithm + +```typescript +import { SignatureAlgorithm } from "@onflow/fcl" +``` + + +**Members:** + +| Name | Value | +| ---- | ----- | +| `ECDSA_P256` | 1 | +| `ECDSA_secp256k1` | 2 | +| `BLS_BLS12_381` | 3 | + +### SubscriptionTopic + +```typescript +import { SubscriptionTopic } from "@onflow/fcl" +``` + +Represents different topics that can be subscribed to for real-time data from the Flow blockchain + +**Members:** + +| Name | Value | +| ---- | ----- | +| `BLOCKS` | "blocks" | +| `BLOCK_HEADERS` | "block_headers" | +| `BLOCK_DIGESTS` | "block_digests" | +| `ACCOUNT_STATUSES` | "account_statuses" | +| `TRANSACTION_STATUSES` | "transaction_statuses" | +| `EVENTS` | "events" | + +### TransactionExecutionStatus + +```typescript +import { TransactionExecutionStatus } from "@onflow/fcl" +``` + +The execution status of the transaction. + +**Members:** + +| Name | Value | +| ---- | ----- | +| `UNKNOWN` | 0 | +| `PENDING` | 1 | +| `FINALIZED` | 2 | +| `EXECUTED` | 3 | +| `SEALED` | 4 | +| `EXPIRED` | 5 | + +### TransactionRole + +```typescript +import { TransactionRole } from "@onflow/fcl" +``` + +Represents different roles in a transaction + +**Members:** + +| Name | Value | +| ---- | ----- | +| `AUTHORIZER` | "authorizer" | +| `PAYER` | "payer" | +| `PROPOSER` | "proposer" | + + +--- \ No newline at end of file diff --git a/docs/tools/clients/fcl-js/scripts.md b/docs/tools/clients/fcl-js/scripts.md index 899850c15a..dbfbccc393 100644 --- a/docs/tools/clients/fcl-js/scripts.md +++ b/docs/tools/clients/fcl-js/scripts.md @@ -103,4 +103,4 @@ const response = await fcl.query({ console.log(response) // [Point{x:1, y:1}, Point{x:2, y:2}] ``` -To learn more about `query`, check out the [API documentation](./api.md#query). +To learn more about `query`, check out the [API documentation](./packages-docs/fcl/query.md). diff --git a/docs/tools/clients/fcl-js/sdk-guidelines.md b/docs/tools/clients/fcl-js/sdk-guidelines.md deleted file mode 100644 index ca153f0178..0000000000 --- a/docs/tools/clients/fcl-js/sdk-guidelines.md +++ /dev/null @@ -1,671 +0,0 @@ ---- -title: SDK Reference -sidebar_label: SDK Reference -sidebar_position: 2 ---- - -## 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: - -[](./api.md) - - -## Getting Started - -### Installing -NPM: -``` -npm install --save @onflow/fcl @onflow/types -``` - -Yarn: -``` -yarn add @onflow/fcl @onflow/types -``` - -### Importing the Library -```javascript -import * as fcl from "@onflow/fcl" -import * as types from "@onflow/types" -``` - -## Connect -[](./configure-fcl.md) - -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](/http-api/). 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: -```javascript -import { config } from "@onflow/fcl" - -config({ - "accessNode.api": "https://rest-testnet.onflow.org" -}) -``` - -## 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 -[](./api.md#getblock) - -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: - -``` -import * as fcl from "@onflow/fcl"; - -// Get latest block -const latestBlock = await fcl.latestBlock(true); // If true, get the latest sealed block - -// Get block by ID (uses builder function) -await fcl.send([fcl.getBlock(), fcl.atBlockId("23232323232")]).then(fcl.decode); - -// Get block at height (uses builder function) -await fcl.send([fcl.getBlock(), fcl.atBlockHeight(123)]).then(fcl.decode) -``` -Result output: [BlockObject](./api.md#blockobject) - -### Get Account -[](./api.md#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: - -```javascript -import * as fcl from "@onflow/fcl"; - -// Get account from latest block height -const account = await fcl.account("0x1d007d755706c469"); - -// Get account at a specific block height -fcl.send([ - fcl.getAccount("0x1d007d755706c469"), - fcl.atBlockHeight(123) -]); -``` -Result output: [AccountObject](./api.md#accountobject) - - -### Get Transactions -[](./api.md#gettransaction) - -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. - -| Status | Final | Description | -| ------------ | ------- | ----------- | -| 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 | - -```javascript -import * as fcl from "@onflow/fcl"; - -// Snapshot the transaction at a point in time -fcl.tx(transactionId).snapshot(); - -// Subscribe to a transaction's updates -fcl.tx(transactionId).subscribe(callback); - -// Provides the transaction once the status is finalized -fcl.tx(transactionId).onceFinalized(); - -// Provides the transaction once the status is executed -fcl.tx(transactionId).onceExecuted(); - -// Provides the transaction once the status is sealed -fcl.tx(transactionId).onceSealed(); -``` -Result output: [TransactionStatusObject](./api.md#gettransactionstatus) - - -### Get Events -[](./api.md#geteventsatblockheightrange) - -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: -``` -A.{contract address}.{contract name}.{event name} -``` - -Please read more about [events in the documentation](https://cadence-lang.org/docs/language/core-events). The exception to this standard are -core events, and you should read more about them in [this document](https://cadence-lang.org/docs/language/core-events). - -📖 **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: - -```javascript -import * as fcl from "@onflow/fcl"; - -// Get events at block height range -await fcl - .send([ - fcl.getEventsAtBlockHeightRange( - "A.7e60df042a9c0868.FlowToken.TokensWithdrawn", // event name - 35580624, // block to start looking for events at - 35580624 // block to stop looking for events at - ), - ]) - .then(fcl.decode); - -// Get events from list of block ids -await fcl - .send([ - fcl.getEventsAtBlockIds("A.7e60df042a9c0868.FlowToken.TokensWithdrawn", [ - "c4f239d49e96d1e5fbcf1f31027a6e582e8c03fcd9954177b7723fdb03d938c7", - "5dbaa85922eb194a3dc463c946cc01c866f2ff2b88f3e59e21c0d8d00113273f", - ]), - ]) - .then(fcl.decode); -``` -Result output: [EventObject](./api.md#event-object) - -### Get Collections -[](./api.md#getcollection) - -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: -```javascript -import * as fcl from "@onflow/fcl"; - -const collection = await fcl - .send([ - fcl.getCollection( - "cccdb0c67d015dc7f6444e8f62a3244ed650215ed66b90603006c70c5ef1f6e5" - ), - ]) - .then(fcl.decode); -``` -Result output: [CollectionObject](./api.md#collectionobject) - -### Execute Scripts -[](./api.md#query) - -Scripts allow you to write arbitrary non-mutating Cadence code on the Flow blockchain and return data. You can learn more about [Cadence here](https://cadence-lang.org/docs/language) and [scripts here](./scripts.md), 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. - -```javascript -import * as fcl from "@onflow/fcl"; - -const result = await fcl.query({ - cadence: ` - access(all) 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 - ], -}); -``` -Example output: -```bash -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](https://cadence-lang.org/docs). Here is an example transaction script: -``` -transaction(greeting: String) { - execute { - log(greeting.concat(", World!")) - } -} -``` - -📖 **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](../../../build/basics/transactions.md#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](../../../build/basics/transactions.md#signer-roles)** 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](../../../build/basics/transactions.md#signer-roles)** 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: -``` -transaction { - prepare(authorizer1: &Account, authorizer2: &Account) { } -} -``` - -📖 **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](https://cadence-lang.org/docs). - -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 -[](./api.md#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: - -```javascript -import * as fcl from "@onflow/fcl" - -await fcl.mutate({ - cadence: ` - transaction(a: Int) { - prepare(acct: &Account) { - log(acct) - log(a) - } - } - `, - args: (arg, t) => [ - arg(6, t.Int) - ], - limit: 50 -}) -``` - -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. - -### [Single party, single signature](../../../build/basics/transactions.md#single-party-single-signature) - -- Proposer, payer and authorizer are the same account (`0x01`). -- Only the envelope must be signed. -- Proposal key must have full signing weight. - -| Account | Key ID | Weight | -| ------- | ------ | ------ | -| `0x01` | 1 | 1000 | - -```javascript -// There are multiple ways to achieve this -import * as fcl from "@onflow/fcl" - -// FCL provides currentUser as an authorization function -await fcl.mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - proposer: currentUser, - payer: currentUser, - authorizations: [currentUser], - limit: 50, -}) - -// Or, simplified - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - authz: currentUser, // Optional. Will default to currentUser if not provided. - limit: 50, -}) - - -// Or, create a custom authorization function -const authzFn = async (txAccount) => { - return { - ...txAccount, - addr: "0x01", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 0, - signature - } - } - } -} - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - proposer: authzFn, - payer: authzFn, - authorizations: [authzFn], - limit: 50, -}) -``` - -### [Single party, multiple signatures](../../../build/basics/transactions.md#single-party-multiple-signatures) - -- 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. - -| Account | Key ID | Weight | -| ------- | ------ | ------ | -| `0x01` | 1 | 500 | -| `0x01` | 2 | 500 | - -**[](https://github.com/onflow/flow-go-sdk/tree/master/examples#single-party-multiple-signatures)** -```javascript -import * as fcl from "@onflow/fcl" - -const authzFn = async (txAccount) => { - return [ - { - ...txAccount, - addr: "0x01", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 0, - signature - } - } - }, - { - ...txAccount, - addr: "0x01", - keyId: 1, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 1, - signature - } - } - } - ] -} - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - proposer: authzFn, - payer: authzFn, - authorizations: [authzFn], - limit: 50, -}) -``` - -### [Multiple parties](../../../build/basics/transactions.md#multiple-parties) - -- 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 | Key ID | Weight | -| ------- | ------ | ------ | -| `0x01` | 1 | 1000 | -| `0x02` | 3 | 1000 | - -**[](https://github.com/onflow/flow-go-sdk/tree/master/examples#multiple-parties)** -```javascript -import * as fcl from "@onflow/fcl" - -const authzFn = async (txAccount) => { - return { - ...txAccount, - addr: "0x01", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 0, - signature - } - } - } -} - -const authzTwoFn = async (txAccount) => { - return { - ...txAccount, - addr: "0x02", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x02", - keyId: 0, - signature - } - } - } -} - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - proposer: authzFn, - payer: authzTwoFn, - authorizations: [authzFn], - limit: 50, -}) -``` - -### [Multiple parties, two authorizers](../../../build/basics/transactions.md#multiple-parties) - -- 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 `&Account` objects into an transaction - -| Account | Key ID | Weight | -| ------- | ------ | ------ | -| `0x01` | 1 | 1000 | -| `0x02` | 3 | 1000 | - -**[](https://github.com/onflow/flow-go-sdk/tree/master/examples#multiple-parties-two-authorizers)** -```javascript -import * as fcl from "@onflow/fcl" - -const authzFn = async (txAccount) => { - return { - ...txAccount, - addr: "0x01", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 0, - signature - } - } - } -} - -const authzTwoFn = async (txAccount) => { - return { - ...txAccount, - addr: "0x02", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x02", - keyId: 0, - signature - } - } - } -} - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account, acct2: &Account) {} - } - `, - proposer: authzFn, - payer: authzTwoFn, - authorizations: [authzFn, authzTwoFn], - limit: 50, -}) -``` - -### [Multiple parties, multiple signatures](../../../build/basics/transactions.md#multiple-parties) - -- 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). - -| Account | Key ID | Weight | -| ------- | ------ | ------ | -| `0x01` | 1 | 500 | -| `0x01` | 2 | 500 | -| `0x02` | 3 | 500 | -| `0x02` | 4 | 500 | - -```javascript -import * as fcl from "@onflow/fcl" - -const authzFn = async (txAccount) => { - return [ - { - ...txAccount, - addr: "0x01", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 0, - signature - } - } - }, - { - ...txAccount, - addr: "0x01", - keyId: 1, - signingFunction: async(signable) => { - return { - addr: "0x01", - keyId: 1, - signature - } - } - } - ] -} - -const authzTwoFn = async (txAccount) => { - return [ - { - ...txAccount, - addr: "0x02", - keyId: 0, - signingFunction: async(signable) => { - return { - addr: "0x02", - keyId: 0, - signature - } - } - }, - { - ...txAccount, - addr: "0x02", - keyId: 1, - signingFunction: async(signable) => { - return { - addr: "0x02", - keyId: 1, - signature - } - } - } - ] -} - -mutate({ - cadence: ` - transaction { - prepare(acct: &Account) {} - } - `, - proposer: authzFn, - payer: authzTwoFn, - authorizations: [authzFn], - limit: 50, -}) -``` - -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](#get-transactions). diff --git a/docs/tools/clients/fcl-js/transactions.md b/docs/tools/clients/fcl-js/transactions.md index fafea9b7f9..cf4243dc0b 100644 --- a/docs/tools/clients/fcl-js/transactions.md +++ b/docs/tools/clients/fcl-js/transactions.md @@ -74,7 +74,7 @@ const transaction = await fcl.tx(transactionId).onceExecuted() console.log(transaction) // The transactions status and events after being executed ``` -To learn more about `mutate`, check out the [API documentation](./api.md#mutate). +To learn more about `mutate`, check out the [API documentation](./packages-docs/fcl-core/getMutate.md). ## Transaction Finality diff --git a/docs/tools/wallet-provider-spec/user-signature.md b/docs/tools/wallet-provider-spec/user-signature.md index 5e30d87c0a..b1d751c67e 100644 --- a/docs/tools/wallet-provider-spec/user-signature.md +++ b/docs/tools/wallet-provider-spec/user-signature.md @@ -36,7 +36,7 @@ As a prerequisite, **FCL** is configured to point to the Wallet Provider's Authe > setting the **Wallet Discovery Url** to the wallet provider's **Authentication Endpoint** > by configuring fcl like this `config().put("discovery.wallet", "https://my-awesome-wallet-provider.com/fcl/authenticate")`. -Common Configuration Keys and additional info can be found here [How to Configure FCL](../clients/fcl-js/configure-fcl.md#common-configuration-keys) +Common Configuration Keys and additional info can be found here [How to Configure FCL](../clients/fcl-js/packages-docs/fcl/index.md#common-configuration-keys) 1. A user initiates authentication with the wallet provider via application UI 2. The wallet confirms a user's identity and sends back information used to configure **FCL** for future user actions in the application