fuels-ts Documentation

Fuel Network Typescript SDK

42,937 stars TypeScript TypeScript 1 file · ~83,527 tokens #fuel#typescript
RAW Doc

Technical Documentation: FuelLabs/fuels-ts

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

fuels-ts

Typescript SDK for Fuel.




Install ([docs](https://docs.fuel.network/docs/fuels-ts/getting-started/installation))

console
npm install fuels --save

Connect ([docs](https://docs.fuel.network/docs/fuels-ts/getting-started/connecting-to-the-network/))

Network URL
Mainnet https://mainnet.fuel.network/v1/graphql
Testnet https://testnet.fuel.network/v1/graphql
Localhost Running a local Fuel node
ts
import { Provider } from 'fuels';

const NETWORK_URL = 'https://mainnet.fuel.network/v1/graphql';

const provider = new Provider(NETWORK_URL);

const chainId = await provider.getChainId();
const gasConfig = await provider.getGasConfig();
const baseAssetId = await provider.getBaseAssetId();

console.log({ chainId, gasConfig, baseAssetId });

Create a new dApp ([docs](https://docs.fuel.network/docs/fuels-ts/creating-a-fuel-dapp/))

console
$ npm create fuels

◇ What is the name of your project? #
│ my-fuel-project
└

⚡️ Success! Created a fullstack Fuel dapp at: my-fuel-project.

Enjoy the `fuels` CLI ([docs](https://docs.fuel.network/docs/fuels-ts/fuels-cli/))

console
$ npm install fuels --save
$ npm fuels --help

Commands:
  init [options]      Create a sample `fuel.config.ts` file
  build [options]     Build Sway programs and generate Typescript for them
  deploy [options]    Deploy contracts to the Fuel network
  dev [options]       Start a Fuel node with hot-reload capabilities
  node [options]      Start a Fuel node using project configs
  typegen [options]   Generate Typescript from Sway ABI JSON files
  versions [options]  Check for version incompatibilities
  help [command]      Display help for command

In-depth docs:

  • fuels init — Creates a new fuels.config.ts file
  • fuels build — Build forc workspace and generate Typescript types for everything
  • fuels deploy — Deploy workspace contracts and save their IDs to JSON file
  • fuels dev — Start a Fuel node with hot-reload capabilities

Official Docs



Apps & Ecosystem

Get in Touch

Contribute

License

The primary license for this repo is Apache 2.0, see LICENSE.


Overview (`.changeset/README.md`)

Changesets

Hello and welcome! This folder has been automatically generated by @changesets/cli, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it in our repository

We have a quick list of common questions to get you started engaging with this project in
our documentation


Overview (`apps/create-fuels-counter-guide/README.md`)

This is a Vite project bootstrapped with create-fuels.

Getting Started

  1. Start the Fuel development server. This server will start a local Fuel node and provide hot-reloading for your smart contracts.
bash
npm run fuels:dev
  1. Start the Next.js development server.
bash
npm run dev

Deploying to Testnet

To learn how to deploy your Fuel dApp to the testnet, you can follow our Deploying to Testnet guide.

Learn More


Overview (`apps/demo-nextjs/README.md`)

This is a Next.js project bootstrapped with create-next-app.

Getting Started

First, run the development server:

bash
npm run dev
# or
yarn dev
# or
pnpm dev

Open http://localhost:3000 with your browser to see the result.

You can start editing the page by modifying app/page.tsx. The page auto-updates as you edit the file.

This project uses next/font to automatically optimize and load Inter, a custom Google Font.

Learn More

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

Deploy on Vercel

The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.

Check out our Next.js deployment documentation for more details.


Overview (`apps/demo-typegen/README.md`)

About

This is a simple demo composed by:

  • /contract — Sway contract
  • /src — Typescript project

Building

shell
pnpm build

Note See the scripts in package.json for detailed info.

This will:

  1. Compile Sway contract
  2. Generate types for it, inside src/generated-types

Overview (`apps/demo-wallet-sdk-react/README.md`)

This is a Next.js project bootstrapped with create-next-app.

Getting Started

First, run the development server:

bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev

Open http://localhost:3000 with your browser to see the result.

You can start editing the page by modifying app/page.tsx. The page auto-updates as you edit the file.

This project uses next/font to automatically optimize and load Inter, a custom Google Font.

Learn More

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

Deploy on Vercel

The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.

Check out our Next.js deployment documentation for more details.


Overview (`apps/docs/README.md`)

`docs`

docs is a private package for the Fuel documentation site.

Table of contents

Building

The build process will build out our snippets and the documentation.

sh
pnpm build

The build process generates testable scripts from the snippets and outputs them alongside the snippets. The corresponding typegen types are also generated and outputted in the src/snippets/typegend folder. All test scripts end with a .test.ts suffix.

Testing

This will build the snippets and run the generated tests. To test a specific environment (node or browser), the snippet should contain one of the following tags:

ts
/**
 * @group browser
 */

or

ts
/**
 * @group node
 */

If no environment is specified, it will run in the browser and node environments by default.

sh
pnpm test

Referencing snippets

To reference a snippet outside of the current directory, you need to use the following syntax (<<< @/):

md
`<<< @/../../path/to/snippet.ts#snippet-name{language:line-numbers}

To reference a snippet in the current directory, you can use the following syntax (<<< @./):

md
`<<< @./snippets/transaction-request/fetch-resources.ts#transaction-request-5{ts:line-numbers}

Overview (`internal/check-imports/README.md`)

This package validates importing all other packages.

It ensures all packages are ok and should build successfully.

If build fails, there might be something broken or misconfigured.


Overview (`internal/check-tests/README.md`)

This package validates our environment testing setup.

It ensures that environment specific functionalities should be supported by the SDK.

If one of these tests fails, it may indicate that an environment is configured incorrectly.


Overview (`internal/forc/README.md`)

`@internal/forc`

Binary wrapper for Forc


Overview (`internal/fuel-core/README.md`)

fuel-core

Binary wrapper for FuelCore


Overview (`packages/abi-coder/README.md`)

`@fuel-ts/abi-coder`

@fuel-ts/abi-coder is a sub-module for interacting with Fuel.

This module is responsible for encoding and decoding the Application Binary Interface (ABI) used by most smart contracts to interoperate between other smart contracts and clients. The ABI being encoded and decoded is specified here.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/abi-coder
# or
npm add @fuel-ts/abi-coder

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/abi-coder, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/abi-coder changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/abi-coder is Apache 2.0, see LICENSE.


Overview (`packages/abi-typegen/README.md`)

`@fuel-ts/abi-typegen`

Generate TypeScript bindings for Sway smart contracts.

See the full ABI-spec here.

Table of contents

Documentation

See Fuels-ts Documentation

Installation

sh
pnpm add @fuel-ts/abi-typegen
# or
npm add @fuel-ts/abi-typegen

Help

console
$ fuels-typegen -h

Generate Typescript from Sway ABI JSON files

Usage: fuels-typegen [options]

Options:
  -V, --version                output the version number
  -i, --inputs <path|glob...>  Input paths/globals to your ABI JSON files
  -o, --output <dir>           Directory path for generated files
  -c, --contract               Generate types for Contracts [default]
  -s, --script                 Generate types for Scripts
  -p, --predicate              Generate types for Predicates
  -S, --silent                 Omit output messages
  -h, --help                   display help for command

Generating types

When using the package in a standalone fashion, its bin is prefixed with fuels-.

sh
npx fuels-typegen -i ./out/debug/*-abi.json -o ./src/contracts

Programmatic API

ts
import { ProgramTypeEnum, runTypegen } from "@fuel-ts/abi-typegen";

  const cwd = process.cwd();
  const input = './abis/**-abi.json'
  const output = './types'
  const filepaths = [ './abis/a-abi.json', './abis/b-abi.json' ]
  const programType = ProgramTypeEnum.CONTRACT;

  // using input global
  await runTypegen({ cwd, input, output, programType });

  // using filepaths' array
  await runTypegen({ cwd, filepaths, output, programType });
}

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Note that in this example we will interact with the fuels bin directly.

We just need to call it with the typegen command, and the rest feels the same.

sh
npx fuels typegen -i ./out/debug/*-abi.json -o ./src/contracts

Type's Conversion Table

The table below describes how Sway types are converted from/to Typescript.

Sway Example TS:input TS:output
u8 255 BigNumberish number
u16 65535 BigNumberish number
u32 4294967295 BigNumberish number
u64 0xFFFFFFFFFFFFFFFF BigNumberish BN
str anything string string
bool true boolean boolean
b256 0x000... string string
b512 fuel1a7r... string string
tuples (MyType, MyType) [MyType, MyType] [MyType, MyType]
enums enum MyEnum { y: (), n: () } MyEnum = Enum<{ y: [], n: [] }> MyEnum = Enum<{ y: [], n: [] }>
structs MyStruct { a: u8, b: u16 } MyStruct MyStruct
vectors Vec<MyType> MyType[] MyType[]
options Option<MyType> Option<MyType> Option<MyType>
raw untyped ptr 123 BigNumberish BN

For more info on Sway types, click here

Contributing

In order to contribute to @fuel-ts/abi-typegen, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/abi-typegen changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/abi-typegen is Apache 2.0, see LICENSE.


Overview (`packages/account/README.md`)

`@fuel-ts/account`

@fuel-ts/account is a sub-module for interacting with Fuel.

This module contains the class to manage a private key and signing for a standard Externally Owned Account (EOA).

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/account
# or
npm add @fuel-ts/account

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/account, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/account changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/account is Apache 2.0, see LICENSE.


Overview (`packages/address/README.md`)

`@fuel-ts/address`

@fuel-ts/address is a sub-module for interacting with Fuel.

This module contains the utilities for encoding and decoding address and contract ids between B256 and other address formats.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/address
# or
npm add @fuel-ts/address

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/address, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/address changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/address is Apache 2.0, see LICENSE.


Overview (`packages/contract/README.md`)

`@fuel-ts/contract`

@fuel-ts/contract is a sub-module for interacting with Fuel.

This module allows for a simple way to serialize calls and transactions to an on-chain contract and deserialize their results and emitted logs.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/contract
# or
npm add @fuel-ts/contract

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/contract, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/contract changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/contract is Apache 2.0, see LICENSE.


Overview (`packages/create-fuels/README.md`)

create-fuels

A scaffolding CLI tool for creating new full-stack Fuel projects.

Usage

bash
pnpm create fuels

Getting Started

  1. Start the Fuel development server. This server will start a local Fuel node and provide hot-reloading for your smart contracts.
bash
npm run fuels:dev

# or
npx fuels dev
  1. Start the Next.js development server.
bash
npm run dev

Deploying to Testnet

To learn how to deploy your Fuel dApp to the testnet, you can follow our Deploying to Testnet guide.

Learn More

Contributing

  • To make changes to the template locally, you will need to have a .env.local file in the templates/nextjs directory with the following contents:
bash
NEXT_PUBLIC_FUEL_NETWORK_URL=http://127.0.0.1:4000/v1/graphql

This file is populated automatically for end users when they run pnpm create fuels.


Overview (`packages/crypto/README.md`)

`@fuel-ts/crypto`

@fuel-ts/crypto is a sub-module for interacting with Fuel.

This module contains the utilities for encrypting and decrypting data objects using initialization vectors (IV) and Advanced Encryption Standard (AES).

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/crypto
# or
npm add @fuel-ts/crypto

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/crypto, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/crypto changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/crypto is Apache 2.0, see LICENSE.


Overview (`packages/errors/README.md`)

`@fuel-ts/errors`

@fuel-ts/errors is a sub-module for interacting with Fuel.

This package contains core utilities regarding throwing errors internally inside of the fuels-ts SDK.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/errors
# or
npm add @fuel-ts/errors

Internal usage

ts
import { FuelError, ErrorCodes } from "@fuel-ts/error";

export function singleImport() {
  throw new FuelError(FuelError.CODES.INVALID_DATA, "Invalid data");
}

export function multipleImports() {
  throw new FuelError(ErrorCodes.INVALID_DATA, "Invalid data");
}

Test Utilities

You can use the expectToThrowFuelError test utility when asserting errors.

ts
// can also be imported from `fuels` when using the umbrella package
import { expectToThrowFuelError } from "@fuel-ts/errors";

import { myFn } from "...";

describe('this and that' () => {
  const code = FuelError.CODES.INVALID_DATA;

  it("should throw FuelError", async () => {
    const expected = new FuelError(code);
    await expectToThrowFuelError(() => myFn(), expected);
  });

  it("should throw something else", async () => {
    const expected = new FuelError(code);
    const fn = () => expectToThrowFuelError(() => myFn(), expected)
    await expect(fn).rejects.toThrow('Something else');
  });
})

External usage

ts
import { FuelError, Provider } from "fuels";

type Locale = "pt-BR" | "bs-BA" | "en-GB";

const currentLocale: Locale = "pt-BR";

const i18nDict = {
  pt-BR: {
    [FuelError.CODES.INVALID_DATA]: "Dados inválidos",
  },
  bs-BA: {
    [FuelError.CODES.INVALID_DATA]: "Nevažeći podaci",
  },
  en-GB: {
    [FuelError.CODES.INVALID_DATA]: "Invalid data",
  },
};

function translateError(e: unknown) {
  const { code } = FuelError.parse(e);
  return i18nDict[currentLocale][code];
}

function main() {
  try {
    const p = new Provider("0004:tƨoʜlɒɔol//:qttʜ");
    console.log(p);
  } catch (e) {
    const prettyError = translateError(e);
    console.log({ prettyError });
  }
};

Contributing

In order to contribute to @fuel-ts/errors, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/errors changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/errors is Apache 2.0, see LICENSE.


Overview (`packages/hasher/README.md`)

`@fuel-ts/hasher`

@fuel-ts/hasher is a sub-module for interacting with Fuel.

This module contains several common hashing utilities.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/hasher
# or
npm add @fuel-ts/hasher

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/hasher, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/hasher changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/hasher is Apache 2.0, see LICENSE.


Overview (`packages/logger/README.md`)

`@fuel-ts/logger`

@fuel-ts/logger is a sub-module for logging within the Fuel TS ecosystem.

A logging component that can be used to log messages to the console or to a file.

Table of contents

Installation

sh
pnpm add @fuel-ts/logger
# or
npm add @fuel-ts/logger

Contributing

In order to contribute to @fuel-ts/logger, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/logger changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/logger is Apache 2.0, see LICENSE.


Overview (`packages/math/README.md`)

`@fuel-ts/math`

@fuel-ts/math is a sub-module for interacting with Fuel.

This module contains helpful math utilities to work with decimal, hex, Uint8Array.

Math is based in bn.js library, which helps us to do all kinds of calculations safely, doesn't matter the size of the number.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/math
# or
npm add @fuel-ts/math

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/math, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/math changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/math is Apache 2.0, see LICENSE.


Overview (`packages/merkle/README.md`)

`@fuel-ts/merkle`

@fuel-ts/merkle is a sub-module for interacting with Fuel.

This module contains:

  • src/binary - Utilities for working with binary merkle trees
  • src/common — Shared utilities for testing and deploying merkle trees
  • src/sum — Utilities for computing merkle tree roots
  • src/sparse — Utilities for working with sparse merkle trees to help provide efficient proofs of non-inclusion

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/merkle
# or
npm add @fuel-ts/merkle

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/merkle, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/merkle changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/merkle is Apache 2.0, see LICENSE.


Overview (`packages/program/README.md`)

`@fuel-ts/program`

@fuel-ts/program is a sub-module for interacting with Sway programs on Fuel.

This module allows for a simple way to serialize calls and transactions to Sway programs like Scripts and Contracts.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/program
# or
npm add @fuel-ts/program

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/program, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/program changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/program is Apache 2.0, see LICENSE.


Overview (`packages/recipes/README.md`)

`@fuel-ts/recipes`

@fuel-ts/recipes is a sub-module for interacting with Sway programs on Fuel.

This module exports TypeScript recipes of Sway programs.

It currently includes recipes for:

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/recipes
# or
npm add @fuel-ts/recipes

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/recipes, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/recipes changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/recipes is Apache 2.0, see LICENSE.


Overview (`packages/transactions/README.md`)

`@fuel-ts/transactions`

@fuel-ts/transactions is a sub-module for interacting with Fuel.

This module contains various constants and functions for encoding and decoding serialized transactions.

Table of contents

Documentation

See Fuels-ts Documentation

Usage

Installation

sh
pnpm add @fuel-ts/transactions
# or
npm add @fuel-ts/transactions

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/transactions, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/transactions changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/transactions is Apache 2.0, see LICENSE.


Overview (`packages/utils/README.md`)

`@fuel-ts/utils`

@fuel-ts/utils is a sub-module for interacting with Fuel.

It's a collection of utilities and test utilities that may be useful in other places.

Table of contents

Documentation

See Fuels-ts Documentation

Installation

sh
pnpm add @fuel-ts/utils
# or
npm add @fuel-ts/utils

Utilities

ts
import { normalizeString } from "@fuel-ts/utils";

console.log(normalizeString("fuel-labs"));
// FuelLabs

Test Utilities

ts
import { safeExec } from "@fuel-ts/utils/test-utils"; // note the `test` suffix

console.log(safeExec(() => 123));
// { error: null, result: 123 }

console.log(
  safeExec(() => {
    throw new Error("Some error");
  }),
);
// { error: (Error: 'Some error'), result: null }

Contributing

In order to contribute to @fuel-ts/utils, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/utils changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/utils is Apache 2.0, see LICENSE.


Overview (`packages/versions/README.md`)

`@fuel-ts/versions`

@fuel-ts/versions is a sub-module for interacting with Fuel.

It automatically assembles all supported versions of the Fuel toolchain, including:

  • FUELS — comes from /packages/fuels/package.json
  • FUEL_CORE — comes from /internal/fuel-core/VERSION
  • FORC — comes from /internal/forc/VERSION

There is a prebuild script to ensure that the src/index.ts file never goes outdated.

Aditionally, the library can be used as a CLI tool to help checking/validating user environments.

Table of contents

Documentation

See Fuels-ts Documentation

Installation

sh
pnpm add @fuel-ts/versions
# or
npm add @fuel-ts/versions

Programmatic Usage

ts
import { versions } from "@fuel-ts/versions";

console.log(versions);
// { FUELS: '0.21.2', FUEL_CORE: '0.14.0', FORC: '0.30.0' }

CLI Usage

console
$ npx fuels-versions
You have all the right versions! ⚡
┌───────────┬───────────┬─────────────────┐
│           │ Supported │ Yours / System  │
├───────────┼───────────┼─────────────────┤
│ Forc      │ 0.30.0    │ 0.30.0          │
├───────────┼───────────┼─────────────────┤
│ Fuel-Core │ 0.14.0    │ 0.14.0          │
└───────────┴───────────┴─────────────────┘

Full SDK Installation

Alternatively, we recommend you install the complete SDK using the umbrella package:

sh
pnpm add fuels
# or
npm add fuels

Contributing

In order to contribute to @fuel-ts/versions, please see the main fuels-ts monorepo.

Changelog

The @fuel-ts/versions changelog can be found at CHANGELOG.

License

The primary license for @fuel-ts/versions is Apache 2.0, see LICENSE.


Overview (`templates/nextjs/README.md`)

This is a Next.js project bootstrapped with create-fuels.

Getting Started

  1. Start the Fuel development server. This server will start a local Fuel node and provide hot-reloading for your smart contracts.
bash
npm run fuels:dev
  1. Start the Next.js development server.
bash
npm run dev

Deploying to Testnet

To learn how to deploy your Fuel dApp to the testnet, you can follow our Deploying to Testnet guide.

Learn More


Overview (`templates/vite/README.md`)

This is a Vite project bootstrapped with create-fuels.

Getting Started

  1. Start the Fuel development server. This server will start a local Fuel node and provide hot-reloading for your smart contracts.
bash
npm run fuels:dev
  1. Start the Next.js development server.
bash
npm run dev

Deploying to Testnet

To learn how to deploy your Fuel dApp to the testnet, you can follow our Deploying to Testnet guide.

Learn More


Overview (`packages/recipes/src/contracts/src14/README.md`)

SRC-14: Owned Proxy Contract

The contract folder contains a pre-built version of the owned proxy contract, its abi and storage-slots JSON files.

Check also the forc notes.


Apps Docs Src Index (`apps/docs/src/index.md`)

The Fuel TypeScript SDK

The Fuel TypeScript SDK provides methods and utilities in TypeScript, for developing on or interacting with the Fuel network and its ecosystem.

Using the SDK you can:

  • Deploy, interact with, and test Sway contracts.
  • Bootstrap a dApp and local development environment using the create fuels CLI.
  • Generate and import wallets from private key, mnemonic, or JSON and safely store them on the client.
  • Craft custom transactions and mutate them by adding resources, policies and signers and submit them.
  • Generate types for Sway programs using typegen to give end-to-end type safety.

Version

This documentation was generated using Fuels v{{fuels}}, Fuel Core v{{fuelCore}}, Sway v{{forc}}, and Forc v{{forc}}.

API Documentation

The Complete API documentation for the SDK is available here.


Apps Docs Src Guide Contracts Index (`apps/docs/src/guide/contracts/index.md`)

Contracts

In the Fuel Network, contracts play a crucial role in facilitating interactions between users and the decentralized applications built on top of the network. Once you've deployed a contract, you may want to perform various tasks such as:

  1. Calling contract methods;
  2. Configuring call and transaction parameters like gas price, byte price, and gas limit;
  3. Forwarding coins and gas in your contract calls;
  4. Reading and interpreting returned values and logs.

For instance, consider a Sway contract with two ABI methods called echo_str_8(str[8]) and echo_u8(u8). After deploying the contract, you can call the methods as follows:

<<< @./snippets/introduction.ts#method-calls{ts:line-numbers}

The example above demonstrates a simple contract call using default configurations. The following sections will explore how to further configure various parameters for contract calls, allowing for more advanced interactions with your deployed contracts in the Fuel Network.


Apps Docs Src Guide Cookbook Index (`apps/docs/src/guide/cookbook/index.md`)

Cookbook

This section covers more advanced use cases that can be satisfied by combining various features of the SDK. As such, it assumes that you have already made yourself familiar with the previous chapters of this book.


Apps Docs Src Guide Creating A Fuel Dapp Index (`apps/docs/src/guide/creating-a-fuel-dapp/index.md`)

Creating a Fuel dApp

npm create fuels is a command line tool that helps you scaffold a new full-stack Fuel dApp. In this guide, we will create a new counter dApp using npm create fuels and add decrement functionality to it. The final result will look like this:

You can also check it live, deployed to the Testnet:

Initializing the project

The first step is to run the command:

::: code-group

sh-vue [npm]
npm create fuels@{{fuels}}
sh-vue [pnpm]
pnpm create fuels@{{fuels}}
sh-vue [bun]
bun create fuels@{{fuels}}

:::

Once you run the command, you will be asked to choose a name for your project:

md
◇ What is the name of your project?
│ my-fuel-project
└

The tool will scaffold the project and install the necessary dependencies for you. You will then be greeted with this message:

md
⚡️ Success! Created a fullstack Fuel dapp at my-fuel-project

To get started:

- cd into the project directory: cd my-fuel-project
- Start a local Fuel dev server: pnpm fuels:dev
- Run the frontend: pnpm dev

-> TS SDK docs: https://docs.fuel.network/docs/fuels-ts/
-> Sway docs: https://docs.fuel.network/docs/sway/
-> If you have any questions, check the Fuel forum: https://forum.fuel.network/

Directory Structure

The project scaffolded by npm create fuels has roughly the following directory structure:

md
my-fuel-project
├── src
│ ├── components
│ │ └── ...
│ ├── hooks
│ │ └── ...
│ ├── lib.tsx
│ ├── App.tsx
│ └── ...
├── sway-programs
│ ├── contract
│ │ └── ...
│ └── ...
├── public
│ └── ...
├── fuels.config.ts
├── package.json
└── ...

It is a Vite project with a few extra files and folders. Let's take a closer look at some of the important ones:

`./fuels.config.ts`

This is the configuration file for the fuels CLI, the CLI and tooling that powers this project under the hood. It makes sure that all of your Sway programs are continuously compiled and deployed to your local Fuel node. You can read more about the fuels.config.ts file in the Fuels CLI documentation.

`./sway-programs/contract/src/main.sw`

This is where our Sway contract lives. Out of the box, it is a simple counter contract that can only be incremented. We will add a decrement functionality to it in the next step.

`./src/App.tsx`

This file contains the source code for the frontend of our dApp.

`./src/components/Contract.tsx`

This file contains the source code for the 'Contract' tab in the UI, this is where the contract calling logic is implemented.

Dev Environment Setup

Now that we have our project scaffolded, let's set up our development environment.

Let's first start our Fuel Dev server. This will start a local Fuel node and continuously compile and deploy our Sway programs to it.

::: code-group

sh [npm]
npm fuels:dev
sh [pnpm]
pnpm fuels:dev
sh [bun]
bun run fuels:dev

:::

Once the server is up and running, we can start our Next.js development server in another terminal.

::: code-group

sh [npm]
pnpm dev
sh [pnpm]
pnpm dev
sh [bun]
bun run dev

:::

You should now be able to see the dApp running at http://localhost:5173. Go ahead and connect a wallet to the dApp. You can choose the Burner Wallet from the list if you don't want to connect a wallet.

Now, you can try changing the contents of the ./sway-programs/contract/src/main.sw file and see the changes reflected in the 'Contract' tab in the UI without having to restart the server.

Note: You may wish to learn more about how you could create a Fuel dApp that uses predicates, check out our Working with Predicates guide.

Adding Decrement Functionality

To add decrement functionality to our counter, we will have to do two things: 1. Add a decrement_counter function to our Sway contract, and 2. Modify the ./src/components/Contract.tsx file to add a button that calls this function.

1. Modifying the Sway Contract

To add a decrement_counter function to our Sway contract, we will modify the ./sway-programs/contract/src/main.sw file.

There are two steps when adding a new function to a Sway program. The first step is to specify the function's ABI.

Towards the top of the file, you will find the ABI section for the contract. Let's add a new function to it:

<<< @/../../create-fuels-counter-guide/sway-programs/contract/src/main.sw#create-fuels-counter-guide-abi{rust:line-numbers}

The second step is to implement the function.

We will add the implementation of the decrement_counter function right below the increment_counter function.

<<< @/../../create-fuels-counter-guide/sway-programs/contract/src/main.sw#create-fuels-counter-guide-impl{rust:line-numbers}

2. Modifying the Frontend

We will now add a new button to the frontend that will call the decrement_counter function when clicked. To do this, we will modify the ./src/App.tsx file.

First, we will add a function called decrementCounter similar to the incrementCounter function:

<<< @/../../create-fuels-counter-guide/src/components/Contract.tsx#create-fuels-counter-guide-on-decrement-react-function{ts:line-numbers}

Second, we will add a new button to the UI that will call the decrementCounter function when clicked:

tsx
<Button onClick={onDecrementPressed} className="mt-6">
  Decrement Counter
</Button>

Congratulations! You should now be able to see the counter dApp running at http://localhost:5173 with our newly added decrement functionality.

You can find the complete source code of the dApp we built here.

Whenever you want to add a new feature to your dApp and quickly prototype things, you can follow the same steps we followed in this guide.

3. Extending the contract testing suite (Optional)

Testing our smart contract is a good practice to ensure that our implementation is working as expected. It also give assurances down the line if we decide to change the implementation of our contract.

We write our test in the #[test] macro within our Sway contract, these can be inline within our Sway contract or in a separate file.

For the guide, we'll add a test for our new decrement_counter function in the ./sway-programs/contract/src/main.sw file:

<<< @/../../create-fuels-counter-guide/sway-programs/contract/src/main.sw#create-fuels-counter-guide-sway-contract-test{rust:line-numbers}

After writing our test, we can run either using forc test or via PNPM using pnpm test:forc.

4. Extending the integration test suite (Optional)

Testing the integration with your smart contract isn't essential, but it's good practice to ensure that your application is working as expected. It also gives you the ability to test your application in a controlled environment against a local node.

We've provided some examples for each program type in the ./test directory of your project. But let's also add a test for our new decrement_counter function in the ./test/contract.test.ts file:

<<< @./snippets/decrement-counter.ts#full{ts:line-numbers}

The template also comes with a UI testing setup using Playwright. We can add a test for our new decrement_counter function in the ./test/ui/ui.test.ts file:

<<< @/../../create-fuels-counter-guide/test/ui/ui.test.ts#decrement-counter-ui-test{ts:line-numbers}

Next Steps

  • Now that you have a basic counter dApp running and have the npm create fuels workflow powering you, you can start building more complex dApps using the Fuel Stack. A good place to start for ideas and reference code is the Sway Applications Repo.

  • As you may have noticed, there are different types of programs in your dApp, feel free to explore Predicates and Scripts, which are both important differentiators in the Fuel Stack.

  • If you want to deploy your dApp to the testnet, check out our Deploying a dApp to Testnet guide.

  • If you want to further validate the functionality of your dApp and program types, check out the test directory in your create fuels project. Couple this with our testing guide to get a better understanding of how to test your dApp.

  • If you have any questions or need help, feel free to reach out to us on the Official Fuel Forum.

  • If you want to learn more about the Fuel Stack, check out the Fuel Docs.


Apps Docs Src Guide Encoding Index (`apps/docs/src/guide/encoding/index.md`)

Encoding

Encoding is the process of serializing data into a format that is suitable for transmission or storage. This is important for blockchains as it enables state minimization and efficiency, as well as for generating proofs.

Fortunately, if you are working with program types on the Fuel network such as calling contracts, the SDK will handle encoding for you automatically. It will adhere to the argument encoding specification, so you can work with data in its expected format rather than as bytecode.

However, there may be scenarios where you want to manipulate call or return data yourself or even implement your own serialization specification. This guide will cover how to encode and decode data using the SDK.


Apps Docs Src Guide Errors Index (`apps/docs/src/guide/errors/index.md`)

Errors

All errors thrown from the SDK are instances of the FuelError class which will have an accompanying ErrorCode.

Error Codes

Here is a list of the expected error codes the SDK can throw. These error codes are used to help understand the error that has been thrown with potential resolutions.

`ABI_MAIN_METHOD_MISSING`

When your ABI does not have a main method.

This can be resolved by adding a main method to your ABI. This is prevalent in scripts and predicates that must contain a main method.

`ABI_TYPES_AND_VALUES_MISMATCH`

When the arguments supplied to the function do not match the minimum required input length.

Check that the arguments supplied to the function match the required type.

`ACCOUNT_REQUIRED`

When an Account is required for an operation. This will usually be in the form of a Wallet.

It could be caused during the deployments of contracts when an account is required to sign the transaction. This can be resolved by following the deployment guide here.

`ASSET_BURN_DETECTED`

When you are trying to send a transaction that will result in an asset burn.

Add relevant coin change outputs to the transaction, or enable asset burn in the transaction request.

`CONFIG_FILE_NOT_FOUND`

When a configuration file is not found. This could either be a fuels.config.[ts,js,mjs,cjs] file or a TOML file.

Ensure that the configuration file is present in the root directory of your project.

`CONFIG_FILE_ALREADY_EXISTS`

When a configuration file already exists in the root directory of your project.

You can not run fuels init more than once for a given project. Either remove the existing configuration file or update it.

`CONVERTING_FAILED`

When converting a big number into an incompatible format.

Ensure that the value you've supplied to the big number is compatible with the value you are converting to.

`CONTRACT_SIZE_EXCEEDS_LIMIT`

When the contract size exceeds the maximum contract size limit.

Ensure that the contract size is less than the maximum contract size limit, of 100 KB. This can be validated by checking the bytecode length of the contract.

`DUPLICATED_POLICY`

When there are more than policies with the same type, for a transaction.

Ensure that there are no duplicate (by type) policies for a transaction.

`ERROR_BUILDING_BLOCK_EXPLORER_URL`

When more than one of the following options is passed: path, address, txId, blockNumber.

Check that only one of the above is passed.

`FUNCTION_NOT_FOUND`

When the function with the given name, signature or selector is not found in the ABI.

Check that the function name, signature or selector is correct and exits on the ABI.

`FUNDS_TOO_LOW`

When the funds in the account are lower than the required amount.

Ensure that the account has enough funds to cover the transaction.

`GAS_LIMIT_TOO_LOW`

When the gas limit is lower than the minimum gas limit.

Increase the gas limit to be greater than the minimum gas limit.

`GAS_PRICE_TOO_LOW`

When the gas price is lower than the minimum gas price.

Increase the gas price to be greater than the minimum gas price.

`HD_WALLET_ERROR`

A hardware wallet will throw for unsupported configurations.

The error message will determine which element of the configuration is incorrect. It could be due to the public or private key or when configuring to/from an extended key.

`INVALID_CHECKSUM`

Checksum validation failed for the provided mnemonic.

Ensure that the mnemonic is correct.

`INVALID_CHUNK_SIZE_MULTIPLIER`

When the chunk size multiplier is not between 0 and 1.

Ensure that the chunk size multiplier is a number that it is between 0 and 1.

`INVALID_CONFIGURABLE_CONSTANTS`

When the program type either: does not have configurable constants to be set; or the provided configurable constant does not belong to the program type, as defined by its ABI.

Ensure the configurable constants provided are correct and are defined in ABI.

`INVALID_COMPONENT`

When an expected component is not found in the ABI or is malformed.

Ensure that you have correctly formed Sway types for Arrays and Vectors.

`INVALID_CREDENTIALS`

When the password provided is incorrect.

Ensure that the password is correct.

`INVALID_DATA`

When the value being passed is not considered valid, as defined by the function.

Check the function signature and ensure that the passed value is valid.

`INVALID_ENTROPY`

When the entropy is not: between 16 and 32 bytes; a multiple of 4.

Ensure that the entropy is between 16 and 32 bytes and a multiple of 4.

`INVALID_EVM_ADDRESS`

When the provided EVM address is invalid.

Ensure that the EVM address is valid.

`INVALID_INPUT_PARAMETERS`

When the provided input parameters are not valid.

The error message will determine which parameter is missing. It could be that the provided program type is not one of the following contract, script, or predicate.

`INVALID_MNEMONIC`

When the supplied mnemonic is invalid.

Check the message for more details. It could be that the mnemonic phrase word length is not one of the following: 12, 15, 18, 21, or 24 lengths.

`INVALID_PASSWORD`

When the provided password is incorrect.

Ensure that the password is correct.

`INVALID_POLICY_TYPE`

When the supplied policy type is invalid for the given Script.

Check the policy type is defined in PolicyType.

`INVALID_PROVIDER`

When unable to connect to the Provider or Network supplied to a method on the Fuel class.

Check that the Provider or Network is supplied correctly.

`INVALID_PUBLIC_KEY`

When the provided public key is invalid.

Ensure that the public key is valid.

`INVALID_RECEIPT_TYPE`

When the receipt type is invalid.

Check the type is within ReceiptType.

`INVALID_REQUEST`

When the request to the Fuel node fails, error messages are propagated from the Fuel node.

Check the error message from the Fuel node.

`INVALID_SEED`

When the seed length is not between 16 and 64 bytes.

Ensure that the seed length is between 16 and 64 bytes.

`INVALID_TRANSACTION_INPUT`

When the input type is invalid.

Check the type is within InputType.

`INVALID_TRANSACTION_OUTPUT`

When the output type is invalid.

Check the type is within OutputType.

`INVALID_TRANSACTION_STATUS`

When the transaction status received from the node is unexpected.

Check the status received is within TransactionStatus.

`UNSUPPORTED_TRANSACTION_TYPE`

When the transaction type from the Fuel Node is not supported.

The type is within TransactionType.

`INVALID_TTL`

When the TTL is less than or equal to zero.

Ensure that the TTL is a number and that the TTL is greater than zero.

`INVALID_WORD_LIST`

When the word list length is not equal to 2048.

The word list provided to the mnemonic length should be equal to 2048.

`INVALID_URL`

When the URL provided is invalid.

Ensure that the URL is valid.

`JSON_ABI_ERROR`

When an ABI type does not conform to the correct format.

It is usually caused by an incorrect type/s within your program, check our type docs here for information on the types we support and their expected format.

`LOG_TYPE_NOT_FOUND`

When the log type ID supplied can not be found in the ABI.

Check that the log type ID is correct and exists in the ABI.

`MISSING_CONNECTOR`

A connector is missing when it's required for a given operation.

Ensure that a connector has been supplied to the Account or Wallet.

`MISSING_PROVIDER`

A provider is missing when it's required for a given operation.

It could be caused by the provider not being set for either an Account or a Wallet - use the connect method to attach a provider.

`MISSING_REQUIRED_PARAMETER`

When a required parameter has not been supplied to a given method.

The error message will determine which parameter is missing. This could be caused during type generation when neither inputs nor filepaths are supplied (at least one is required).

`NODE_INFO_CACHE_EMPTY`

When the Fuel Node info cache is empty; This is usually caused by not being connected to the Fuel Node.

Ensure that the provider has connected to a Fuel Node successfully.

`INSUFFICIENT_FUNDS_OR_MAX_COINS`

This error can occur during a funding operation or when calling the getResourcesToSpend method. It indicates one of the following issues:

Insufficient Balance: The specified account does not have enough balance to cover the required amount.

UTXO Limit Exceeded: Although the account has enough total funds, the funds are spread across too many UTXOs (coins). The blockchain limits how many UTXOs can be used in a single transaction, and exceeding this limit prevents the transaction from being processed.

First, to be sure what the real reason is, you can fetch the balance of the assetId to ensure that the account has enough funds to cover the amount. After knowing the reason, to solve you can:

For Insufficient Balance: Acquire additional funds in the required asset to meet the amount needed.

For UTXO Limit Exceeded: Combine UTXOs to reduce their number and meet the network's requirements. You can follow this guide to learn how to combine UTXOs effectively.

`TIMEOUT_EXCEEDED`

When the timeout has been exceeded for a given operation.

Check that you're connected to the network and that the network is stable.

`TYPE_NOT_FOUND`

When the type with the given type ID is not found in the ABI.

Check that the type ID is correct and exists in the ABI.

`TYPE_NOT_SUPPORTED`

When an unexpected type has been detected - the error message will determine which type is incorrect.

Check the type against your ABI and ensure that it is correct. You can find a list of all our types here.

`UNSUPPORTED_FUEL_CLIENT_VERSION`

When the version of the Fuel Node you are targeting is not supported by the client you are accessing it from.

Check the version of the Fuel Node and use a compatible version of the SDK to target it.

`WALLET_MANAGER_ERROR`

A wallet manager will throw for a multitude of reasons. The error message will determine which element of the configuration is incorrect.

It could be that the passphrase is incorrect and/or the wallet does not exist in the manager.

`WORKSPACE_NOT_DETECTED`

When the workspace is not detected in the directory indicated in the message.

Ensure that the workspace is present in the directory specified.

`UNKNOWN`

In cases where the error hasn't been mapped yet, this code will be used.

If you believe you found a bug, please report the issue to the team.

`MAX_INPUTS_EXCEEDED`

When the number of transaction inputs exceeds the maximum limit allowed by the blockchain.

`MAX_OUTPUTS_EXCEEDED`

When the number of transaction outputs exceeds the maximum limit allowed by the blockchain.

`CHANGE_OUTPUT_COLLISION`

This error occurs when there's a conflict between the change output specified in the transaction request and the one specified in the assembleTx parameters:

  1. The transaction request already has a change output set for a specific asset ID and address
  2. The assembleTx parameters specify a different change output for the same asset ID

`DUPLICATE_CHANGE_OUTPUT_ACCOUNT`

This error occurs when there are duplicate entries for the same asset ID with different changeOutputAccount values in the accountCoinQuantities parameter of the assembleTx method:

  1. The accountCoinQuantities parameter contains multiple entries for the same asset ID
  2. Each entry specifies a different changeOutputAccount for the same asset ID

`RESPONSE_BODY_EMPTY`

This error occurs when the response from the server has an empty body. The issue will generally lie with the connection setup from your environment and the RPC.


Apps Docs Src Guide Fuel Asm Index (`apps/docs/src/guide/fuel-asm/index.md`)

Fuel ASM

Instruction set for the FuelVM.


This is a wrapped WASM version of the fuel-asm Rust crate:

Usage

This example demonstrates how to use the FuelAsm to create a program, represented as a vector of instructions, and then convert it to bytes.

<<< @./snippets/fuel-asm.ts#main{ts:line-numbers}

Reference

The above usage is the Typescript equivalent of the original example in Rust.

<<< @../../../../fuel-asm-example/src/main.rs#main{rs:line-numbers}

See Also


Apps Docs Src Guide Fuels Cli Index (`apps/docs/src/guide/fuels-cli/index.md`)

Fuels CLI

The quickest way to build full stack Fuel dApps.

  • fuels init — Creates a new fuels.config.ts file
  • fuels build — Build forc workspace and generate Typescript types for everything
  • fuels deploy — Deploy workspace contracts and save their IDs to JSON file
  • fuels dev — Start local Fuel Core node and build + deploy on every file change

Getting started

Imagine you have this file structure:

sh
my-fuel-dapp # NextJS app or similar
├── sway-programs # Forc's workspace
│   ├── src
│   ├── ...
│   └── Forc.toml
├── public
│   └── ...
├── src
│   ├── app
│   ├── ...
├   └── sway-programs-api # Type-safe generated API
└── package.json

Prerequisites

The Fuel Toolchain and its components (namely forc and fuel-core) are pre-requisite for several operations with the Fuels CLI. For example:

  • Building out contracts using fuels build requires forc.
  • Deploying contracts locally using fuels deploy requires fuel-core.

Follow the installation guide if you don't have them installed already.

Installation

Add it to your my-fuel-dapp project:

::: code-group

console-vue [npm]
npm install fuels@{{fuels}} --save
console-vue [pnpm]
pnpm add fuels@{{fuels}}
console-vue [bun]
bun add fuels@{{fuels}}

:::

Double-checking

console-vue
npx fuels@{{fuels}} -v

Next Step

Use fuels init to create a fuel.config.ts file.


Apps Docs Src Guide Getting Started Index (`apps/docs/src/guide/getting-started/index.md`)

Getting Started

Welcome to fuels Typescript SDK!

We prepared some guides to walk you through your first steps:

  1. Installation
  2. Connecting to the Network
  3. Running a local Fuel node
  4. React Example
  5. CDN Usage
  6. Next Steps

Apps Docs Src Guide Predicates Index (`apps/docs/src/guide/predicates/index.md`)

Predicates

Predicates in Sway are specific types of programs that return a boolean value, meaning they function like rules that a transaction must follow to be valid.

They don't have access to the information written on the blockchain – they make decisions based solely on the received parameters.

These predicates are pure functions, which means they don't cause any unintended side effects.

The key difference here is that instead of checking these rules directly on the blockchain, we check them 'off' the blockchain first. Once we're confident they're valid, we then record the transaction on the blockchain.

This method is not only more efficient but also helps to prevent traffic jams on the network and makes transactions cheaper. It does so by reducing the need for repetitive calculations on the blockchain.

Working with Predicates

Users can send assets to the predicate address as they would to any other address on the blockchain. To spend funds stored at the predicate address, users must provide the original byte code of the predicate and, if required, the predicate data.

The predicate data relates to the parameters received by the predicate's main function. This data comes into play during the byte code's execution. If the main function does not have any parameters then there is no data to be provided, therefore we do not provide the predicate data.

If the predicate is validated successfully, the funds will be accessible. Otherwise, the SDK will throw a validation error.

In the next section, we provide a step-by-step guide on how to interact with a predicate to validate your transactions.

Debugging Predicates

Currently there is no way to debug a predicate yet. In the meantime, a practical workaround is to initially write, test, and debug your predicate as a script, which has more debugging tools available. Once it's working as expected, you can then convert it back into a predicate.


Apps Docs Src Guide Provider Index (`apps/docs/src/guide/provider/index.md`)

Provider

The Provider lets you connect to a Fuel node (docs) and interact with it, encapsulating common client operations in the SDK. Those operations include querying the blockchain for network, block, and transaction-related info (and more), as well as sending transactions to the blockchain.

All higher-level abstractions (e.g. Wallet, Contract) that interact with the blockchain go through the Provider, so it's used for various actions like getting a wallet's balance, deploying contracts, querying their state, etc.

<<< @./snippets/provider-instantiation.ts#provider-instantiation{ts:line-numbers}

You can find more examples of Provider usage here.


Apps Docs Src Guide Scripts Index (`apps/docs/src/guide/scripts/index.md`)

Scripts

A script, in Sway, is runnable bytecode on the chain which executes once to perform some task. A script can return a single value of any type.

Learn more about scripts here.


Apps Docs Src Guide Testing Index (`apps/docs/src/guide/testing/index.md`)

Testing

This guide will teach you how to test Sway applications using the Typescript SDK.

While we use Vitest internally, we don't enforce any specific testing library or framework, so you can pick whichever you feel comfortable with.

Not using Typescript?

See also:

  1. Using forc test
  2. Using the Rust SDK

Apps Docs Src Guide The Utxo Model Index (`apps/docs/src/guide/the-utxo-model/index.md`)

The UTXO Model

In UTXO (Unspent Transaction Output) based systems, each coin is unique, similar to how physical currency bills have different denominations.

A UTXO represents a coin with a specific amount, similar to having a $10 or $5 bill. It's crucial to understand this unique feature of UTXOs, as it differs significantly from Ethereum's account-based system.

In Ethereum, balances are tracked as cumulative totals, similar to a bank account, rather than as distinct 'coins' or 'bills'.

Why UTXOs Matter

Each UTXO corresponds to a unique coin and has an associated amount. This model allows for greater transparency and control in cryptocurrency transactions. Understanding UTXOs is key for effectively managing and tracking your digital assets.

How UTXOs Work

When you create a transaction, you will use UTXOs from your account to fund it. Here's a step-by-step explanation:

1. Selecting UTXOs: The SDK selects one or more UTXOs from your account that together are equal to or greater than the transaction amount plus the transaction fee.

2. Spending UTXOs: These selected UTXOs are used to fund the transaction and cover the transaction fee. For example, if you need to send $15 and the transaction fee is $1, and you have $10 and $6 UTXOs, both will be used.

3. New UTXOs: If the total value of the selected UTXOs exceeds the transaction amount plus the transaction fee, the difference is returned to your account as new UTXOs. For instance, if you spend a $20 UTXO for a $15 transaction with a $1 fee, a new UTXO worth $4 will be created as change and added back to your account.

In summary, the original UTXOs used in the transaction are marked as spent and cannot be used again. The new UTXOs are available for future transactions.

Suppose you have the following UTXOs in your account:

  • $10 UTXO
  • $20 UTXO

You want to send $15 to someone, and the transaction fee is $1. Here's what happens:

  • The $20 UTXO is selected to fund the $15 transaction and cover the $1 fee.
  • The transaction is completed and the $20 UTXO is spent.
  • A new $15 UTXO is generated to the recipient, and a new $4 UTXO (change) is created and added to your account.

Apps Docs Src Guide Transactions Index (`apps/docs/src/guide/transactions/index.md`)

Transactions

A transaction is a way of interacting with a Fuel blockchain and can include actions like transferring assets, deploying contracts and minting tokens. All of which are possible through the SDK by using simple utility methods or building out more custom transactions.

Transferring assets is the most common transaction type and can be be executed by calling the transfer function from an account to a recipient address:

<<< @./snippets/transaction.ts#transactions-1{ts:line-numbers}

Deploying and interacting with contracts are other common transactions. More information on this can be found in the contracts guide, either through the contract deployment guide or the contract interaction guide.

This guide will discuss how to create and modify transactions to fit bespoke use cases, as well as submit them to the network using transactional policies and parameters. As well as retrieving information about submitted transactions.


Apps Docs Src Guide Types Index (`apps/docs/src/guide/types/index.md`)

Types

As you dive deeper into the SDK, it's essential to understand the variety of internal types available in both FuelVM and Sway, as well as their corresponding SDK equivalents. This section aims to provide you with the necessary knowledge to efficiently work with these types.

Overview

In this section, you will learn about:

  1. FuelVM and Sway Internal Types: Discover the various types used within FuelVM and Sway, and their significance in different contexts.

  2. SDK Equivalents: Explore the corresponding types available in the SDK, and understand their similarities and differences compared to FuelVM and Sway internal types.

  3. Type Usage: Gain insights into how to effectively use these types in your projects or applications, with examples and best practices.

  4. Type Conversion: Learn the techniques and methods for converting between FuelVM, Sway, and SDK types, guaranteeing smooth interoperability and consistent data integrity.

Additional Resources

As you progress through the documentation, you may find it helpful to refer back to the following resources:

  • Sway Documentation: Explore the Sway documentation homepage for an overview of Sway Types, as well as other sections.

  • The Fuel Book: A comprehensive guide to the whole Fuel ecosystem.


Apps Docs Src Guide Utilities Index (`apps/docs/src/guide/utilities/index.md`)

Utilities

Utilities are a set of helpers that can be used for various purposes.


Apps Docs Src Guide Wallets Index (`apps/docs/src/guide/wallets/index.md`)

Wallets

Wallets can be used for many important things, for instance:

  1. Checking your balance;
  2. Transferring coins to a destination address or contract;
  3. Signing messages and transactions;
  4. Paying for network fees when sending transactions or deploying smart contracts.

Wallets Instances

The SDK has multiple classes related to a Wallet instance:

  • Wallet: Works simply like a wrapper providing methods to create and instantiating WalletUnlocked and WalletLocked instances.

  • WalletLocked: Provides the functionalities for a locked wallet.

  • WalletUnlocked: Provides the functionalities for an unlocked wallet.

  • Account: Provides an abstraction with basic functionalities for wallets or accounts to interact with the network. It is essential to notice that both WalletLocked and WalletUnlocked extend from the Account class.

Let's explore these different approaches in the following sub-chapters.

Note: Keep in mind that you should never share your private/secret key. And in the case of wallets that were derived from a mnemonic phrase, never share your mnemonic phrase. If you're planning on storing the wallet on disk, do not store the plain private/secret key and do not store the plain mnemonic phrase. Instead, use WalletManager to encrypt its content first before saving it to disk.


Apps Docs .Spellcheck.Yml (`apps/docs/.spellcheck.yml`)

matrix:

  • name: SPCheck
    aspell:
    lang: en
    dictionary:
    encoding: utf-8
    wordlists:
    - apps/docs/spell-check-custom-words.txt

    pipeline:
    • pyspelling.filters.context:
      context_visible_first: true
      escapes: \[\~] delimiters: # Ignore all code blocks - open: '(?s)^(?P<open> *{3,}\s*(\w+\s*,?\s*)+.*?)$'
      close: "^( `{3,})$"
      # Ignore lines starting with <<< @
      - open: "^(<<<.
      )"
      close: "$"
    • pyspelling.filters.markdown:
      markdown_extensions:
      - pymdownx.superfences:
    • pyspelling.filters.html:
      comments: false
      ignores:
      - code
      - pre

    sources:

    • "apps/docs/src/*.md"
    • "apps/docs/src/**/*.md"
    • "apps/docs/src///*.md"
      default_encoding: utf-8

Apps Docs CHANGELOG (`apps/docs/CHANGELOG.md`)

@fuel-ts/docs

0.43.11

0.43.10

0.43.9

0.43.8

0.43.7

0.43.6

0.43.5

Patch Changes

  • Add typegen support and docs for new types, by @camsjams (See #1342)

0.43.4

0.43.3

0.43.2

0.43.1

0.43.0

Minor Changes

  • chainInfo is now fetched and cached on all Providers when they are initialized. With this release, you now need to initialize a Provider like so:
    ts
    const provider = await Provider.create(url);
    For the full list of breaking-changes, please see this PR, by @Dhaiwat10 (See #1181)
  • Remove chainId from the Predicate constructor. You don't need to pass in chainId anymore since you are passing in a provider already, by @Dhaiwat10 (See #1181)
  • using FuelError across all packages, by @Torres-ssf (See #1230)

0.42.9

0.42.8

0.42.7

0.42.6

Patch Changes

0.42.5

0.42.4

0.42.3

0.42.2

0.42.1

0.42.0

Minor Changes

  • use simulate instead of get on BaseInvocationScope class, by @Torres-ssf (See #1179)

Patch Changes

0.41.6

0.41.5

0.41.4

Patch Changes

  • Deprecate tx funding call option as all txs require a spendable input, by @danielbate (See #1136)

0.41.3

0.41.2

0.41.1

0.41.0

Minor Changes

0.40.0

Minor Changes

  • Upgrade to fuel-core 0.18.1 and forc 0.40.1, by @Dhaiwat10 (See #986)

0.39.2

Patch Changes

  • Proxing bin entries to fix locally broken symlinks and re-shaping example contract into Typegen demo app, by @arboleya (See #1037)

0.39.1

Patch Changes

0.39.0

Minor Changes

  • #953 8332026a Thanks @Dhaiwat10! - You can now query for a list of blocks using the getBlocks method on the Provider class.

  • #954 bf6214cc Thanks @Dhaiwat10! - The addMissingVariable helper has been renamed to estimateTxDependencies, and some documentation around it has been added.

Patch Changes

  • #931 0ff4eeab Thanks @Dhaiwat10! - The second param timeParameters in the produceBlocks helper was required until now. This is now an optional param, in line with the GQL API and the Rust SDK.

0.38.1

0.38.0

Minor Changes

0.38.0

Minor Changes


Apps Docs Nodemon.Config.Json (`apps/docs/nodemon.config.json`)

{
"verbose": true,
"ext": "ts",
"watch": ["../../packages"],
"ignore": ["/*.d.ts", "/.map", "**/.js", "/out/release/"]
}


Apps Docs Package.Json (`apps/docs/package.json`)

{
"private": true,
"name": "docs",
"version": "0.43.11",
"description": "",
"type": "module",
"scripts": {
"dev": "nodemon --config nodemon.config.json -x 'run-s build:snippets build:docs-api dev:docs'",
"build": "run-s build:snippets build:docs",
"preview": "run-s build:snippets build:docs-api preview:docs",
"test": "cd ../.. && pnpm run test:filter apps/docs",
"build:snippets": "run-s clear:snippets wrap:snippets build:forc",
"build:docs": "run-s build:docs-app build:docs-api",
"build:docs-app": "vitepress build",
"build:docs-api": "cd ../docs-api && pnpm build && cp -r ./src/api ../docs/dist",
"preview:docs": "vitepress preview",
"preview:docs-api": "pnpm vite preview --port 5174 --outDir ../docs-api/src/api",
"dev:docs": "run-p docs:dev preview:docs-api",
"docs:dev": "vitepress dev",
"clear:snippets": "tsx ./scripts/clear-snippets.mts",
"wrap:snippets": "tsx ./scripts/wrap-snippets.ts",
"build:forc": "pnpm fuels --silent build --deploy",
"type:check": "pnpm tsc --noEmit --project tsconfig.emit.json"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@fuel-ts/errors": "workspace:",
"@fuel-ts/versions": "workspace:
",
"fuels": "workspace:*",
"ethers": "6.13.5"
},
"devDependencies": {
"@types/markdown-it": "14.1.2",
"glob": "10.4.5",
"markdown-it": "14.1.0",
"nodemon": "3.1.9",
"vitepress-plugin-search": "1.0.4-alpha.22",
"vitepress": "1.6.3",
"vue": "3.5.13"
}
}


Apps Docs Spell Check Custom Words (`apps/docs/spell-check-custom-words.txt`)

ABI
ABI's
abigen
ABIs
ALU
ANDs
API's
APIs
args
arity
ASM
AssemblyScript
AssetId
AST
async
Atomique
Autoloading
backend
backends
backoff
backtrace
backtraces
BigNumber
Bitfield
bitmask
Bitwise
Bitwise
blazingly
blockchain
blockchain's
blockchains
boolean
Booleans
BrowserStack
bytecode
callee
CDN
CEI
Celestia
Changelog
CLI
CLI
CLIs
codebase
codegen
CODEOWNERS
codespace
codespaces
coinbase
Coinbase
collateralized
Collateralized
compositional
config
config
configurables
Config
configs
ContractFactory
cryptocurrency
Cryptocurrency
cryptographic
cryptographically
curve25519
customizable
customizations
dapp
dApp
DApp
dApps
DateTime
DCA
decrypt
decrypted
Decrypted
decrypting
Decrypting
decrypts
deployable
deployer
Deserialization
deserializing
destructuring
deterministically
dev
DEX
DEX
differentiators
Dockerized
DOT
dropdown
DSL
EcDSA
ECDSA
EdDSA
encodings
endian
entrancy
enum
enums
env
EOA
ERC
ETH
Ethereum
Ethereum's
EVM
EVM's
executablity
Executablity
exponentiate
Exponentiate
extractable
estimateTxDependencies
FIPS
forc
formatter
frontend
FuelLabs
fuelup
Fuelup
FuelVM
FuelVM's
fullstack
FVM
Github
GitHub
graphql
graphQL
GraphQL
GraphViz
growable
Gwei
hardcoded
HD
hexlified
hoc
Homebrew
HRP
http
https
IaaS
IDE
IDEs
incentivise
incrementor
indexable
Infura
initializer
initializers
inlined
inlines
inlining
instantiation
INSTR
INSTRs
integrations
interoperable
intra
intrinsics
Intrinsics
IPFS
js
JSON
JSON
JWT
keccak
keystore
Keystore
KiB
launchTestNode
lhs
Libs
localhost
lookups
LSP
LSP
Macbook
macOS
MacOS
mainnet
mempool
merkle
Merkle
MiB
monomorphization
monorepo
monorepos
MULTICALL
namespace
namespaces
natively
neovim
nonces
npm
nvm
onboarding
onchain
OOB
orchestrator
Orchestrator
ORs
overriden
params
parsable
pnpm
PoA
PoS
postcondition
Postcondition
Postgres
PostgreSQL
PoW
pre
preimage
prepended
prerelease
programmatically
PRs
pseudocode
Pseudocode
queryable
quickstart
reaccessing
Reaccessing
relayer
relayers
repo
repos
reuploaded
rhs
RPC
runnable
runtime
runtimes
SauceLabs
scaffolded
scalable
Scalable
schemas
Schemas
ScriptTransactionRequest
SDK
SDK's
SDKs
secp
Secp
semver
Sepolia
SHA
SHA-256
SMT
SMTs
SQLx
SRC
stateful
struct
struct's
structs
Structs
subcommand
subcommands
Subcommands
subcurrency
Subcurrency
submodule
subtree
subtrees
superABI
superABIs
SuperABIs
superset
supertrait
supertraits
supertraits
Supertraits
SUT
Sway
TAI
testnet
testnets
TLDR
TODO
TOML
toolchain
toolchains
transactional
tsconfig
TTL
tuple's
turbofish
TxParameters
TypeChain
typeclass
typedoc
typegen
Typegen
typesafe
TypeScript
UI
unary
underflows
unhashed
unspendable
untrusted
unwritable
Unwritable
updatable
Updatable
Upgradability
Upgradable
URI
frontend's
urql
USD
USDC
USDT
UTF
Utils
Utils
UTXO
UTXOs
utxos
validator
validators
vercel
Vercel
Vite
Vitest
VM
VMs
VS
VSCode
WalletLocked
walletsConfig
WalletUnlocked
WASM
WebAssembly
WETH
workspace
workspaces
Workspaces
WSL
XOR
XORs
YAML
RESTful
EIP
AssembleTxParams
AssembleTxResponse
AssembleTx
Unparsed
zero'd
asm
io
asm
github
vm
PreconfirmationSuccessStatus
PreconfirmationFailureStatus
OutputChange
OutputVariable


Apps Docs Tsconfig.Emit.Json (`apps/docs/tsconfig.emit.json`)

{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "ES2022",
"outDir": "./dist",
"rootDir": "./",
"baseUrl": "./"
},
"include": ["src//guide"],
"exclude": ["src/
/typegend"]
}


Apps Docs Tsconfig.Json (`apps/docs/tsconfig.json`)

{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "ES2022",
"outDir": "./dist",
"rootDir": "./",
"baseUrl": "./"
},
"include": ["src", "test", "scripts", "./.vitepress/**/*.ts", "types"]
}


Apps Docs Turbo.Json (`apps/docs/turbo.json`)

{
"$schema": "https://turborepo.org/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build", "prebuild"],
"outputs": ["dist/"],
"inputs": ["src/
", ".vitepress/", "types/"]
}
}
}


Apps Docs Src Guide Contracts Call Parameters (`apps/docs/src/guide/contracts/call-parameters.md`)

Call Parameters

When interacting with contracts, you can configure specific parameters for contract calls using the callParams method. The available call parameters are:

  1. forward
  2. gasLimit

Note: Setting transaction parameters is also available when calling contracts. More information on this can be found at Transaction Parameters.

The contract in use in this section has the following implementation:

<<< @/../../docs/sway/return-context/src/main.sw#return-context-contract{rust:line-numbers}

Forward Parameter

The forward parameter allows the sending of a specific amount of coins to a contract when a function is called. This is useful when a contract function requires coins for its execution, such as transferring funds to another account or contract.

The forward parameter helps you control the resources allocated to the contract call and offers protection against potentially costly operations.

<<< @./snippets/call-parameters/forward.ts#forward{ts:line-numbers}

Gas Limit Parameter

The gasLimit refers to the maximum amount of gas that can be consumed specifically by the contract call itself, separate from the rest of the transaction.

<<< @./snippets/call-parameters/gas-fee.ts#gas-fee{ts:line-numbers}

Call Parameter `gasLimit` vs Transaction Parameter `gasLimit`

The call parameter gasLimit sets the maximum gas allowed for the actual contract call, whereas the transaction parameter gasLimit (see Transaction Parameters) sets the maximum gas allowed for the entire transaction and constrains the gasLimit call parameter. If the call parameter gasLimit is set to a value greater than the available transaction gas, then the entire available transaction gas will be allocated for the contract call execution.

If you don't set the gasLimit for the call, the transaction gasLimit will be applied.

Setting Both Parameters

You can set both call parameters and transaction parameters within the same contract function call.

<<< @./snippets/call-parameters/setting-both-parameters.ts#setting-both-parameters{ts:line-numbers}


Apps Docs Src Guide Contracts Configurable Constants (`apps/docs/src/guide/contracts/configurable-constants.md`)

Configurable Constants

Sway introduces a powerful feature: configurable constants. When creating a contract, you can define constants, each assigned with a default value.

Before deploying the contract, you can then redefine the value for these constants, it can be all of them or as many as you need.

This feature provides flexibility for dynamic contract environments. It allows a high level of customization, leading to more efficient and adaptable smart contracts.

Defining Configurable Constants

Below is an example of a contract in which we declare four configurable constants:

<<< @/../../docs/sway/echo-configurables/src/main.sw#configurable-constants-1{rust:line-numbers}

In this contract, the function echo_configurables returns the values of the configurable constants, which we'll use for demonstrating the setting of configurables via the SDK.

Setting New Values For Configurable Constants

During contract deployment, you can define new values for any/all of the configurable constants. The example below shows setting of one configurable constant, while the others will have default values.

<<< @./snippets/configurable-constants.ts#setting-configurable-constant{ts:line-numbers}

Please note that when assigning new values for a Struct, all properties of the Struct must be defined. Failing to do so will result in an error:

<<< @./snippets/configurable-constants.ts#invalid-configurable{ts:line-numbers}


Apps Docs Src Guide Contracts Contract Balance (`apps/docs/src/guide/contracts/contract-balance.md`)

Contract Balance

When working with contracts, it's crucial to be aware of the available contract balance of an asset while paying for costly operations. This guide will explain the getBalance method in the Contract class, which allows you to check a contract's available balance.

The `getBalance` Method

The Contract.getBalance method retrieves the available balance of a specific asset on your contract. This method is particularly useful for determining the remaining balance after sending assets to a contract and executing contract calls.

It is important to note that this method returns the total available contract balance, regardless of how often assets have been sent to it or spent.

Checking Contract Balance

Consider a simple contract that transfers a specified amount of a given asset to an address:

<<< @/../../docs/sway/transfer-to-address/src/main.sw#full{rust:line-numbers}

The transfer function has three parameters:

  1. amount_to_transfer: The amount that is being transferred.

  2. asset: The address of the deployed contract token.

  3. recipient: The address of the receiver's wallet.

The transfer function calls the built-in Sway function transfer_to_address, which does precisely what the name suggests.

Let's execute this contract and use the getBalance method to validate the remaining asset amount the contract has left to spend.

<<< @./snippets/contract-balance.ts#example{ts:line-numbers}

In this example, we first forward an asset amount greater than the amount required for the transfer, and then we execute the contract call.

Finally, we use the getBalance method to confirm that the contract balance is precisely the total forwarded amount minus the transferred amount.


Apps Docs Src Guide Contracts Custom Contract Calls (`apps/docs/src/guide/contracts/custom-contract-calls.md`)

Custom Contract Call

In certain scenarios, your use case may require more control over how contract calls are prepared and submitted.

For instance, imagine a liquidity pool contract where users can deposit a specific asset to receive some form of benefit. To enhance the experience and make it more attractive, one could use a predicate to cover the transaction fees. This way, users only need to provide the asset they wish to deposit without worrying about the fees.

There are two main ways to customize a contract call:

Approach 1: Customize `assembleTx` Parameters

In most cases, this isn’t necessary. However, if you need precise control, you can specify the parameters passed to assembleTx, which is used internally to estimate and fund the transaction.

Here’s how it works:

<<< @./snippets/custom-contract-calls/assemble-tx-parameters.ts#assemble-tx-parameters-1{ts:line-numbers}

Approach 2: Manually Call `assembleTx`

You can also retrieve the transaction request from the invocation scope and manually call assembleTx on it. Just like the approach 1 this gives you full control over how the transaction is assembled and funded.

<<< @./snippets/custom-contract-calls/call.ts#custom-contract-call-1{ts:line-numbers}

There are 2 details here that there are essential in this flow

  1. fromRequest:
    This sets the transaction request extracted from the invocation scope. It ensures that any manual changes you’ve applied persist and are used when the transaction is executed.

  2. { skipAssembleTx: true } option:
    It tells the SDK to skip the automatic assembleTx step during the .call() execution, since we’ve already manually assembled and funded the transaction using provider.assembleTx(). Skipping this step prevents the SDK from re-estimating the transaction and ensures the custom logic remains intact, such as using a predicate as the fee payer.


Apps Docs Src Guide Contracts Dependency Estimation (`apps/docs/src/guide/contracts/dependency-estimation.md`)

Transaction Dependency Estimation

In variable outputs, we mention that a contract call might require you to manually specify external contracts or variable outputs.

However, by default the SDK always automatically estimates these dependencies and double-checks if everything is in order whenever you invoke a contract function or attempt to send a transaction.

The SDK uses the Provider.estimateTxDependencies method to set any missing dependencies identified during the estimation process. This requires simulating the transaction a few times in the background.

While relying on the SDK's automatic estimation is a decent default behavior, we recommend manually specifying the dependencies if they are known in advance to avoid the performance impact of the estimation process.


Apps Docs Src Guide Contracts Deploying Contracts (`apps/docs/src/guide/contracts/deploying-contracts.md`)

Deploying Contracts

To deploy a contract using the SDK, you can use the ContractFactory. This process involves collecting the contract artifacts, initializing the contract factory, and deploying the contract.

The SDK utilizes two different deployment processes, depending on the contract's size. The threshold for the contract size is dictated by the chain and can be queried:

<<< @./snippets/deploying-contracts/get-max-size.ts#full{ts:line-numbers}

It either uses a single create transaction to deploy the entire contract bytecode, or it splits the contract bytecode into multiple chunks, deploys them as blobs (on chain data accessible to the VM), and then generates a contract from the associated blob IDs. That generated contract is then deployed as a create transaction.

The ContractFactory offers the following methods for the different processes:

  • deploy for deploying contacts of any size (will automatically choose the appropriate deployment process).
  • deployAsCreateTx for deploying the entire contract bytecode in a single create transaction.
  • deployAsBlobTx for deploying the contract in chunks as blobs, and then deploying the contract as a create transaction.

Note: If the contract is deployed via blob deployments, multiple transactions will be required to deploy the contract.

Deploying a Contract Guide

This guide will cover the process of deploying a contract using the deploy method, however all these methods can be used interchangeably dependent on the contract size. In the guide we use a contract factory that has been built using Typegen. This tool provided by the Fuels CLI provides a better developer experience and end to end type support for your smart contracts.

1. Setup

After writing a contract in Sway you can build the necessary deployment artifacts either by running forc build (read more on how to work with Sway) or by using the Fuels CLI and running fuels build using your chosen package manager. We recommend using the Fuels CLI as it provides a more comprehensive usage including end to end type support.

Once you have the contract artifacts, it can be passed to the ContractFactory for deployment, like so:

<<< @./snippets/deploying-contracts/deployment.ts#setup{ts:line-numbers}

2. Contract Deployment

As mentioned earlier, there are two different processes for contract deployment handled by the ContractFactory. These can be used interchangeably, however, the deploy method is recommended as it will automatically choose the appropriate deployment process based on the contract size.

This call resolves as soon as the transaction to deploy the contract is submitted and returns three items: the contractId, a waitForTransactionId function and a waitForResult function.

<<< @./snippets/deploying-contracts/deployment.ts#deploy{ts:line-numbers}

The contract instance will be returned only after calling waitForResult and waiting for it to resolve. To avoid blocking the rest of your code, you can attach this promise to a hook or listener that will use the contract only after it is fully deployed. Similarly, the transaction ID is only available once the underlying transaction has been funded. To avoid blocking the code until the ID is ready, you can use the waitForTransactionId function to await it's retrieval.

3. Executing a Contract Call

Now that the contract is deployed, you can interact with it by submitting a contract call:

<<< @./snippets/deploying-contracts/deployment.ts#call{ts:line-numbers}

Deploying a Large Contract as Blobs

In the above guide we use the recommended deploy method. If you are working with a contract that is too large to be deployed in a single transaction, then the SDK will chunk the contract for you and submit it as blobs, to then be accessed later by a create transaction. This process is handled by the ContractFactory.deployAsBlobTx method.

<<< @./snippets/deploying-contracts/deployment.ts#blobs{ts:line-numbers}

In the above example, we also pass a chunkSizeMultiplier option to the deployment method. The SDK will attempt to chunk the contract to the most optimal about, however the transaction size can fluctuate and you can also be limited by request size limits against the node. By default we set a multiplier of 0.95, meaning the chunk size will be 95% of the potential maximum size, however you can adjust this to suit your needs and ensure the transaction passes. It must be set to a value between 0 and 1.

Note: Deploying large contracts using blob transactions will take more time. Each transaction is dependent and has to wait for a block to be produced before it gets mined. Then a create transaction is submitted as normal. So you will need to wait longer than usual for the contract to be fully deployed and can be interacted with.


Apps Docs Src Guide Contracts Inter Contract Calls (`apps/docs/src/guide/contracts/inter-contract-calls.md`)

Inter-Contract Calls with the SDK

This guide explains how to use the SDK to execute a contract call where one contract interacts with another contract. We will use a simple scenario involving a SimpleToken contract and a TokenDepositor contract.

`SimpleToken` and `TokenDepositor` Contracts

In this example, we have a SimpleToken contract representing a basic token contract capable of holding balances for different addresses. We also have a TokenDepositor contract that deposits tokens into the SimpleToken contract.

Contract: `SimpleToken`

Here's a simple token contract that allows holding balances:

<<< @/../../docs/sway/simple-token/src/main.sw#inter-contract-calls-1{rs:line-numbers}

Contract: `TokenDepositor`

The TokenDepositor contract imports the SimpleToken contract and calls its deposit function to deposit tokens:

<<< @/../../docs/sway/token-depositor/src/main.sw#inter-contract-calls-2{rs:line-numbers}

Inter-contract calls using the SDK

Once both contracts are deployed, we can use the SDK to make the TokenDepositor contract to call the SimpleToken contract.

<<< @./snippets/inter-contract-calls.ts#full{ts:line-numbers}

Pay attention to the method addContracts called by the TokenDepositor contract. This method accepts an array of instances of deployed contracts. Without calling this method, the inter-contract call will not work.


Apps Docs Src Guide Contracts Logs (`apps/docs/src/guide/contracts/logs.md`)

Working with Contract Logs

When you log a value within a contract method, you can generate a log entry that is added to the log receipt, and the variable type is recorded in the contract's ABI. The SDK enables you to parse these values into TypeScript types.

Simple Logs

Consider the following example contract:

<<< @/../../docs/sway/log-simple/src/main.sw#full{rust:line-numbers}

To access the logged values in TypeScript, use the logs (typed as Array<any>) property from the response of a contract call.

<<< @./snippets/logs-simple.ts#logs{ts:line-numbers}

Grouped Logs

We also provide a groupedLogs property that groups the logs by their program identifier. This is particularly useful when working with inter-contract or multi-calls.

We will use the same LogSimple contract as in the previous example.

Multi-call

We can make a multi-call to the contract

<<< @./snippets/logs-grouped-for-single-contract.ts#single{ts:line-numbers}

Inter-contract

Consider the following example contract:

In this example, we are making a call an inter-contract call to the LogSimple contract from the previous example.

<<< @/../../docs/sway/log-inter-calls/src/main.sw#full{rust:line-numbers}

The log_inter_call function makes a call to the log_simple function of the LogSimple contract.

<<< @./snippets/logs-grouped-for-inter-contract-call.ts#inter{ts:line-numbers}


Apps Docs Src Guide Contracts Managing Deployed Contracts (`apps/docs/src/guide/contracts/managing-deployed-contracts.md`)

Managing Deployed Contracts

To interact with a deployed contract using the SDK without redeploying it, you only need the contract ID and its JSON ABI. This allows you to bypass the deployment setup.

Contract ID

The contractId property from the Contract class is an instance of the Address class.

The Address class also provides a set of utility functions for easy manipulation and conversion between address formats along with one property; b256Address, which is a string encoded in B256 format.

When you log the contractId property of an instantiated Contract using console.log, the output appears as follows:

console
Address {
    b256Address: '0xcd16d97c5c4e18ee2e8d6428447dd9c8763cb0336718b53652d049f8ec88b3ba'
  }

If you have already an instantiated and deployed contract in hands you can create another contract instance simply by using the contractId property and the contract JSON ABI:

<<< @./snippets/managing-deployed-contracts.ts#with-contractId{ts:line-numbers}

The previous example assumes that you have a Contract instance at hand. However, some Fuel tools and Sway use the B256 type format, a hex-encoded string-like type, for contract IDs.

You might have this format instead, for example, if you have deployed your contract with forc deploy.

The process of instantiating a Contract remains the same when using a contract ID of type B256:

<<< @./snippets/managing-deployed-contracts.ts#with-b256{ts:line-numbers}


Apps Docs Src Guide Contracts Methods (`apps/docs/src/guide/contracts/methods.md`)

Interacting With Contracts

There are 4 ways to interact with contracts: get, dryRun, simulate, call.

`get`

The get method should be used to read data from the blockchain without using resources. It can be used with an unfunded wallet or even without a wallet at all:

<<< @./snippets/methods/get.ts#interacting-with-contracts-1{ts:line-numbers}

`dryRun`

The dryRun method should be used to dry-run a contract call. It does not spend resources and can be used with an unfunded wallet or even without a wallet at all:

<<< @./snippets/methods/dry-run.ts#interacting-with-contracts-2{ts:line-numbers}

`simulate`

The simulate method should be used to dry-run a contract call, ensuring that the wallet used has sufficient funds to cover the transaction fees, without consuming any resources.

A funded wallet it's required:

<<< @./snippets/methods/simulate.ts#interacting-with-contracts-3{ts:line-numbers}

`call`

The call method submits a real contract call transaction to the node, resolving immediately upon submission and returning a transactionId along with a waitForResult callback to wait for transaction execution. This behavior aligns with the natural behaviour of blockchains, where transactions may take a few seconds before being recorded on the chain.

Real resources are consumed, and any operations executed by the contract function will be processed on the blockchain.

<<< @./snippets/methods/call.ts#interacting-with-contracts-4{ts:line-numbers}

`isReadOnly` (utility)

If you want to figure out whether a function is read-only, you can use the isReadOnly method:

<<< @./snippets/methods/is-read-only.ts#is-function-readonly-1{ts:line-numbers}

If the function is read-only, you can use the get method to retrieve onchain data without spending gas.

If the function is not read-only you will have to use the call method to submit a transaction onchain which incurs a gas fee.


Apps Docs Src Guide Contracts Minted Token Asset Id (`apps/docs/src/guide/contracts/minted-token-asset-id.md`)

Minted Token Asset ID

The asset ID of a token on the Fuel network is determined by two factors:

  • The ID of the contract that minted the token,
  • A sub-identifier (Sub ID)

Both of which are B256 strings.

The process involves applying a SHA-256 hash algorithm to the combination of the Contract ID and the Sub ID, to derive an Asset ID - as explained here.

Consider the following simplified token contract:

<<< @/../../docs/sway/token/src/main.sw#minted-token-asset-id-1{rs:line-numbers}

Imagine that this contract is already deployed and we are about to mint some coins:

<<< @./snippets/utilities/minted-token-asset-id.ts#minted-token-asset-id-2{ts:line-numbers}

Obtaining the Asset ID

Since the asset ID depends on the contract ID, which is always dynamic (unlike the sub ID, which can be set to a fixed value), the helper getMintedAssetId can be used to easily obtain the asset ID for a given contract ID and sub ID.

Create Asset Id

The SDK provides a helper named createAssetId which takes the contract ID and sub ID as parameters. This helper internally calls getMintedAssetId and returns the Sway native parameter AssetId, ready to be used in a Sway program invocation:

<<< @./snippets/utilities/create-asset-id.ts#create-asset-id-1{ts:line-numbers}


Apps Docs Src Guide Contracts Multi Contract Calls (`apps/docs/src/guide/contracts/multi-contract-calls.md`)

Multiple Contract Calls

You can execute multiple contract calls in a single transaction, either to the same contract or to different contracts. This can improve efficiency and reduce the overall transaction costs.

Same Contract Multi Calls

Use the multiCall method to call multiple functions on the same contract in a single transaction:

<<< @./snippets/multi-call/same-contract.ts#multicall-1{ts:line-numbers}

Different Contracts Multi Calls

The multiCall method also allows you to execute multiple contract calls to distinct contracts within a single transaction:

<<< @./snippets/multi-call/different-contracts.ts#multicall-2{ts:line-numbers}

You can also chain supported contract call methods, like callParams, for each contract call:

<<< @./snippets/multi-call/different-contracts-chain-methods.ts#multicall-3{ts:line-numbers}

When using multiCall, the contract calls are queued and executed only after invoking one of the following methods: .get, .simulate, or .call.

Using `multiCall` for Read-Only Contract Calls

When you need to read data from multiple contracts, the multiCall method can perform multiple read-only calls in a single transaction. This minimizes the number of requests sent to the network and consolidates data retrieval, making your dApp interactions more efficient.

<<< @./snippets/multi-call/different-contracts-readonly.ts#multicall-4{ts:line-numbers}


Apps Docs Src Guide Contracts Proxy Contracts (`apps/docs/src/guide/contracts/proxy-contracts.md`)

Proxy Contracts

Automatic deployment of proxy contracts can be enabled in Forc.toml.

We recommend that you use fuels deploy to deploy and upgrade your contract using a proxy as it will take care of everything for you. However, if you want to deploy a proxy contract manually, you can follow the guide below.

Manually Deploying and Upgrading by Proxy

As mentioned above, we recommend using fuels deploy to deploy and upgrade your contract because it will handle everything automatically. However, the guide below will explain this process in detail if you want to implement it yourself.

We recommend using the SRC14 compliant owned proxy contract as the underlying proxy as that is the one we will use in this guide and the one used by fuels deploy. A TypeScript implementation of this proxy is exported from the fuels package as Src14OwnedProxy and Src14OwnedProxyFactory.

The overall process is as follows:

  1. Deploy your contract
  2. Deploy the proxy contract
  3. Set the target of the proxy contract to your deployed contract
  4. Make calls to the contract via the proxy contract ID
  5. Upgrade the contract by deploying a new version of the contract and updating the target of the proxy contract

Note: When new storage slots are added to the contract, they must be initialized in the proxy contract before they can be read from. This can be done by first writing to the new storage slot in the proxy contract. Failure to do so will result in the transaction being reverted.

For example, lets imagine we want to deploy the following counter contract:

<<< @/../../docs/sway/counter/src/main.sw#proxy-1{rs:line-numbers}

Let's deploy and interact with it by proxy. First let's setup the environment and deploy the counter contract:

<<< @./snippets/proxy-contracts.ts#proxy-2{ts:line-numbers}

Now let's deploy the SRC14 compliant proxy contract and initialize it by setting its target to the counter target ID.

<<< @./snippets/proxy-contracts.ts#proxy-3{ts:line-numbers}

Finally, we can call our counter contract using the contract ID of the proxy.

<<< @./snippets/proxy-contracts.ts#proxy-4{ts:line-numbers}

Now let's make some changes to our initial counter contract by adding an additional storage slot to track the number of increments and a new get method that retrieves its value:

<<< @/../../docs/sway/counter-v2/src/main.sw#proxy-5{rs:line-numbers}

We can deploy it and update the target of the proxy like so:

<<< @./snippets/proxy-contracts.ts#proxy-6{ts:line-numbers}

Then, we can instantiate our upgraded contract via the same proxy contract ID:

<<< @./snippets/proxy-contracts.ts#proxy-7{ts:line-numbers}

For more info, please check these docs:


Apps Docs Src Guide Contracts Storage Slots (`apps/docs/src/guide/contracts/storage-slots.md`)

Storage Slots

When deploying a contract, you can specify the custom storage slots that you want to use.

<<< @./snippets/storage-slots/override-storage-slots.ts#contract-deployment-storage-slots{ts:line-numbers}

Using plain JavaScript

In the above example, we directly imported the storage slots from a JSON file generated by the Sway compiler.

Instead of importing from a file, you can also specify the custom storage slots directly in your code:

<<< @./snippets/storage-slots/override-storage-slots-inline.ts#contract-deployment-storage-slots-inline{ts:line-numbers}

Auto-load of Storage Slots

Code generated using Typegen automatically load Storage Slots for you.


Apps Docs Src Guide Contracts Transferring Assets (`apps/docs/src/guide/contracts/transferring-assets.md`)

Transferring assets

Consider a scenario where you're interacting with a smart contract and need to transfer assets to a recipient's wallet. The addTransfer enables you to combine these actions into a single transaction seamlessly.

The addTransfer method allows you to append an asset transfer to your contract call transaction. You can use it is shown in the following example:

<<< @./snippets/utilities/add-transfer-single-recipient.ts#add-transfer-1{ts:line-numbers}

In the previous example, we first use a contract call to the echo_u64 function. Following this, addTransfer is added to chain call to include a transfer of 100 units of the BaseAssetId in the transaction.

Batch Transfer

You can add a batch of transfers into a single transaction by using addBatchTransfer:

<<< @./snippets/utilities/add-transfer-multiple-recipients.ts#add-transfer-2{ts:line-numbers}


Apps Docs Src Guide Contracts Understanding The Fuelvm Binary File (`apps/docs/src/guide/contracts/understanding-the-fuelvm-binary-file.md`)

Understanding the FuelVM Binary File

When you compile your Sway code using the forc build command, it generates a bytecode file. This binary file contains the compiled code that the Fuel Virtual Machine (FuelVM) will interpret and execute.

For example, consider the following smart contract:

<<< @/../../docs/sway/echo-values/src/main.sw#understanding-fuel-binary-file{ts:line-numbers}

After running forc build, a binary file will be generated with the following content:

sh
$ cat out/debug/echo-values.bin
�GT]����]@`I]G�I@sH]G�I@sHr�{6�]D`J]C�%E]@`J$@Ͼ{RD�^�%

At first glance, the content appears unreadable. However, forc provides a helpful interpreter for this bytecode: the forc parse-bytecode command. This command takes the binary data and outputs the equivalent FuelVM assembly:

sh
$ forc parse-bytecode out/debug/echo-values.bin
half-word   byte   op                raw           notes
        0   0      JI(4)             90 00 00 04   jump to byte 16
        1   4      NOOP              47 00 00 00
        2   8      Undefined         00 00 00 00   data section offset lo (0)
        3   12     Undefined         00 00 00 34   data section offset hi (52)
        4   16     LW(63, 12, 1)     5d fc c0 01
        5   20     ADD(63, 63, 12)   10 ff f3 00
        6   24     LW(17, 6, 73)     5d 44 60 49
        7   28     LW(16, 63, 1)     5d 43 f0 01
        8   32     EQ(16, 17, 16)    13 41 14 00
        9   36     JNZI(16, 11)      73 40 00 0b   conditionally jump to byte 44
       10   40     RVRT(0)           36 00 00 00
       11   44     LW(16, 63, 0)     5d 43 f0 00
       12   48     RET(16)           24 40 00 00
       13   52     Undefined         00 00 00 00
       14   56     Undefined         00 00 00 01
       15   60     Undefined         00 00 00 00
       16   64     XOR(20, 27, 53)   21 51 bd 4b

When deploying your smart contract using the SDK, the binary file plays a crucial role. It is sent to the FuelVM in a transaction, allowing the FuelVM to interpret and execute your smart contract.


Apps Docs Src Guide Contracts Using Different Wallets (`apps/docs/src/guide/contracts/using-different-wallets.md`)

Making Calls with Different Wallets or Providers

This guide demonstrates how to make contract calls using different wallets and providers by passing either an Account or a Provider to the contract on instantiation.

Changing Wallets

To change the wallet associated with a contract instance, assign a new wallet to the instance's account property. This allows you to make contract calls with different wallets in a concise manner:

<<< @./snippets/utilities/using-different-wallet.ts#using-different-wallet{ts:line-numbers}

Changing Providers

Similarly, you can assign a custom provider to a contract instance by modifying its provider property. This enables you to use a provider wrapper of your choice:

ts
const newProvider = new Provider(NEW_URL);
deployedContract.provider = newProvider;

Note: When connecting a different wallet to an existing contract instance, the provider used to deploy the contract takes precedence over the newly set provider. If you have two wallets connected to separate providers (each communicating with a different fuel-core instance), the provider assigned to the deploying wallet will be used for contract calls. This behavior is only relevant when multiple providers (i.e. fuel-core instances) are present and can be ignored otherwise.


Apps Docs Src Guide Contracts Variable Outputs (`apps/docs/src/guide/contracts/variable-outputs.md`)

Variable Outputs

Sway includes robust functions for transferring assets to wallets and contracts.

When using these transfer functions within your Sway projects, it is important to be aware that each call will require an Output Variable within the Outputs of the transaction.

For instance, if a contract function calls a Sway transfer function 3 times, it will require 3 Output Variables present within the list of outputs in your transaction.

Example: Sway functions that requires `Output Variable`

<<< @/../../docs/sway/token/src/main.sw#variable-outputs-1{ts:line-numbers}

Adding Variable Outputs to the contract call

When your contract invokes any of these functions, or if it calls a function that leads to another contract invoking these functions, you need to add the appropriate number of Output Variables.

This can be done as shown in the following example:

<<< @./snippets/utilities/variable-outputs.ts#variable-outputs-2{ts:line-numbers}

In the TypeScript SDK, the Output Variables are automatically added to the transaction's list of outputs.

This process is done by a brute-force strategy, performing sequential dry runs until no errors are returned. This method identifies the number of Output Variables required to process the transaction.

However, this can significantly delay the transaction processing. Therefore, it is highly recommended to manually add the correct number of Output Variables before submitting the transaction.


Apps Docs Src Guide Cookbook Combining Utxos (`apps/docs/src/guide/cookbook/combining-utxos.md`)

Combining UTXOs

When performing a funding operation or calling getResourcesToSpend, you may encounter the INSUFFICIENT_FUNDS_OR_MAX_COINS error if the number of coins fetched per asset exceeds the maximum limit allowed by the chain.

You may also want to do this if you want to reduce the number of inputs in your transaction, which can be useful if you are trying to reduce the size of your transaction or you are receiving the MAX_INPUTS_EXCEEDED error.

Using the Account's `consolidateCoins` Method

The SDK provides a built-in method to consolidate your base asset UTXOs:

<<< @./snippets/combining-utxos.ts#combining-utxos{ts:line-numbers}

Configuration Options

The consolidateCoins method accepts the following parameters:

  • assetId: The ID of the asset to consolidate

  • mode (optional): How to submit consolidation transactions

    • 'parallel' (default): Submit all transactions simultaneously for faster processing
    • 'sequential': Submit transactions one after another, waiting for each to complete
  • outputNum (optional): Number of output UTXOs to create (default is 1)

Max Inputs and Outputs

It's also important to note that depending on the chain configuration, you may be limited on the number of inputs and/or outputs that you can have in a transaction. These amounts can be queried via the TxParameters GraphQL query.

<<< @./snippets/max-outputs.ts#max-outputs{ts:line-numbers}


Apps Docs Src Guide Cookbook Custom Transactions From Contract Calls (`apps/docs/src/guide/cookbook/custom-transactions-from-contract-calls.md`)

Custom Transactions From Contract Calls

In the previous example we demonstrated how you can instantiate a ScriptTransactionRequest to customize and build out a more complex transaction via a script. The same can be done using contracts, but this allows us to utilize functions available in the contract and access on-chain state. Allowing us to harness all of the power from an invocation scope and a transaction request.

This cookbook demonstrates how we can utilize a contract call to build out a custom transaction, allowing us to update on-chain state and transfer assets to a recipient address.

<<< @./snippets/custom-contract-calls.ts#custom-transactions-contract-calls{ts:line-numbers}


Apps Docs Src Guide Cookbook Custom Transactions (`apps/docs/src/guide/cookbook/custom-transactions.md`)

Custom Transactions

There may be scenarios where you need to build out transactions that involve multiple program types and assets; this can be done by instantiating a ScriptTransactionRequest. This class allows you to a append multiple program types and assets to a single transaction.

Consider the following script that transfers multiple assets to a contract:

<<< @/../../docs/sway/script-transfer-to-contract/src/main.sw#custom-transactions-1{rust:line-numbers}

This script can be executed by creating a ScriptTransactionRequest, appending the resource and contract inputs/outputs and then sending the transaction, as follows:

<<< @/../../docs/src/guide/scripts/snippets/script-custom-transaction.ts#custom-transactions-2{ts:line-numbers}

Full Example

For a full example, see below:

<<< @/../../docs/src/guide/scripts/snippets/script-custom-transaction.ts#full{ts:line-numbers}


Apps Docs Src Guide Cookbook Deposit And Withdraw (`apps/docs/src/guide/cookbook/deposit-and-withdraw.md`)

Deposit And Withdraw

Consider the following contract:

<<< @/../../docs/sway/liquidity-pool/src/main.sw#deposit-and-withdraw-cookbook-1{rust:line-numbers}

As the name implies, this contract represents a simplified version of a liquidity pool. The deposit() method allows you to supply an arbitrary amount of BASE_TOKEN. In response, it mints twice the amount of the liquidity asset to the caller's address. Similarly, the withdraw() method transfers half the amount of the BASE_TOKEN back to the caller's address.

Now, let's deposit some tokens into the liquidity pool contract. Since this requires forwarding assets to the contract, we need to pass the appropriate values to callParams when creating a contract call.

<<< @./snippets/deposit-and-withdraw/deposit.ts#deposit-and-withdraw-cookbook-2{ts:line-numbers}

As a final demonstration, let's use all our liquidity asset balance to withdraw from the pool and confirm we retrieved the initial amount. For this, we get our liquidity asset balance and supply it to the withdraw() function via callParams.

<<< @./snippets/deposit-and-withdraw/withdraw.ts#deposit-and-withdraw-cookbook-3{ts:line-numbers}


Apps Docs Src Guide Cookbook Generate Fake Resources (`apps/docs/src/guide/cookbook/generate-fake-resources.md`)

Generate Fake Resources

When working with an unfunded account, you can generate fake resources to perform a dry-run on your transactions. This is useful for testing purposes without the need for real funds.

Below is an example script that returns the value 1337. You can use fake resources to execute a dry-run of this script and obtain the returned value.

<<< @/../../docs/sway/return-script/src/main.sw#generate-fake-resources-1{rust:line-numbers}

To execute a dry-run, use the Provider.dryRun method. Ensure you set the utxo_validation flag to true, as this script uses fake UTXOs:

<<< @./snippets/fake-resources.ts#generate-fake-resources-2{ts:line-numbers}

By setting utxo_validation to true, you can successfully execute the dry-run and retrieve the returned value from the script without requiring actual funds.


Apps Docs Src Guide Cookbook Graphql Integration (`apps/docs/src/guide/cookbook/graphql-integration.md`)

GraphQL Integration

The Fuel Network provides a GraphQL API to query the blockchain. To get a better understanding of the underlying schema and other operations, you can visit the playground for an interactive deep dive.

Operations

For its own purposes, the SDK creates custom operations based off of the API's schema and auto-generates TypeScript client code via codegen tools.
The end result of this code generation are the operations available on the Provider, of which some are shown below:

<<< @/../../docs/src/guide/provider/snippets/provider-operations.ts#operations{ts:line-numbers}

Note that these operations primarily serve the needs of the SDK and the Provider's methods which can encapsulate calls to multiple operations, parse the responses, etc.

If your querying needs exceed what the Provider provides, we suggest you follow this same process and write your own custom query operations, e.g.:

gql
query getChain {
  latestBlock {
    transactions {
      id
    }
  }
}

Mutations and subscriptions

For mutations and subscriptions, we strongly suggest that you communicate with the node via the Provider and do not write your own custom GraphQL operations because, in its methods, the Provider does additional processing before and after sending them to the node which might require detailed knowledge of various Fuel domain-specific topics.


Apps Docs Src Guide Cookbook Optimized React Example (`apps/docs/src/guide/cookbook/optimized-react-example.md`)

Optimized React Example

This example implements the strategies outlined in Optimizing Frontend Apps and demonstrates how to improve the perceived speed of transactions in a React application.

text
/* Detailed source-code truncated for AI context efficiency. */

Apps Docs Src Guide Cookbook Resubmitting Failed Transactions (`apps/docs/src/guide/cookbook/resubmitting-failed-transactions.md`)

Resubmitting Failed Transactions

In certain scenarios, you might need to implement a solution to resubmit failed transactions to the Fuel Network. While this approach can be effective, there are important considerations to remember.

Submission and Processing

When submitting a transaction, you will first get a response.

<<< @./snippets/resubmitting-failed-transactions/submitting.ts#resubmitting-failed-transactions-1{ts:line-numbers}

If the sendTransaction method resolves without an error, we know that the transaction was successfully submitted and accepted by the network. However, this does not guarantee that the transaction has been processed; it only indicates that the transaction has been accepted and placed in a queue for processing.

To determine whether the transaction has been processed, you must call waitForResult, which will either resolve (with the processed transaction) or reject with an error.

<<< @./snippets/resubmitting-failed-transactions/submitting.ts#resubmitting-failed-transactions-2{ts:line-numbers}

In other words:

  • If sendTransaction is rejected with an error, the transaction was not accepted by the network and is not processed.
  • If waitForResult is rejected with an error, the transaction was accepted but reverted during processing.

Resources Spent When a Transaction Is Processed

If a transaction is reverted during processing, the Fuel VM will still consume the funded resources to cover the gas used up to the point of failure. After deducting the gas cost, the remaining funds will be added to a new UTXO (Unspent Transaction Output) addressed to the owner.

Attempting to resubmit the same transaction request that failed during processing will likely result in an error, as the initially spent resources no longer exist.

<<< @./snippets/resubmitting-failed-transactions/wrong-resubmission.ts#resubmitting-failed-transactions-3{ts:line-numbers}

The attempt from the above snippet will result in the error:

console
FuelError: Transaction is not inserted. UTXO does not exist: {{utxoId}}

To safely retry a transaction that failed during processing, you should reassemble the request from scratch and resubmit it.

<<< @./snippets/resubmitting-failed-transactions/right-resubmission.ts#resubmitting-failed-transactions-4{ts:line-numbers}


Apps Docs Src Guide Cookbook Splitting Utxos (`apps/docs/src/guide/cookbook/splitting-utxos.md`)

Splitting UTXOs

There may be times when you want to split one large UTXO into multiple smaller UTXOs. This can be useful if you want to send multiple concurrent transactions without having to wait for them to be processed sequentially.

Note: Depending on how many smaller UTXOs you want to create, you may need to fund the wallet with additional funds to cover the fees. As we see in the example below, we fund the sending wallet with 500 to cover the fees for the batch transfer.

<<< @./snippets/splitting-utxos.ts#splitting-utxos{ts:line-numbers}


Apps Docs Src Guide Cookbook Sway Script With Signature Validation (`apps/docs/src/guide/cookbook/sway-script-with-signature-validation.md`)

Sway Script With Signature Validation

This guide explains how to work with a Script that rely on in-code signature validation. This is particularly useful when you need to verify that a transaction was authorized by a specific account.

Example Sway Script

Here's an example of a Sway script that validates signatures:

<<< @/../../docs/sway/script-signing/src/main.sw#multiple-signers-1{rust:line-numbers}

This script:

  1. Takes 2 parameters; an account address and an witness index
  2. Recovers the entry witness from the transaction's witnesses array using the given index
  3. Validates if the signature was generated by the given account address
  4. Returns true or false based on the validation result

Understanding Signature Validation in Fuel

On Fuel, transaction signing involves using a wallet's private key to create a hash based on the transaction ID (which is the same as the transaction hash). The transaction ID is generated by hashing the transaction bytes themselves.

Important considerations:

  • Any modification to the transaction after signing will invalidate the signature (modification within the witnesses array do not invalidate the signature)
  • This is because the transaction ID changes when the transaction is modified
  • The signature is typically the last thing added to a transaction, after estimation and funding

Special Considerations for Estimation

When working with Sway programs that have in-code signature validation, the estimation process becomes more complex because:

  1. A valid signature is required during the estimation process
  2. The signature must be valid for both during the transaction estimation and later when submitting the transaction
  3. The transaction may be modified during the estimation and funding process, which will result in invalidating any previously added signature

Implementation Example

Here's how to properly implement a transaction with signature validation for this specific Sway script:

<<< @./snippets/signature-script.ts#signature-script{ts:line-numbers}


Apps Docs Src Guide Cookbook Wallet Sdk And React Hooks (`apps/docs/src/guide/cookbook/wallet-sdk-and-react-hooks.md`)

Wallet SDK and React Hooks

This guide will show you how you can use the Fuel Wallet SDK and its React Hooks to build a simple React application that lets users connect their wallet to your application and see their balance.

Setup

The first thing we will do is setup a Next.js project.

::: code-group

sh [npm]
npm create next-app my-fuel-app
sh [pnpm]
pnpm create next-app my-fuel-app
sh [bun]
bun create next-app my-fuel-app

:::

Next, we will install the Fuel Wallet React SDK and the Fuel TypeScript SDK.

::: code-group

sh [npm]
npm install fuels @fuels/connectors @fuels/react @tanstack/react-query
sh [pnpm]
pnpm add fuels @fuels/connectors @fuels/react @tanstack/react-query
sh [bun]
bun add fuels @fuels/connectors @fuels/react @tanstack/react-query

:::

The Provider

In order to make use of the React hooks provided by the Fuel Wallet SDK, we need to wrap our application in a FuelProvider component. This component will provide the hooks with the necessary context to interact with the Fuel Wallet SDK. Add the following to your pages/_app.tsx file:

<<< @/../../demo-wallet-sdk-react/src/app/layout.tsx#wallet-sdk-react-provider{tsx:line-numbers}

Building the UI

Go to your pages/index.tsx file and replace the contents with the following:

<<< @/../../demo-wallet-sdk-react/src/app/page.tsx#wallet-sdk-react-ui{tsx:line-numbers}

Let's break down what's happening here.

The useConnectors hook returns a list of available wallet connectors.

Once a connector has been selected by the user, the useConnect hook will return a connect function that can be used to connect the user's wallet to your application.

The useAccount hook returns information about the user's account, if they are connected.

The useBalance hook returns the user's ETH balance on the testnet network, if they are connected.

Further Reading


Apps Docs Src Guide Creating A Fuel Dapp Deploying A Dapp To Testnet (`apps/docs/src/guide/creating-a-fuel-dapp/deploying-a-dapp-to-testnet.md`)

Deploying a dApp to Testnet

In this guide, we will deploy a full-stack dApp bootstrapped with npm create fuels to the Fuel testnet.

Make sure you have already bootstrapped a dApp using npm create fuels. If you haven't, please follow this guide.

There are mainly two steps to get our dApp live on the testnet:

  1. Deploying the Contract to the Testnet
  2. Deploying the Frontend to the Cloud

Deploying the Contract

We will be using forc to deploy our contracts to the testnet. forc is a part of the Fuel Toolchain.

If you don't have the Fuel Toolchain installed, follow this guide to install it.

The first step is to cd into the directory containing your contract:

sh
cd sway-programs/contract

And then, run the following command and follow the instructions to deploy the contract to the testnet:

sh
forc deploy --testnet

You can check out this guide for more information on deploying a contract to the testnet.

You should see a message similar to this:

md
Contract deploy-to-testnet Deployed!

Network: https://testnet.fuel.network
Contract ID: 0x8342d413de2a678245d9ee39f020795800c7e6a4ac5ff7daae275f533dc05e08
Deployed in block 0x4ea52b6652836c499e44b7e42f7c22d1ed1f03cf90a1d94cd0113b9023dfa636

Copy the contract ID and save it for later use.

Deploying the Frontend

Let's now prepare our frontend so that we can deploy it to the cloud.

Go to your .env.local file and add a new variable named VITE_TESTNET_CONTRACT_ID. Set its value to the contract ID you had copied earlier after deploying your contract.

md
VITE_TESTNET_CONTRACT_ID=0x8342d413de2a678245d9ee39f020795800c7e6a4ac5ff7daae275f533dc05e08

If you are curious, this environment variable is used here in the src/lib.tsx file to set the contract ID:

<<< @/../../create-fuels-counter-guide/src/lib.tsx#deploying-dapp-to-testnet-frontend-contract-id{ts:line-numbers}

You will notice that this piece of code is getting the contract ID depending on the current environment. If the environment is local, it will use the contract ID from the auto-generated contract-ids.json file. Otherwise, for a testnet deployment, it will use the contract ID provided by you.

The CURRENT_ENVIRONMENT variable is defined in the lib.tsx file:

<<< @/../../create-fuels-counter-guide/src/lib.tsx#deploying-dapp-to-testnet-lib-current-environment{ts:line-numbers}

As you can see, it depends on the VITE_DAPP_ENVIRONMENT environment variable. If you go to your .env.local file, you will see that it is set to local by default. If you change this value to testnet, the frontend will now be connected to the testnet instead of your local node.

Go ahead and change the VITE_DAPP_ENVIRONMENT value to testnet in your .env.local file.
If you run your frontend now, you should be able to interact with your contract on the testnet.

To deploy your frontend to the cloud, you can use any service like Vercel. Make sure that you setup your environment variables correctly and that your contract ID is correct. Your environment variables should look something like this:

md
VITE_DAPP_ENVIRONMENT=testnet
VITE_TESTNET_CONTRACT_ID=0x8342d413de2a678245d9ee39f020795800c7e6a4ac5ff7daae275f533dc05e08

(the rest of the environment variables are optional)

Conclusion

Congratulations! You have successfully deployed your Fuel dApp to the testnet.

To recap, to deploy your dApp to the testnet, you need to:

  1. Deploy your contract to the testnet using forc deploy --testnet.
  2. Specify this contract ID in your frontend's environment variables. (VITE_TESTNET_CONTRACT_ID)
  3. Set the VITE_DAPP_ENVIRONMENT environment variable to testnet.

Apps Docs Src Guide Creating A Fuel Dapp Options (`apps/docs/src/guide/creating-a-fuel-dapp/options.md`)

Options

The npm create fuels command has several command-line options that you can use to customize your project.

::: code-group

sh-vue [pnpm]
pnpm create fuels@{{fuels}} [project-name] [options]
sh-vue [npm]
npm create fuels@{{fuels}} -- [project-name] [options]
sh-vue [bun]
bun create fuels@{{fuels}} [project-name] [options]

:::

`--template `

Specifies the template to use for your project. The available templates are: vite and nextjs. The default template is vite.

`--verbose`

Enables verbose logging. Useful when debugging issues with the tool.

`-h, --help`

Displays a help message with all available options.

`-V, --version`

Displays the version number of the npm create fuels command.


Apps Docs Src Guide Creating A Fuel Dapp Working With Predicates (`apps/docs/src/guide/creating-a-fuel-dapp/working-with-predicates.md`)

Working with Predicates

This guide builds on the Creating a Fuel dApp guide. Once you've gotten the dApp there up and running, then you can continue here via clicking the Predicate Example link. We will modify the predicate we created in the previous guide. The final result will look like this:

You can also check it live, deployed to the Testnet:

Adding a Configurable pin

The current predicate functionality we have is a simple one that checks if the user has a pin. We will modify this predicate to accept a configurable pin. This will allow the user to set their own pin.

  1. Modifying the Predicate Contract

The first step is to modify the predicate contract to accept a configurable pin. We will use the configurable keyword to create an updatable constant to store the pin. We will also modify the main function to check this constant instead of a hardcoded pin.

<<< @/../../docs/sway/configurable-pin/src/main.sw#full{rust:line-numbers}

  1. Modifying the Frontend

We will now add new button to the frontend that will update the pin in the predicate when clicked. To do this, we will modify the ./src/components/Predicate.tsx file.

We will add a function called changePin, which will use the current pin in state to update the pin in the predicate as well as transfer 1000 to the predicate.

<<< @/../../create-fuels-counter-guide/src/components/Predicate.tsx#change-pin-react-function{ts:line-numbers}

It would also be useful to change the placeholder text.

tsx
<input
  type="text"
  value={predicatePin}
  onChange={(e) => setPredicatePin(e.target.value)}
  className="w-1/2 bg-gray-800 rounded-md px-2 py-1 mr-3 truncate font-mono"
  placeholder="Enter current or new pin"
/>

Finally, we will add a button that calls the changePin function when clicked.

tsx
<Button onClick={changePin} className="w-full" disabled={isLoading}>
  Change Pin
</Button>

Congratulations! That's all. You should now be able to see the modified predicate dApp running at http://localhost:5173 with our newly added change pin functionality.

You can find the complete source code of the dApp we built here.

Next Steps

  • Now that you have a predicate dApp running and have the npm create fuels workflow powering you, you can start building more complex dApps using the Fuel Stack. A good place to start for ideas and reference code is the Sway Applications Repo.

  • If you have any questions or need help, feel free to reach out to us on the Official Fuel Forum.

  • If you want to learn more about the Fuel Stack, check out the Fuel Docs.


Apps Docs Src Guide Encoding Encode And Decode (`apps/docs/src/guide/encoding/encode-and-decode.md`)

Encode and Decode

To interact with the FuelVM, types must be encoded and decoded per the argument encoding specification. The SDK provides the Interface class to encode and decode data.

The relevant methods of Interface are:

  • encodeType
  • decodeType

The Interface class requires you to pass the ABI on initialization. Both methods accept a concreteTypeId, which must exist in the ABI's concreteTypes array. After that, a suitable coder will be assigned to encode/decode that type.

Imagine we are working with the following script that returns the sum of two u32 integers:

<<< @/../../docs/sway/script-sum/src/main.sw#encode-and-decode-1{rust:line-numbers}

When you build this script, using:

sh
forc build

It will produce the following ABI:

<<< @./snippets/encode-and-decode.jsonc#encode-and-decode-2{json:line-numbers}

Now, let's prepare some data to pass to the main function to retrieve the combined integer. The function expects and returns a u32 integer. So here, we will encode the u32 to pass it to the function and receive the same u32 back, as bytes, that we'll use for decoding. We can do both of these with the Interface.

First, let's prepare the transaction:

<<< @./snippets/encode-and-decode.ts#encode-and-decode-3{ts:line-numbers}

Now, we can encode the script data to use in the transaction:

<<< @./snippets/encode-and-decode.ts#encode-and-decode-4{ts:line-numbers}

Finally, we can decode the result:

<<< @./snippets/encode-and-decode.ts#encode-and-decode-5{ts:line-numbers}

A similar approach can be taken with Predicates; however, you must set the encoded values to the predicateData property.

Contracts require more care. Although you can utilize the scriptData property, the arguments must be encoded as part of the contract call script. Therefore, it is recommended to use a FunctionInvocationScope when working with contracts which will be instantiated for you when submitting a contract function, and therefore handles all the encoding.

Full Example

Here is the full example of the encoding and decoding methods:

<<< @./snippets/encode-and-decode.ts#full{ts:line-numbers}


Apps Docs Src Guide Encoding Working With Bytes (`apps/docs/src/guide/encoding/working-with-bytes.md`)

Working with Bytes

This guide aims to give a high-level overview of how to work with bytes in the SDK and the structures we expect them to take. For a complete overview of ABI Encoding generally, within the Fuel network, we recommend you see the ABI Encoding documentation.

Core Types

We know the sizes of all core types at compile time. They are the building blocks of the more complex types and are the most common types you will encounter.

Unsigned Integer (`u8` / `u16` / `u32` / `u64` / `u128` / `u256`)

Each type will only contain the number of bits specified in the name. For example, a u8 will contain 8 bits, and a u256 will contain 256 bits and take up the exact property space with no additional padding.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-1{ts:line-numbers}

Boolean

A boolean is encoded as a single byte like a u8, its value being either 0 or 1.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-2{ts:line-numbers}

Fixed Length String

A fixed-length string's size is known at compile time due to the argument declaration of str[n] with n denoting its length. Each character in the string is encoded as a utf-8 bit.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-3{ts:line-numbers}

`B256` / `B512`

These are fixed-length byte arrays, with B256 containing 256 bits and B512 containing 512 bits. You can use them for address and signature formats.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-4{ts:line-numbers}

Automatically Encoded Types

These are the types that will contain nested types and no additional encoding is required other than the encoding of the nested types. This is relevant to arrays, tuples, and structs and enums. The only caveat here, is an enum will also contain a u64 representing the enum case value. options are encoded in the same way as enums.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-5{ts:line-numbers}

Heap types

Heap types are types with a dynamic length that we do not know at compile time. These are Vec, String, and raw_slice. These types are encoded with a u64 representing the length of the data, followed by the data itself.

<<< @./snippets/working-with-bytes.ts#working-with-bytes-6{ts:line-numbers}

Full Example

Here is the full example of the working with bytes functions:

<<< @./snippets/working-with-bytes.ts#full{ts:line-numbers}


Apps Docs Src Guide Fuels Cli Abi Typegen (`apps/docs/src/guide/fuels-cli/abi-typegen.md`)

ABI Typegen

The JSON ABI file

Whether you want to deploy or connect to a pre-existing smart contract, the JSON ABI file is what makes it possible.

It tells the SDK about the ABI methods in your Smart Contracts and Scripts

Given the following Sway smart contract:

rust:line-numbers
contract;

abi MyContract {
    fn test_function() -> bool;
}

impl MyContract for Contract {
    fn test_function() -> bool {
        true
    }
}

The JSON ABI file would look something like this:

json
$ cat out/debug/my-test-abi.json
[
  {
    "type": "function",
    "inputs": [],
    "name": "test_function",
    "outputs": [
      {
        "name": "",
        "type": "bool",
        "components": null
      }
    ]
  }
]

See also:


Apps Docs Src Guide Fuels Cli Commands (`apps/docs/src/guide/fuels-cli/commands.md`)

Commands

The fuels CLI consists of a couple of commands.

`fuels init`

console-vue
npx fuels@{{fuels}} help init
console
Options:
  --path <path>                Path to project root (default: current directory)
  -w, --workspace <path>       Relative dir path to Forc workspace
  -c, --contracts [paths...]   Relative paths to Contracts
  -s, --scripts [paths...]     Relative paths to Scripts
  -p, --predicates [paths...]  Relative paths to Predicates
  -o, --output <path>          Relative dir path for Typescript generation output
  --forc-path <path>           Path to the `forc` binary
  --fuel-core-path <path>      Path to the `fuel-core` binary
  --auto-start-fuel-core       Auto-starts a `fuel-core` node during `dev` command
  --fuel-core-port <port>      Port to use when starting a local `fuel-core` node for dev mode
  -h, --help                   Display help

Creating a sample fuel.config.ts file:

console-vue
npx fuels@{{fuels}} init --contracts ./my-contracts/* --output ./src/sway-contracts-api

Using Forc workspaces? Try this instead:

console-vue
npx fuels@{{fuels}} init --workspace ./sway-programs --output ./src/sway-programs-api

This will give you a minimal configuration:

<<< @/../../demo-fuels/fuels.config.minimal.ts#config{ts:line-numbers}

In a nutshell:

sh
.
├── sway-programs # <— forc workspace
├── src
│   └── sway-programs-api # <— output
├── fuels.config.ts
└── package.json

See more

`fuels build`

console-vue
npx fuels@{{fuels}} help build
console
Options:
  --path <path>  Path to project root (default: "/Users/anderson/Code/fuel/fuels-ts/apps/docs")
  -d, --deploy       Deploy contracts after build (auto-starts a `fuel-core` node if needed)
  -h, --help         Display help

Examples:

console-vue
npx fuels@{{fuels}} build
  1. Build all Sway programs under your workspace using forc 1
  2. Generate types for them using fuels-typegen 2
console-vue
npx fuels@{{fuels}} build --deploy

Using the --deploy flag will additionally:

  1. Auto-start a short-lived fuel-core node if needed (docs)
  2. Run deploy on that node

This is useful when working with contracts because a contract's ID is generated only on deployment.

`fuels deploy`

console-vue
npx fuels@{{fuels}} deploy

The fuels deploy command does two things:

  1. Deploy all Sway contracts under workspace.
  2. Saves their deployed IDs to:
    • ./src/sway-programs-api/contract-ids.json
json
{
  "myContract1": "0x..",
  "myContract2": "0x.."
}

Use it when instantiating your contracts:

<<< @/../../demo-fuels/src/index.test.ts#using-generated-files{ts:line-numbers}

For a complete example, see:

Proxy Contracts Deployment

Automatic deployment of proxy contracts can be enabled in Forc.toml.

For more info, please check these docs:

`fuels dev`

console-vue
npx fuels@{{fuels}} dev

The fuels dev command does three things:

  1. Auto-start a short-lived fuel-core node (docs)
  2. Runs build and deploy once at the start
  3. Watches your Forc workspace and repeats the previous step on every change

In dev mode, every time you update a contract on your Forc workspace, we re-generate type definitions and factory classes for it, following your pre-configured output directory. If it's part of another build system running in dev mode (i.e. next dev), you can expect it to re-build / auto-reload as well.

`fuels node`

console-vue
npx fuels@{{fuels}} node

Starts a short-lived fuel-core node and requires a fuels.config.ts config file.

Generate one with fuels init:

<<< @/../../demo-fuels/fuels.config.minimal.ts#config{ts:line-numbers}

`fuels typegen`

Manually generates type definitions and factory classes from ABI JSON files.

console-vue
npx fuels@{{fuels}} help typegen
console
Options:
  -i, --inputs <path|glob...>  Input paths/globals to your Abi JSON files
  -o, --output <dir>           Directory path for generated files
  -c, --contract               Generate types for Contracts [default]
  -s, --script                 Generate types for Scripts
  -p, --predicate              Generate types for Predicates
  -S, --silent                 Omit output messages

For more info, check:

`fuels versions`

Check for version incompatibilities between your Fuel Toolchain component versions, matching them against the ones supported by the Typescript SDK version that you have.

console-vue
npx fuels@{{fuels}} versions
console-vue
┌───────────┬───────────┬────────────────┬─────────────┐
│           │ Supported │ Yours / System │ System Path │
├───────────┼───────────┼────────────────┼─────────────┤
│ Forc      │ {{forc}}    │ {{forc}}         │ forc        │
├───────────┼───────────┼────────────────┼─────────────┤
│ Fuel-Core │ {{fuelCore}}    │ {{fuelCore}}         │ fuel-core   │
└───────────┴───────────┴────────────────┴─────────────┘

You have all the right versions! ⚡

Apps Docs Src Guide Fuels Cli Config File (`apps/docs/src/guide/fuels-cli/config-file.md`)

Config File

Here, you can learn more about all configuration options.

`workspace`

Relative directory path to Forc workspace.

<<< @/../../demo-fuels/fuels.config.full.ts#workspace{ts:line-numbers}

The property workspace is incompatible with contracts, predicates, and scripts.

`contracts`

List of relative directory paths to Sway contracts.

<<< @/../../demo-fuels/fuels.config.full.ts#contracts{ts:line-numbers}

The property contracts is incompatible with workspace.

`predicates`

List of relative directory paths to Sway predicates.

<<< @/../../demo-fuels/fuels.config.full.ts#predicates{ts:line-numbers}

The property predicates is incompatible with workspace.

`scripts`

List of relative directory paths to Sway scripts.

<<< @/../../demo-fuels/fuels.config.full.ts#scripts{ts:line-numbers}

The property scripts is incompatible with workspace.

`output`

Relative directory path to use when generating Typescript definitions.

<<< @/../../demo-fuels/fuels.config.full.ts#output{ts:line-numbers}

`providerUrl`

The URL to use when deploying contracts.

<<< @/../../demo-fuels/fuels.config.full.ts#providerUrl{ts:line-numbers}

When autostartFuelCore property is set to true, the providedUrl is overridden by that of the local short-lived fuel-core node started by the fuels dev command.

`privateKey`

Wallet private key, used when deploying contracts.

This property should ideally come from env — process.env.MY_PRIVATE_KEY.

<<< @/../../demo-fuels/fuels.config.full.ts#privateKey{ts:line-numbers}

When autostartFuelCore property is set to true, the privateKey is overridden with the consensusKey of the local short-lived fuel-core node started by the fuels dev command.

`snapshotDir`

Relative path to directory containing custom configurations for fuel-core, such as:

  • chainConfig.json
  • metadata.json
  • stateConfig.json

This will take effect only when autoStartFuelCore is true.

<<< @/../../demo-fuels/fuels.config.full.ts#snapshotDir{ts:line-numbers}

`autoStartFuelCore`

When set to true, it will automatically:

  1. Starts a short-lived fuel-core node as part of the fuels dev command
  2. Override property providerUrl with the URL for the recently started fuel-core node

<<< @/../../demo-fuels/fuels.config.full.ts#autoStartFuelCore{ts:line-numbers}

If set to false, you must spin up a fuel-core node by yourself and set the URL for it via providerUrl.

`fuelCorePort`

Port to use when starting a local fuel-core node.

<<< @/../../demo-fuels/fuels.config.full.ts#fuelCorePort{ts:line-numbers}

`forcBuildFlags`

Sway programs are compiled in debug mode by default.

Here you can customize all build flags, e.g. to build programs in release mode.

<<< @/../../demo-fuels/fuels.config.full.ts#forcBuildFlags{ts:line-numbers}

Check also:

`deployConfig`

You can supply a ready-to-go deploy configuration object:

<<< @/../../demo-fuels/fuels.config.full.ts#deployConfig-obj{ts:line-numbers}

Or use a function for crafting dynamic deployment flows:

  • If you need to fetch and use configs or data from a remote data source
  • If you need to use IDs from already deployed contracts — in this case, we can use the options.contracts property to get the necessary contract ID. For example:

<<< @/../../demo-fuels/fuels.config.full.ts#deployConfig-fn{ts:line-numbers}

`onBuild`

A callback function that is called after a build event has been successful.

Parameters:

  • config — The loaded config (fuels.config.ts)

<<< @/../../demo-fuels/fuels.config.full.ts#onBuild{ts:line-numbers}

`onDeploy`

A callback function that is called after a deployment event has been successful.

Parameters:

  • config — The loaded config (fuels.config.ts)
  • data — The data (an array of deployed contracts)

<<< @/../../demo-fuels/fuels.config.full.ts#onDeploy{ts:line-numbers}

`onDev`

A callback function that is called after the fuels dev command has successfully restarted.

Parameters:

  • config — The loaded config (fuels.config.ts)

<<< @/../../demo-fuels/fuels.config.full.ts#onDev{ts:line-numbers}

`onNode`

A callback function that is called after the fuels node command has successfully refreshed.

Parameters:

  • config — The loaded config (fuels.config.ts)

<<< @/../../demo-fuels/fuels.config.full.ts#onNode{ts:line-numbers}

`onFailure`

Pass a callback function to be called in case of errors.

Parameters:

  • config — The loaded config (fuels.config.ts)
  • error — Original error object

<<< @/../../demo-fuels/fuels.config.full.ts#onFailure{ts:line-numbers}

`forcPath`

Path to the forc binary.

When not supplied, will default to using the system binaries (forc).

<<< @/../../demo-fuels/fuels.config.full.ts#forcPath{ts:line-numbers}

`fuelCorePath`

Path to the fuel-core binary.

When not supplied, will default to using the system binaries (fuel-core).

<<< @/../../demo-fuels/fuels.config.full.ts#fuelCorePath{ts:line-numbers}

Loading environment variables

If you want to load environment variables from a .env file, you can use the dotenv package.

First, install it:

::: code-group

sh [pnpm]
pnpm install dotenv
sh [npm]
npm install dotenv
sh [bun]
bun install dotenv

:::

Then, you can use it in your fuels.config.ts file:

<<< @/../../create-fuels-counter-guide/fuels.config.ts#fuels-config-file-env{ts:line-numbers}


Apps Docs Src Guide Fuels Cli Generating Types (`apps/docs/src/guide/fuels-cli/generating-types.md`)

Generating Types from ABI

Installation

First we install fuels to our project:

console-vue
pnpm add fuels@{{fuels}}

Help

A first glance at the docs:

console
$ pnpm fuels typegen -h

Usage: fuels typegen [options]

Generate Typescript from Sway ABI JSON files

Options:
  -i, --inputs <path|glob...>  Input paths/globals to your ABI JSON files
  -o, --output <dir>           Directory path for generated files
  -c, --contract               Generate types for Contracts [default]
  -s, --script                 Generate types for Scripts
  -p, --predicate              Generate types for Predicates
  -S, --silent                 Omit output messages
  -h, --help                   Display help

Generating Types for Contracts

You can generate types for a Sway contract using the command below:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types

The path after the input flag -i should point to the file ending in -abi.json produced when the contract was built.

The path after the output flag -o will be the output directory for the generated types.

You can omit the --contract option here since it's the default.

Generating Types for Scripts

To generate types for a Sway script, use the --script flag:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --script

Generating Types for Predicates

To generate types for a Sway predicate, use the --predicate flag:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --predicate

See also:


Apps Docs Src Guide Fuels Cli Using Generated Types (`apps/docs/src/guide/fuels-cli/using-generated-types.md`)

Using Generated Types

After generating types via:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types

We can use these files like so:

<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-factory-connect{ts:line-numbers}

Contract

Let's use the Contract class to deploy a contract:

<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-factory-deploy{ts:line-numbers}

Autoloading of Storage Slots

Typegen tries to resolve, auto-load, and embed the Storage Slots for your Contract within the MyContract class. Still, you can override it alongside other options from DeployContractOptions, when calling the deploy method:

<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-storage-slots{ts:line-numbers}

Script

After generating types via:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --script

We can use these files like so:

<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-script{ts:line-numbers}

Predicate

After generating types via:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --predicate

We can use these files like so:

<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-predicate{ts:line-numbers}

See also:


Apps Docs Src Guide Getting Started Cdn Usage (`apps/docs/src/guide/getting-started/cdn-usage.md`)

CDN Usage (browser only)

html-vue
<script type="module">
  import {
    Wallet,
    Provider,
  } from "https://cdn.jsdelivr.net/npm/fuels@{{fuels}}/dist/browser.min.mjs";

  const main = async () => {
    const provider = new Provider(
      "https://mainnet.fuel.network/v1/graphql",
    );
    const { name } = await provider.getChain();
    console.log(name);
  };

  main();
</script>

More


Apps Docs Src Guide Getting Started Connecting To The Network (`apps/docs/src/guide/getting-started/connecting-to-the-network.md`)

Connecting to the Network

After installing the fuels package, it's easy to connect to the Network:

<<< @./snippets/connecting-to-the-network.ts#main{ts:line-numbers}

RPC URLs

These are our official RPC URLs:

Network URL
Mainnet https://mainnet.fuel.network/v1/graphql
Testnet https://testnet.fuel.network/v1/graphql
Localhost Running a local Fuel node

Resources

Access all our apps directly:

Mainnet Testnet
Faucet — https://faucet-testnet.fuel.network/
Explorer https://app.fuel.network https://app-testnet.fuel.network
Bridge https://app.fuel.network/bridge https://app-testnet.fuel.network/bridge
GraphQL https://mainnet.fuel.network/v1/playground https://testnet.fuel.network/v1/playground

Apps Docs Src Guide Getting Started Installation (`apps/docs/src/guide/getting-started/installation.md`)

Installation

You must install the Fuel Toolchain before using this library.

Then add the fuels dependency to your project:

::: code-group

sh-vue [bun]
bun add fuels@{{fuels}}
sh-vue [pnpm]
pnpm add fuels@{{fuels}}
sh-vue [npm]
npm install fuels@{{fuels}} --save

:::

Now you are ready to:


Apps Docs Src Guide Getting Started Next Steps (`apps/docs/src/guide/getting-started/next-steps.md`)

Done!

Wait no more, let's build your first Fuel dApp!

Further Resources

For a more in-depth, step-by-step guide on working with the wider Fuel ecosystem, check out the Developer Quickstart, which uses a more procedural and detailed approach:

  1. Installing all tools needed to develop with the Fuel ecosystem
  2. Writing your first Sway Project
  3. Deploying your contract
  4. Building a simple front-end dApp to interact with your deployed contract

Apps Docs Src Guide Getting Started React Example (`apps/docs/src/guide/getting-started/react-example.md`)

React Example

tsx
import { BN, Provider, Wallet } from "fuels";
import { useEffect, useState } from "react";

function App() {
  const [balance, setBalance] = useState(0);

  useEffect(() => {
    const onPageLoad = async () => {
      const provider = new Provider("https://mainnet.fuel.network/v1/graphql");

      const wallet = Wallet.fromAddress("0x...", provider);
      const { balances } = await wallet.getBalances();

      setBalance(new BN(balances[0].amount).toNumber());
    };

    onPageLoad();
  }, []);

  return <div>My Balance: {balance}</div>;
}

export default App;

See Also


Apps Docs Src Guide Getting Started Running A Local Fuel Node (`apps/docs/src/guide/getting-started/running-a-local-fuel-node.md`)

Running a local Fuel node

Remember to first install the Fuel Toolchain.

Check the online docs:

Command Documentation
Fuel Binary fuel-core docs — Running a local node
TS SDK fuels node docs — Using the fuels CLI

Utilities

Testing

You can run a Fuel node from within your .ts unit tests:

Developing

Configure your project for the fuels CLI using a fuels.config.ts file:

It makes development easier with a hot-reload experience:

More


Apps Docs Src Guide Predicates Configurable Constants (`apps/docs/src/guide/predicates/configurable-constants.md`)

Predicate With Configurable Constants

Predicates, much like contracts and scripts, also supports configurable constants. This enables Predicates to suit specific use cases and enhance their functionality.

Example: Asset Transfer Validation

Let's consider an example where a predicate is used to validate an asset transfer. In this case, the transfer will only be executed if the recipient's address is on a pre-approved whitelist.

The following snippet illustrates how this could be implemented:

<<< @/../../docs/sway/whitelisted-address-predicate/src/main.sw#full{rust:line-numbers}

In this example, you'll notice the use of a configurable constant named WHITELISTED. This constant has a default value that represents the default approved address.

Modifying The Whitelist

If there is a need to whitelist another address, the WHITELISTED constant can be easily updated. The following snippet demonstrates how to set a new value for the WHITELISTED constant and to make the predicate execute the transfer:

<<< @./snippets/configurables/configurable-set-data.ts#full{ts:line-numbers}

By ensuring that the updated WHITELISTED address matches the intended recipient's address, the predicate will validate the transfer successfully.

Default Whitelist Address

In scenarios where the default whitelisted address is already the intended recipient, there's no need to update the WHITELISTED constant. The predicate will validate the transfer based on the default value. Here's how this scenario might look:

<<< @./snippets/configurables/configurable-default.ts#full{ts:line-numbers}

This ability to configure constants within predicates provides a flexible mechanism for customizing their behavior, thereby enhancing the robustness and versatility of our asset transfer process.

It's important to note that these customizations do not directly modify the original predicate. The address of a predicate is a hash of its bytecode. Any change to the bytecode, including altering a constant value, would generate a different bytecode, and thus a different hash. This leads to the creation of a new predicate with a new address.

This doesn't mean that we're changing the behavior of the original predicate. Instead, we're creating a new predicate with a different configuration.

Therefore, while configurable constants do indeed enhance the flexibility and robustness of predicates, it is achieved by creating new predicates with different configurations, rather than altering the behavior of existing ones.


Apps Docs Src Guide Predicates Custom Transactions (`apps/docs/src/guide/predicates/custom-transactions.md`)

Custom Transactions

Utilizing predicate logic unlocks a wide range of possibilities for your dApps when creating transactions. Therefore, pairing predicates with custom transactions can help you achieve more complex use cases. This can be achieved by instantiating a custom transaction, appending the predicate resources, and submitting the transaction via a successfully validated predicate.

Custom transactions can be shaped via a ScriptTransactionRequest instance. For more information on crafting custom transactions and the methods available to them, please refer to the Transaction Request guide.

However, this guide will demonstrate how to use a predicate in a custom transaction. Consider the following predicate, where a configurable pin must be used to validate the predicate and unlock the funds:

<<< @/../../docs/sway/configurable-pin/src/main.sw#full{rust:line-numbers}

We can interact with the above and include it in a custom transaction like so:

<<< @./snippets/custom-transactions.ts#predicate-custom-transaction{ts:line-numbers}


Apps Docs Src Guide Predicates Deploying Predicates (`apps/docs/src/guide/predicates/deploying-predicates.md`)

Deploying Predicates

In order to optimize the cost of your recurring predicate executions, we recommend first deploying your predicate. This can be done using the Fuels CLI and running the deploy command.

By deploying the predicate, its bytecode is stored on chain as a blob. The SDK will then produce bytecode that can load the blob on demand to execute the original predicate. This far reduces the repeat execution cost of the predicate.

How to Deploy a Predicate

To deploy a predicate, we can use the Fuels CLI and execute the deploy command.

This will perform the following actions:

  1. Compile the predicate using your forc version
  2. Deploy the built predicate binary to the chain as a blob
  3. Generate a new, smaller predicate that loads the deployed predicate's blob
  4. Generate types for both the predicate and the loader that you can use in your application

We can then utilize the above generated types like so:

<<< @./snippets/deploying-predicates.ts#full{ts:line-numbers}


Apps Docs Src Guide Predicates Instantiating A Predicate (`apps/docs/src/guide/predicates/instantiating-a-predicate.md`)

Instantiating predicates

A predicate in Sway can be as simple as the following:

<<< @/../../docs/sway/return-true-predicate/src/main.sw#predicate-simple-1{rust:line-numbers}

In this minimal example, the main function does not accept any parameters and simply returns true.

Just like contracts in Sway, once you've created a predicate, you can compile it using forc build. For more information on working with Sway, refer to the Sway documentation.

After compiling, you will obtain the binary of the predicate and its JSON ABI (Application Binary Interface). Using these, you can instantiate a predicate in TypeScript as shown in the code snippet below:

<<< @./snippets/instantiation/simple.ts#predicate-simple-2{ts:line-numbers}

The created Predicate instance, among other things, has three important properties: the predicate bytes (byte code), the chainId, and the predicate address.

This address, generated from the byte code, corresponds to the Pay-to-Script-Hash (P2SH) address used in Bitcoin.

Predicate with multiple arguments

You can pass more than one argument to a predicate. For example, this is a predicate that evaluates to true if the two arguments are not equal:

<<< @/../../docs/sway/predicate-multi-args/src/main.sw#predicate-multi-args-1{rust:line-numbers}

You can pass the two arguments to this predicate like this:

<<< @./snippets/instantiation/multi-args.ts#predicate-multi-args-2{rust:line-numbers}

Predicate with a Struct argument

You can also pass a struct as an argument to a predicate. This is one such predicate that expects a struct as an argument:

<<< @/../../docs/sway/predicate-main-args-struct/src/main.sw#predicate-main-args-struct-1{rust:line-numbers}

You can pass a struct as an argument to this predicate like this:

<<< @./snippets/instantiation/struct-arg.ts#predicate-main-args-struct-2{ts:line-numbers}


Apps Docs Src Guide Predicates Methods (`apps/docs/src/guide/predicates/methods.md`)

Interacting With Predicates

The Predicate class extends the Account class, inheriting all its methods. Therefore, there are multiple ways to interact with predicates, but broadly speaking, we can think about three:

  • Checking Balances
  • Transactions
  • Transfers

Checking Balances

`getBalances`

This will return the balances of all assets owned by the predicate.

See also: Checking Wallet Balances

`getResourcesToSpend`

This will return the resources owned by a predicate so that they can be added to a transaction request.

This method is called under the hood when using transfer or createTransfer.

You may want to use this method when using a predicate in an existing transaction request.

<<< @./snippets/methods/get-resources-to-spend.ts#getResourcesToSpend{ts:line-numbers}

Transactions

`setData`

The setData method can be used to update the predicate data (i.e., predicate arguments) after the predicate has already been instantiated. Since the predicate data is initially set during instantiation, setData provides a way to modify it afterward if needed.

<<< @./snippets/methods/set-predicate-new-data.ts#set-predicate-new-data{ts:line-numbers}

Note: Using setData only updates the predicate data inside the predicate instance itself. It does not affect predicate data already embedded in a transaction request that includes predicate UTXOs. This is because each predicate UTXO carries its own copy of the predicate data.

<<< @./snippets/methods/no-modified-data.ts#no-modified-data{ts:line-numbers}

If you need to modify the predicate data within a transaction request, use the populateTransactionPredicateData method after setting the new data.

<<< @./snippets/methods/modified-data.ts#modified-data{ts:line-numbers}

`sendTransaction`

This is used to send a transaction to the node.

<<< @./snippets/methods/send-transaction.ts#sendTransaction{ts:line-numbers}

`simulateTransaction`

You can use the simulateTransaction method to dry-run a predicate call without consuming resources. A typical use case of a dry-run call is to validate that sufficient funds are available to cover the transaction fees.

<<< @./snippets/methods/simulate-transaction.ts#simulateTransaction{ts:line-numbers}

Transfers

`createTransfer`

The createTransfer method creates a transaction request with all the necessary transfer details. It automatically estimates the transaction costs via a dry-run call and funds the request with the required predicate resources. After this, one can submit the returned transaction request with greater certainty that it will succeed.

However, please remember that you can still modify the transfer request details and use its properties before submitting it to the node.

<<< @./snippets/methods/create-transfer.ts#createTransfer{ts:line-numbers}

`transfer`

You can send funds to another address using the transfer method.

<<< @./snippets/methods/transfer.ts#transfer{ts:line-numbers}


Apps Docs Src Guide Predicates Send And Spend Funds From Predicates (`apps/docs/src/guide/predicates/send-and-spend-funds-from-predicates.md`)

Send And Spend Funds From Predicates

Predicates can be used to validate transactions. This implies that a predicate can safeguard assets, only allowing their transfer if the predicate conditions are met.

This guide will demonstrate how to send and spend funds using a predicate.

Predicate Example

Consider the following predicate:

<<< @/../../docs/sway/simple-predicate/src/main.sw#send-and-spend-funds-from-predicates-1{rust:line-numbers}

This predicate accepts an address of type B256 and compares it with a hard-coded address of the same type. If both addresses are equal, the predicate returns true, otherwise it will return false.

Interacting with the Predicate Using SDK

Let's use the above predicate to validate our transaction.

Once you've compiled the predicate (forc build), you'll obtain two important artifacts: the JSON ABI and the predicate's binary code. These are needed to instantiate a new predicate.

This is where we also pass in the predicate's data. Note that the main function in our predicate example requires a parameter called input_address of type B256. We will pass this parameter to the Predicate constructor along with the bytecode and the JSON ABI.

<<< @./snippets/cookbook/transferring-assets.ts#send-and-spend-funds-from-predicates-2{ts:line-numbers}

Note: If you want to pass in the predicate data after instantiating the Predicate or if you want to use a different data than the one passed in the constructor, you will have to create a new Predicate instance.

With the predicate instantiated, we can transfer funds to its address. This requires us to have a wallet with sufficient funds. If you're unsure about using wallets with the SDK, we recommend checking out our wallet guide.

<<< @./snippets/cookbook/transferring-assets.ts#send-and-spend-funds-from-predicates-3{ts:line-numbers}

Now that our predicate holds funds, we can use it to validate a transaction and hence execute our transfer. We can achieve that by doing the following:

<<< @./snippets/cookbook/transferring-assets.ts#send-and-spend-funds-from-predicates-5{ts:line-numbers}

Note the method transfer has two parameters: the recipient's address and the intended transfer amount.

Once the predicate resolves with a return value true based on its predefined condition, our predicate successfully spends its funds by means of a transfer to a desired wallet.


In a similar approach, you can use the createTransfer method, which returns a ScriptTransactionRequest. Then, we can submit this transaction request by calling the sendTransaction method.

The following example, we are pre-staging a transaction and therefore we are able to know the transaction ID without actually submitting the transaction.

<<< @./snippets/cookbook/pre-stage.ts#send-and-spend-funds-from-predicates-8{ts:line-numbers}

Spending Entire Predicate Held Amount

Trying to forward the entire amount held by the predicate results in an error because no funds are left to cover the transaction fees. Attempting this will result in an error message like:

<<< @./snippets/cookbook/failure-not-enough-funds.ts#send-and-spend-funds-from-predicates-6{ts:line-numbers}

Predicate Validation Failure

What happens when a predicate fails to validate? Recall our predicate only validates if the input_address matches the hard-coded valid_address. Hence, if we set a different data from the valid_address, the predicate will fail to validate.

When a predicate fails to validate, the SDK throws an error that starts like this:

<<< @./snippets/cookbook/failure-returns-false.ts#send-and-spend-funds-from-predicates-7{ts:line-numbers}


Apps Docs Src Guide Provider Pagination (`apps/docs/src/guide/provider/pagination.md`)

Pagination

Pagination is highly efficient when dealing with large sets of data. Because of this some methods from the Provider class support GraphQL cursor pagination, allowing you to efficiently navigate through data chunks.

Pagination Arguments

The pagination arguments object is used to specify the range of data you want to retrieve. It includes the following properties:

  • after: A cursor pointing to a position after which you want to retrieve items.
  • first: The number of items to retrieve after the specified cursor. This is used in conjunction with the after argument.
  • before: A cursor pointing to a position before which you want to retrieve items.
  • last: The number of items to retrieve before the specified cursor. This is used in conjunction with the before argument.

<<< @./snippets/pagination.ts#pagination-args{ts:line-numbers}

Page Info

The pageInfo object is included in the GraphQL response for requests that support cursor pagination. It provides crucial metadata about the current page of results, allowing you to understand the pagination state and determine if there are more items to fetch before or after the current set.

  • endCursor: A cursor representing the last item in the current set of results. It should be used as the after argument in subsequent queries to fetch the next set of items.
  • hasNextPage: A boolean indicating whether there are more items available after the current set.
  • startCursor: A cursor representing the first item in the current set of results. It should be used as the before argument in subsequent queries to fetch the previous set of items.
  • hasPreviousPage: A boolean indicating whether there are more items available before the current set.

<<< @./snippets/pagination.ts#pagination-page-info{ts:line-numbers}

Using Pagination

One of the methods that supports pagination is the getCoins method. This method receives three parameters:

  • address: The owner's account address
  • assetId: The asset ID of the coins (optional)
  • paginationArgs: The pagination arguments (optional)

Basic Pagination

Here is how you can use the getCoins method with pagination:

<<< @./snippets/pagination.ts#pagination-next-page{ts:line-numbers}

You can also use the paginationArgs to navigate to the previous page of results:

<<< @./snippets/pagination.ts#pagination-previous-page{ts:line-numbers}

Valid Combinations

  • Forward Pagination:

    Use after with first to retrieve items following a cursor.

<<< @./snippets/pagination.ts#pagination-forward-pagination{ts}

  • Backward Pagination:

    Use before with last to retrieve items preceding a cursor.

<<< @./snippets/pagination.ts#pagination-backward-pagination{ts}

Default Behavior

If neither assetId nor paginationArgs are provided, the getCoins method will default to the base asset ID and return the first 100 items:

<<< @./snippets/pagination.ts#pagination-default-args{ts:line-numbers}


Apps Docs Src Guide Provider Provider Options (`apps/docs/src/guide/provider/provider-options.md`)

Provider Options

You can provide various options on Provider instantiation to modify its behavior.

`retryOptions`

Calls to a fuel node via the Provider will fail if a connection cannot be established.
Specifying retry options allows you to customize the way you want to handle that failure scenario before ultimately throwing an error.

NOTE: retrying is only done when a connection cannot be established. If the connection is established and the node throws an error, no retry will happen.

You can provide the following settings:

  • maxRetries - Amount of attempts to retry after initial attempt before failing the call.
  • backoff - Strategy used to define the intervals between attempts.
    • exponential (default): Doubles the delay with each attempt.
    • linear - Increases the delay linearly with each attempt.
    • fixed: Uses a constant delay between attempts.
  • baseDelay (default 150ms) - Base time in milliseconds for the backoff strategy.

<<< @./snippets/provider-options.ts#retryOptions{ts:line-numbers}

`requestMiddleware`

Allows you to modify the request object to add additional headers, modify the request's body, and much more.

<<< @./snippets/provider-options.ts#requestMiddleware{ts:line-numbers}

`timeout`

Specify the timeout in milliseconds after which every request will be aborted.

<<< @./snippets/provider-options.ts#timeout{ts:line-numbers}

`fetch`

Provide a custom fetch function that'll replace the default fetch call.

Note: If defined, requestMiddleware, timeout and retryOptions are applied to this custom fetch function as well.

<<< @./snippets/provider-options.ts#fetch{ts:line-numbers}

`resourceCacheTTL`

When using the SDK, it may be necessary to submit multiple transactions from the same account in a short period. In such cases, the SDK creates and funds these transactions, then submits them to the node.

However, if a second transaction is created before the first one is processed, there is a chance of using the same resources (UTXOs or Messages) for both transactions. This happens because the resources used in the first transaction are still unspent until the transaction is fully processed.

If the second transaction attempts to use the same resources that the first transaction has already spent, it will result in one of the following error:

console
Transaction is not inserted. Hash is already known

Transaction is not inserted. UTXO does not exist: {{utxoID}}

Transaction is not inserted. A higher priced tx {{txID}} is already spending this message: {{messageNonce}}

This error indicates that the resources used by the second transaction no longer exist, as the first transaction already spent them.

To prevent this issue, the SDK sets a default cache for resources to 20 seconds. This default caching mechanism ensures that resources used in a submitted transaction are not reused in subsequent transactions within the specified time. You can control the duration of this cache using the resourceCacheTTL flag. If you would like to disable caching, you can pass a value of -1 to the resourceCacheTTL parameter.

<<< @./snippets/provider-options.ts#cache-utxo{ts:line-numbers}

Note:

If you would like to submit multiple transactions without waiting for each transaction to be completed, your account must have multiple UTXOs available. If you only have one UTXO, the first transaction will spend it, and any remaining amount will be converted into a new UTXO with a different ID.

By ensuring your account has multiple UTXOs, you can effectively use the resourceCacheTTL flag to manage transactions without conflicts. For more information on UTXOs, refer to the UTXOs guide.


Apps Docs Src Guide Provider Querying The Chain (`apps/docs/src/guide/provider/querying-the-chain.md`)

Querying the Chain

Once you have set up a provider, you're ready to interact with the Fuel blockchain.

Let's look at a few examples below.

`getBaseAssetId`

The base asset is the underlying asset used to perform any transaction on a chain. This should be fetched from a provider to then be used in transactions.

<<< @./snippets/functionality/get-base-asset-id.ts#getBaseAssetId{ts:line-numbers}

`getCoins`

Returns UTXOs coins from an account address, optionally filtered by asset ID. This method supports pagination.

<<< @./snippets/functionality/get-coins-from-provider.ts#getCoins-1{ts:line-numbers}

This method is also implemented on the Account class and can be used without providing the address:

<<< @./snippets/functionality/get-coins-from-account.ts#getCoins-2{ts:line-numbers}

`getResourcesToSpend`

Returns spendable resources (coins or messages) for a transaction request. It accepts an optional third parameter, resourcesIdsToIgnore, to exclude specific UTXO IDs or coin message nonces:

<<< @./snippets/functionality/get-resources-to-spend-from-provider.ts#getResourcesToSpend-1{ts:line-numbers}

This method is also available in the Account class and can be used without providing the address:

<<< @./snippets/functionality/get-resources-to-spend-from-account.ts#getResourcesToSpend-2{ts:line-numbers}

`getBalances`

Returns the sum of all UTXOs coins and unspent message coins amounts for all assets. Unlike getCoins, it only returns the total amounts, not the individual coins:

<<< @./snippets/functionality/get-balances.ts#getBalances-1{ts:line-numbers}

This method is also available in the Account class and can be used without providing the address parameter:

<<< @./snippets/functionality/get-balances.ts#getBalances-2{ts:line-numbers}

`getBlocks`

The getBlocks method returns blocks from the blockchain matching the given paginationArgs parameter, supporting pagination. The below code snippet shows how to get the last 10 blocks.

<<< @./snippets/functionality/get-blocks.ts#getBlocks{ts:line-numbers}

`getMessageByNonce`

You can use the getMessageByNonce method to retrieve a message by its nonce.

<<< @./snippets/functionality/get-messages-by-nonce.ts#getMessageByNonce{ts:line-numbers}

`getMessages`

You can use the getMessages method to retrieve a list of messages from the blockchain.

<<< @./snippets/functionality/get-messages.ts#getMessages{ts:line-numbers}

`getMessageProof`

A message proof is a cryptographic proof that a message was included in a block. You can use the getMessageProof method to retrieve a message proof for a given transaction ID and message ID.

You can retrieve a message proof by either using it's block ID:

<<< @./snippets/functionality/get-message-proof-block-id.ts#getMessageProof-blockId{ts:line-numbers}

Or by it's block height:

<<< @./snippets/functionality/get-message-proof-block-height.ts#getMessageProof-blockHeight{ts:line-numbers}

`getTransactions`

You can use the getTransactions method to retrieve a list of transactions from the blockchain. This is limited to 30 transactions per page.

<<< @./snippets/functionality/get-transactions.ts#getTransactions{ts:line-numbers}


Apps Docs Src Guide Provider Rpc Consistency (`apps/docs/src/guide/provider/rpc-consistency.md`)

RPC Consistency

A common issue with querying distributed networks is ensuring consistency between nodes. At any moment, each node could be at a different block height; therefore, querying the state of the blockchain may yield different results from node to node.

To defend against this, the SDK appends the block height to block-sensitive requests so the node will verify that it meets the block height criteria before processing the request.

If the node has not met the block height criteria, the request will either be awaited on the node's side (if the node supports this) or retried from the SDK side. The SDK will attempt to retry the request until it reaches the maximum number of retries and then throw an error.

This functionality is enabled by default but can be disabled as so:

<<< @./snippets/rpc-consistency.ts#full{ts:line-numbers}


Apps Docs Src Guide Scripts Configurable Constants (`apps/docs/src/guide/scripts/configurable-constants.md`)

Script With Configurable

In the same way as contracts and predicates, Scripts also support configurable constants. This feature enables dynamic adjustment of certain values within your scripts.

Configurable constants are fairly straightforward to add and set in your scripts.

Let's consider the following script:

<<< @/../../docs/sway/script-sum/src/main.sw#script-with-configurable-contants-1{rust:line-numbers}

In this script, AMOUNT is a configurable constant with a default value of 10. The main function returns the sum of the inputted_amount and the configurable constant AMOUNT.

To change the value of the AMOUNT constant, we can use the setConfigurableConstants method as shown in the following example:

<<< @./snippets/script-with-configurable.ts#script-with-configurable-contants-2{ts:line-numbers}

In this example, we're setting a new value 81 for the AMOUNT constant. We then call the main function with an inputted value of 10.

The expectation is that the script will return the sum of the inputted value and the new value of AMOUNT.

This way, configurable constants in scripts allow for more flexibility and dynamic behavior during execution.

Full Example

For a full example, see below:

<<< @./snippets/script-with-configurable.ts#full{ts:line-numbers}


Apps Docs Src Guide Scripts Custom Script Call (`apps/docs/src/guide/scripts/custom-script-call.md`)

Preparing a Script Transaction

Akin to Contracts, we can configure the call parameters and transaction parameters for Scripts, as well as retrieve the entire transaction request prior to submission.

<<< @./snippets/script-with-configurable.ts#preparing-scripts{ts:line-numbers}


Apps Docs Src Guide Scripts Deploying Scripts (`apps/docs/src/guide/scripts/deploying-scripts.md`)

Deploying Scripts

In order to optimize the cost of your recurring script executions, we recommend first deploying your script. This can be done using the Fuels CLI and running the deploy command.

By deploying the script, its bytecode is stored on chain as a blob. The SDK will then produce bytecode that can load the blob on demand to execute the original script. This far reduces the repeat execution cost of the script.

How to Deploy a Script

To deploy a script, we can use the Fuels CLI and execute the deploy command.

This will perform the following actions:

  1. Compile the script using your forc version
  2. Deploy the built script binary to the chain as a blob
  3. Generate a script that loads the blob that can be used to execute the script
  4. Generate types for both the script and the loader that you can use in your application

We can then utilize the above generated types like so:

<<< @./snippets/deploying-scripts.ts#deploying-scripts{ts:line-numbers}


Apps Docs Src Guide Scripts Instantiating A Script (`apps/docs/src/guide/scripts/instantiating-a-script.md`)

Instantiating a script

Similar to contracts and predicates, once you've written a script in Sway and compiled it with forc build (read here for more on how to work with Sway), you'll get the script binary. Using the binary, you can instantiate a script as shown in the code snippet below:

<<< @./snippets/initialising-scripts.ts#script-init{ts:line-numbers}

In the next section, we show how to run a script.


Apps Docs Src Guide Scripts Logs (`apps/docs/src/guide/scripts/logs.md`)

Working with Script Logs

When you log a value within a script, you can generates a log entry that is added to the log receipt, and the variable type is recorded in the script's ABI. The SDK enables you to parse these values into TypeScript types.

Simple

Consider the following example script:

<<< @/../../docs/sway/script-log-simple/src/main.sw#full{rust:line-numbers}

To access the logged values in TypeScript, use the logs property in the response of a script call.

<<< @./snippets/script-log-simple.ts#full{ts:line-numbers}

Grouped logs

Consider the following example script:

<<< @/../../docs/sway/script-log-with-contract/src/main.sw#full{rust:line-numbers}

With Contract

To access the fine-grained logs for each contract, use the groupedLogs property from the script call response.

<<< @./snippets/script-log-with-contract.ts#full{ts:line-numbers}

Although Scripts don't have IDs/addresses, they can still call contracts and generate logs, so we use a zeroed-out (hexadecimal) address as their key instead.


Apps Docs Src Guide Scripts Running Scripts (`apps/docs/src/guide/scripts/running-scripts.md`)

Running a script

Suppose your Sway script main function is written using the arguments passed to the main function like so:

<<< @/../../docs/sway/script-main-args/src/main.sw#script-with-main-args{rust:line-numbers}

You can still hand code out a solution wrapper using callScript utility to call your script with data. However, if you prefer to use the ABI generated from your script, you can use the ScriptFactory helper:

<<< @./snippets/script-with-main-args.ts#full{ts:line-numbers}


Apps Docs Src Guide Testing Advanced Example (`apps/docs/src/guide/testing/advanced-example.md`)

Advanced Example

A more complex example showcasing genesis block state configuration with walletsConfig and deployment of multiple contracts is shown below.

<<< @./snippets/launching-a-test-node.ts#advanced-example{ts:line-numbers}

Summary

  1. All points listed in the basic example apply here as well.
  2. Multiple wallets were generated with highly-specific coins and messages.
  3. It's possible to specify the wallet to be used for contract deployment via walletIndex.
  4. The test contract can be deployed with all the options available for real contract deployment.

Apps Docs Src Guide Testing Basic Example (`apps/docs/src/guide/testing/basic-example.md`)

Basic Example

Let's use launchTestNode with the counter contract from the Fuel dApp tutorial.

Note: you will have to change the import paths of the contract factory and bytecode to match your folder structure.

<<< @./snippets/launching-a-test-node.ts#basic-example{ts:line-numbers}

Summary

  1. The launched variable was instantiated with the using keyword.
  2. launchTestNode spun up a short-lived fuel-core node, deployed a contract to it and returned it for testing.
  3. The deployed contract is fully typesafe because of launchTestNode's type-level integration with typegen outputs.
  4. Besides the contract, you've got the provider and wallets at your disposal.

Apps Docs Src Guide Testing Custom Blocks (`apps/docs/src/guide/testing/custom-blocks.md`)

Custom Blocks

You can force-produce blocks using the produceBlocks helper to achieve an arbitrary block height. This is especially useful when you want to do some testing regarding transaction maturity.

<<< @./snippets/tweaking-the-blockchain.ts#produce-blocks{ts:line-numbers}

Blocks With Custom Timestamps

You can also produce blocks with a custom block time using the produceBlocks helper by specifying the second optional parameter.

<<< @./snippets/tweaking-the-blockchain.ts#produceBlocks-custom-timestamp{ts:line-numbers}

Full Example

For a full example, see the following file:
<<< @./snippets/tweaking-the-blockchain.ts#full{ts:line-numbers}


Apps Docs Src Guide Testing Fuel Core Options (`apps/docs/src/guide/testing/fuel-core-options.md`)

Fuel-Core Options

The launchTestNode creates a temporary snapshot directory and configurations every time it runs. The path to this directory is passed to fuel-core via the --snapshot flag.

Default Snapshot

The default snapshot used is that of the current testnet network iteration.

Click here to see what it looks like.

Custom Snapshot

If you need a different snapshot, you can specify a DEFAULT_CHAIN_SNAPSHOT_DIR environment variable which points to your snapshot directory. launchTestNode will read that config and work with it instead, integrating all the functionality with it the same way it'd do with the default config.

How and where you specify the environment variable depends on your testing tool.

<<< @./snippets/launching-a-test-node.ts#custom-chain-config{ts:line-numbers}

Fuel-Core Node Options

Besides the snapshot, you can provide arguments to the fuel-core node via the nodeOptions.args property. For a detailed list of all possible arguments run:

shell
fuel-core run --help

If you want all your tests to run with the same arguments, consider specifying the DEFAULT_FUEL_CORE_ARGS environment variable.

<<< @./snippets/launching-a-test-node.ts#custom-fuel-core-args{ts:line-numbers}


Apps Docs Src Guide Testing Launching A Test Node (`apps/docs/src/guide/testing/launching-a-test-node.md`)

Launching a Test Node

To simplify testing in isolation, we provide a utility called launchTestNode.

It allows you to spin up a short-lived fuel-core node, set up a custom provider, wallets, deploy contracts, and much more in one go.

For usage information for launchTestNode including it's inputs, outputs and options, please check the API reference.

Explicit Resource Management

We support explicit resource management, introduced in TypeScript 5.2, which automatically calls a cleanup function after a variable instantiated with the using keyword goes out of block scope:

<<< @./snippets/launching-a-test-node.ts#automatic-cleanup{ts:line-numbers}

Configuring Typescript

To use explicit resource management, you must:

  1. Set your TypeScript version to 5.2 or above
  2. Set the compilation target to es2022 or below
  3. Configure your lib setting to either include esnext or esnext.disposable
json
{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2022", "esnext.disposable"]
  }
}

Standard API

If you don't want, or can't use explicit resource management, you can use const as usual.

In this case, remember you must call .cleanup() to dispose of the node.

<<< @./snippets/launching-a-test-node.ts#manual-cleanup{ts:line-numbers}


Apps Docs Src Guide Testing Setting Up Test Wallets (`apps/docs/src/guide/testing/setting-up-test-wallets.md`)

Setting up test wallets

You'll often want to create one or more test wallets when testing your contracts. Here's how to do it.

Create a single wallet

<<< @/../../docs/src/guide/wallets/snippets/access.ts#wallets{ts:line-numbers}

Setting up multiple test wallets

You can set up multiple test wallets using the launchTestNode utility via the walletsConfigs option.

To understand the different configurations, check out the walletsConfig in the test node options guide.

<<< @./snippets/launch-test-node-wallets.ts#multiple-wallets{ts:line-numbers}


Apps Docs Src Guide Testing Test Node Options (`apps/docs/src/guide/testing/test-node-options.md`)

Test Node Options

This reference describes all the options of the launchTestNode utility:

<<< @./snippets/launching-a-test-node.ts#options{ts:line-numbers}

Check out the API reference for usage information on the Test Node Options.

`walletsConfig`

Used to set the node's genesis block state (coins and messages).

  • count: number of wallets/addresses to generate on the genesis block.
  • assets: configure how many unique assets each wallet will own with the base asset included. Can be number or TestAssetId[].
    • The TestAssetId utility simplifies testing when different assets are necessary.
  • coinsPerAsset: number of coins (UTXOs) per asset id.
  • amountPerCoin: for each coin, the amount it'll contain.
  • messages: messages to assign to the wallets.

`walletsConfig.assets`

The TestAssetId utility integrates with walletsConfig and gives you an easy way to generate multiple random asset ids via the TestAssetId.random static method.

<<< @./snippets/launching-a-test-node.ts#asset-ids{ts:line-numbers}

`walletsConfig.messages`

The TestMessage helper class is used to create messages for testing purposes. When passed via walletsConfig.messages, the recipient field of the message is overriden to be the wallet's address.

<<< @./snippets/launching-a-test-node.ts#test-messages{ts:line-numbers}

It can also be used standalone and passed into the initial state of the chain via the TestMessage.toChainMessage instance method.

<<< @./snippets/launching-a-test-node.ts#test-messages-chain{ts:line-numbers}

`contractsConfigs`

Used to deploy contracts on the node the launchTestNode utility launches. It's an array of objects with the following properties:

`nodeOptions`

Options to modify the behavior of the node.

For example, you can specify your own base asset id of the chain like below:

<<< @./snippets/launching-a-test-node.ts#custom-node-options{ts:line-numbers}

Note: The API for these options is still not fully complete and better documentation will come in the future.

`providerOptions`

Provider options passed on Provider instantiation. More on them here.


Apps Docs Src Guide Transactions Adding Parameters (`apps/docs/src/guide/transactions/adding-parameters.md`)

Adding Parameters

Transaction parameters allow you to configure various aspects of your blockchain transactions. Dependent on these parameters, it may introduce a transaction policy.

All available parameters are shown below:

<<< @./snippets/transaction-parameters.ts#transaction-parameters-7{ts:line-numbers}

Gas Limit

The maximum amount of gas you're willing to allow the transaction to consume. If the transaction requires more gas than this limit, it will fail.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-1{ts:line-numbers}

Max Fee

The maximum amount you're willing to pay for the transaction using the base asset. This allows users to set an upper limit on the transaction fee they are willing to pay, preventing unexpected high costs due to sudden network congestion or fee spikes.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-2{ts:line-numbers}

Tip

An optional amount of the base asset to incentivise the block producer to include the transaction, ensuring faster processing for those willing to pay more. The value set here will be added to the transaction maxFee.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-3{ts:line-numbers}

Maturity

The number of blocks that must pass before the transaction can be included in a block. This is useful for time-sensitive transactions, such as those involving time-locked assets.

For example, if the chain produces a new block every second, setting Maturity to 10 means the transaction will be processed after approximately 10 seconds.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-4{ts:line-numbers}

Witness Limit

The maximum byte length allowed for the transaction witnesses array. For instance, imagine a transaction that will deploy a contract. The contract bytecode will be one of the entries in the transaction witnesses. If you set this limit to 5000 and the contract bytecode length is 6000, the transaction will be rejected because the witnesses bytes length exceeds the maximum value set.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-5{ts:line-numbers}

Expiration

The block number after which the transaction can no longer be included in the blockchain. For example, if you set the expiration block for your transaction to 200, and the transaction remains in the queue waiting to be processed when block 200 is created, the transaction will be rejected.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-6{ts:line-numbers}

Variable Outputs

The number of variable outputs that should be added to the transaction request. You can read more about it on this guide

Note: Setting transaction parameters is optional. If you don't specify them, the SDK will fetch some sensible defaults from the chain.

Setting Transaction Parameters

To set the transaction parameters, you have access to the txParams method on a transaction request.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-8{ts:line-numbers}

The same method is also accessible within a function invocation scope, so it can also be used when calling contract functions.

<<< @./snippets/transaction-parameters.ts#transaction-parameters-9{ts:line-numbers}

Note: When performing an action that results in a transaction (e.g. contract deployment, contract call with .call(), asset transfer), the SDK will automatically estimate the fee based on the gas limit and the transaction's byte size. This estimation is used when building the transaction. As a side effect, your wallet must own at least one coin of the base asset, regardless of the amount.

Full Example

Here is the full example of the transaction parameters:

<<< @./snippets/transaction-parameters.ts#full{ts:line-numbers}


Apps Docs Src Guide Transactions Adding Policies (`apps/docs/src/guide/transactions/adding-policies.md`)

Adding Policies

Transaction policies are rules that can govern how a transaction is processed, introduced by the transaction parameters that you pass to a transaction request. The available policies are as follows:

Tip

Optional amount on the base asset to incentivise block producer to include transaction, ensuring faster processing for those willing to pay more. The value set here will be added to the transaction maxFee.

Witness Limit

The maximum byte length allowed for the transaction witnesses array.

Maturity

The number of blocks that must pass before the transaction can be included in a block.

Max Fee

The maximum amount you're willing to pay for the transaction using the base asset.

Expiration

Block number after which the transaction can no longer be included in the blockchain.

Setting Transaction Policies

The following snippet shows which transaction parameters correspond to which policies:

<<< @./snippets/transaction-policies/setting-policies.ts#transaction-policies-1{ts:line-numbers}

Retrieving Transaction Policies from a Transaction

Policies used for a transaction can be retrieved from a transaction using a TransactionResponse. The below snippet will show how to retrieve the policies from a transaction:

<<< @./snippets/transaction-policies/policies-from-response.ts#transaction-policies-2{ts:line-numbers}


Apps Docs Src Guide Transactions Assemble Tx Migration Guide (`apps/docs/src/guide/transactions/assemble-tx-migration-guide.md`)

AssembleTx Migrating Guide

The old methods of estimating and funding transaction were deprecated in favor of a more robust provider.assembleTx. This guide will help you migrate your code to use the new method.

Migrating From `getTransactionCost` and `fund`

Old Approach (Deprecated)

<<< @./snippets/assemble-tx/get-cost-and-fund-1.ts#get-cost-and-fund-1{ts:line-numbers}

New Approach

<<< @./snippets/assemble-tx/assemble-tx-3.ts#assemble-tx-3{ts:line-numbers}

More Complex Transactions

Consider the following Sway script

<<< @/../../docs/sway/script-transfer-to-contract/src/main.sw#custom-transactions-1{rust:line-numbers}

This script transfers two asset amounts to the same contract address. To ensure the transaction succeeds, it must be properly funded with the required amounts. This means we need to explicitly define how the transaction should be funded.

Old Approach (Deprecated)

<<< @./snippets/assemble-tx/get-cost-and-fund-2.ts#get-cost-and-fund-2{ts:line-numbers}

New Approach

<<< @./snippets/assemble-tx/assemble-tx-4.ts#assemble-tx-4{ts:line-numbers}

By specifying which parameters assembleTx should use, we gain control over how the script call is estimated and funded.

Migrating from `estimateAndFund`

Old Code

<<< @./snippets/assemble-tx/estimate-and-fund-2.ts#estimate-and-fund-2{ts:line-numbers}

New Code

<<< @./snippets/assemble-tx/assemble-tx-2.ts#assemble-tx-2{ts:line-numbers}

Key Differences

  1. More Explicit Control: assembleTx provides clearer control over which account pays fees and which accounts provide resources.

  2. Better Resource Management: The new method allows you to specify exactly which accounts should provide which quantities of assets.

  3. Controlling Change Output: When informing each account coin quantity you have control over determining who is going to receive a the change for that specific asset ID.

Notes

  • The methods getTransactionCost and estimateAndFund are deprecated and are going to be removed on futures updates
  • The new method provides more predictable transaction assembly

Additional Options

The new assembleTx method provides several additional options:

<<< @/../../../packages/account/src/providers/provider.ts#assemble-tx-params{ts:line-numbers}

You can read more about the assembleTx here.


Apps Docs Src Guide Transactions Assemble Tx (`apps/docs/src/guide/transactions/assemble-tx.md`)

AssembleTx

The assembleTx method is a crucial part of the Fuel TypeScript SDK that helps prepare and assemble transactions with the correct inputs, outputs, and policies. It is used by all higher-level APIs in the SDK, including account transfers, contract and blob deployments, and contract calls. This guide provides a comprehensive overview of how to use assembleTx effectively.

Overview

The assembleTx method takes a transaction request and assembles it with the necessary inputs, outputs, and policies based on the provided parameters. It handles:

  • Coin quantity for different assets
  • Fee payer account
  • Gas and fee estimation
  • Predicate estimation
  • Resource exclusion (specific resources to ignore)

Parameters

The AssembleTxParams interface includes the following parameters:

<<< @/../../../packages/account/src/providers/provider.ts#assemble-tx-params{ts:line-numbers}

Parameter Details

  • request: The transaction request to be assembled.
  • blockHorizon: The number of blocks to look ahead for gas price estimation. Defaults to 10 blocks.
  • feePayerAccount: The account that will pay for the transaction fees
  • accountCoinQuantities: An array of coin quantities needed for the transaction. This is optional if the transaction only requires funds to cover the fee. The parameters are:
    • amount: The amount of coins needed (fee value does need to be included)
    • assetId: The asset ID of the coins
    • account: The account providing the coins (optional, defaults to feePayerAccount)
    • changeOutputAccount: The account to receive change (optional, defaults to the account or feePayerAccount properties, respectively)
  • resourcesIdsToIgnore: Resources to be ignored when funding the transaction (UTXOs or messages)
  • estimatePredicates: Whether to estimate gas for predicates
  • reserveGas: Additional Amount of gas to be set for the transaction

Default Behaviors for Account Properties

The accountCoinQuantities entries have two optional properties with specific default behaviors:

  1. account property:

    • If not provided, defaults to the root feePayerAccount
    • Used to specify which account provides the resources for the transaction
  2. changeOutputAccount property:

    • If not provided, defaults to the account property
    • Used to specify which account receives the change from all spent resources from a specific assetId

Example of default behaviors:

<<< @./snippets/assemble-tx/default-behaviors.ts#assemble-tx-default-behaviors{ts:line-numbers}

Return Value

The method returns an object of the type AssembleTxResponse:

  • assembledRequest: The fully assembled transaction request with all necessary inputs, outputs, and policies
  • gasPrice: The estimated gas price for the transaction
  • receipts: Parsed receipts returned from the transaction dry run.
  • rawReceipts: Unparsed receipts returned from the transaction dry run.

Usage Example

<<< @./snippets/assemble-tx/basic-usage.ts#assemble-tx-basic-usage{ts:line-numbers}

Attention to `account` and `changeOutputAccount` Fields

As mentioned earlier, the account and changeOutputAccount fields are optional in the accountCoinQuantities entries. However, special attention must be paid to changeOutputAccount due to how change from spent resources works on Fuel.

In Fuel, only one OutputChange is allowed per assetId in a transaction. But what exactly is an OutputChange? In simple terms, it designates the recipient of the leftover funds ("change") after all UTXO resources for a specific assetId have been spent.

Understanding Change in Fuel's UTXO Model

Because Fuel uses a UTXO-based model (unlike Ethereum’s account-based model), transactions will spend all included UTXOs, even if only a small portion is actually required. For example, suppose you have a single UTXO worth 10 ETH. If you create a transaction to send just 1 Gwei, the entire 10 ETH UTXO will be consumed. The transaction will then:

  • Create a UTXO with 1 Gwei to the recipient.
  • Create another UTXO for the remaining amount (i.e., 10 ETH - 1 Gwei - fee), sent to the address defined in the OutputChange.

In this context, the OutputChange ensures that you receive the change from your transaction.

Fuel's Constraint: One Change Output per `assetId`

A key rule in Fuel is that only one OutputChange per assetId is allowed per transaction. This becomes particularly important when a transaction includes resources from multiple accounts that hold the same assetId (e.g., ETH). In such a case, only one account can receive the change, whichever one is defined on the OutputChange.

If not managed correctly, this can lead to unintended behavior, such as one account spending its funds while another receives the leftover balance.

How This Relates to `assembleTx`

The changeOutputAccount field in assembleTx explicitly specifies which account should receive the change for a particular assetId. This is critical when you're using resources from multiple accounts in the same transaction.

Here's an example:

<<< @./snippets/assemble-tx/multiple-output-change.ts#multiple-output-change{ts:line-numbers}

In the example above:

  • Resources from accountB are being explicitly requested in accountCoinQuantities.
  • accountA is listed as the feePayerAccount, meaning it will also contribute resources to cover fees.
  • changeOutputAccount is explicitly set to accountB.

As a result, accountB will receive the change, even if UTXOs from accountA are spent in the transaction.

This means that if accountA contributes a 10 ETH UTXO, the transaction will spend the full 10 ETH. The leftover amount (change) will be sent to accountB, not back to accountA, because changeOutputAccountis set to accountB.

Best Practices

  1. Always provide the correct feePayerAccount that has sufficient funds for the transaction fees
  2. Pay special attention to change outputs when dealing with multiple accounts and the same asset ID:
    • In Fuel, only one change output is allowed per asset ID
    • If a transaction includes resources from the same asset ID for multiple accounts, only one account will receive the change from all spent resources
    • Make sure to coordinate with all parties involved to determine which account should receive the change output

Notes

  • The method automatically handles base asset requirements for fees
  • It performs a dry run to validate the transaction before returning
  • The assembled transaction will include all necessary inputs and outputs based on the provided coin quantities
  • Gas and fee estimation is performed using the specified block horizon

Apps Docs Src Guide Transactions Getting The Response (`apps/docs/src/guide/transactions/getting-the-response.md`)

Transaction Response

Once a transaction has been submitted, you may want to extract information regarding the result of the transaction. The SDK offers a TransactionResponse class with helper methods to expose the following information:

  • The transaction ID
  • The status (submitted, success, squeezed out, or failure)
  • Receipts (return data, logs, mints/burns, transfers and panic/reverts)
  • Operations (contract calls, transfers, withdrawals)
  • Gas fees and usages
  • Date and time of the transaction
  • The block the transaction was included in

We can easily extract this information from a contract call:

<<< @./snippets/transaction-response/contract-call.ts#transaction-response-1{ts:line-numbers}

We can also use the result of a transaction request to extract a transaction summary:

<<< @./snippets/transaction-response/from-submitted-request.ts#transaction-response-2{ts:line-numbers}

Or we can build a transaction summary from a stored transaction ID:

<<< @./snippets/transaction-response/from-submitted-request.ts#transaction-response-3{ts:line-numbers}


Apps Docs Src Guide Transactions Modifying The Request (`apps/docs/src/guide/transactions/modifying-the-request.md`)

Transaction Request

A transaction request provides the foundations for submitting a transaction and interacting with the blockchain.

Within Fuel, we have the following transaction types:

  • Script
  • Create
  • Mint

The SDK provides class helpers for handling script and create transactions: ScriptTransactionRequest and CreateTransactionRequest, respectively.

Note: Mint transactions can only be created by the block producer and do not have any use outside of block creation. Therefore, the SDK only provides the ability to decode them.

Creating a Transaction Request

To create a transaction request, you must first instantiate either a ScriptTransactionRequest or CreateTransactionRequest.

A ScriptTransactionRequest is used for script transactions, which allows you to execute bytecode on chain to perform a task or chain of tasks. Within the SDK they can be created like so:

<<< @./snippets/transaction-request/create-request.ts#transaction-request-1{ts:line-numbers}

A CreateTransactionRequest is used for create transactions, which are transactions that create a new contract on the blockchain.

<<< @./snippets/transaction-request/create-request.ts#transaction-request-2{ts:line-numbers}

Note: We recommend you use the ContractFactory for contract deployment as this will shape the create transaction request for you. Information on this can be found in the contract deployment guide.

Modifying a Transaction Request

Once you have instantiated a transaction request, you can modify it by setting the transaction parameters and policies. This can either be done manually by directly altering the transaction request object, or through helper methods that are available on the above classes.

Adding `OutputCoin`

Including OutputCoins in the transaction request specifies the UTXOs that will be created once the transaction is processed. These UTXOs represent the amounts being transferred to specified account addresses during the transaction:

<<< @./snippets/transaction-request/add-output-coin.ts#transaction-request-3{ts:line-numbers}

Estimating and Funding the Transaction Request

Before submitting a transaction, ensure it is fully funded to meet its requirements and cover the associated fees. The assembleTx method handles this by returning a fully funded and estimated transaction, ready for submission.

<<< @./snippets/transaction-request/estimate-and-fund.ts#estimate-and-fund{ts:line-numbers}

Manually Fetching Resources

In certain scenarios, you may need to manually fetch resources. This can be achieved using the getResourcesToSpend method, which accepts an array of CoinQuantities and returns the necessary resources to meet the specified amounts:

<<< @./snippets/transaction-request/fetch-resources.ts#transaction-request-5{ts:line-numbers}

Manually Fetching Coins or Messages

If needed, you can manually include specific coins or messages in the transaction. However, this approach is generally discouraged and should only be used in scenarios where explicitly adding particular coins or messages to the transaction request is required:

<<< @./snippets/transaction-request/fetch-coins.ts#transaction-request-6{ts:line-numbers}

Adding a Contract Input and Output to a Transaction Request

Imagine that you have a Sway script that manually calls a contract:

<<< @/../../docs/sway/script-call-contract/src/main.sw#transaction-request-7{rs:line-numbers}

In those cases, you will need to add both an InputContract and OutputContract to the transaction request:

<<< @./snippets/transaction-request/input-contract.ts#transaction-request-8{ts:line-numbers}

Adding a Predicate to a Transaction Request

Predicates are used to define the conditions under which a transaction can be executed. Therefore you may want to add a predicate to a transaction request to unlock funds that are utilized by a script. This can be added like so:

<<< @./snippets/transaction-request/add-predicate.ts#transaction-request-9{ts:line-numbers}

Note: For more information on predicates, including information on configuring them, funding them and using them to unlock funds, please refer to the predicate guide.

Adding a Witness and Signing a Transaction Request

The SDK provides a way of either modifying the witnesses for a transaction request directly, or by passing accounts. This will then sign the transaction request with the account's private key. Below will detail how to add a witness to a transaction request:

<<< @./snippets/transaction-request/add-witness.ts#transaction-request-10{ts:line-numbers}

A more complex example would when signatures are validated inside the script itself, like this guide here, .

Note: Once addAccountWitnesses has been called, any additional modifications to the transaction request will invalidate the signature as the transaction ID changes. Therefore, it is recommended to add witnesses last.

Getting the Transaction ID for a Transaction Request

The transaction ID is a SHA-256 hash of the entire transaction request. This can be useful for tracking the transaction on chain. To get the transaction ID, you can use the following method:

<<< @./snippets/transaction-request/add-witness.ts#transaction-request-11{ts:line-numbers}

Note: Any changes made to a transaction request will alter the transaction ID. Therefore, you should only get the transaction ID after all modifications have been made.

Burning assets

Assets can be burnt as part of a transaction that has inputs without associated output change. The SDK validates against this behavior, so we need to explicitly enable this by sending the transaction with the enableAssetBurn option set to true.

<<< @./snippets/transaction-request/asset-burn.ts#asset-burn{ts:line-numbers}

Note: Burning assets is permanent and all assets burnt will be lost. Therefore, be mindful of the usage of this functionality.


Apps Docs Src Guide Transactions Optimizing Frontend Apps (`apps/docs/src/guide/transactions/optimizing-frontend-apps.md`)

Optimizing Frontend Apps

Your application must perform a series of operations to estimate, submit and receive the result of a transaction. However, the flow in which it performs these actions can be organized or performed optimistically, increasing it's perceived speed.

Use Case

In a frontend application, imagine we have a button that executes a contract call:

tsx
<Button onClick={handleSubmit}>Submit</Button>

The handler would be implemented as follows:

<<< @./snippets/transaction-speed/transaction-speed-init.ts#main{ts:line-numbers}

Once the user clicks the button, multiple sequential calls are made to the network, which can take a while because the transaction must be:

  1. Estimated
  2. Funded
  3. Submitted

Optimization Strategy

With a few optimizations, the flow can be organized as follows:

<<< @./snippets/transaction-speed/transaction-speed-optimized.ts#main{ts:line-numbers}

Conclusion

Finally, when users click the button, they only need to submit the transaction, which vastly improves the perceived speed of the transaction because many of the necessary requests were done upfront, under the hood.

Just remember:

  • After preparation, any changes made to the transaction request will require it to be re-estimated and re-funded before it can be signed and submitted.

See Also


Apps Docs Src Guide Transactions Pre Confirmations (`apps/docs/src/guide/transactions/pre-confirmations.md`)

Pre-Confirmations

What is a Pre-Confirmation?

A pre-confirmation is an intermediate transaction status that occurs after a transaction has been submitted and accepted by the blockchain, but before it is fully processed and included in a new block.

At this stage, the transaction is pre-executed and assigned one of two possible statuses:

  • PreconfirmationSuccessStatus: The transaction is expected to be successfully included in a future block.

  • PreconfirmationFailureStatus: The transaction will not be included in any future block.

Why are Pre-Confirmations important?

Pre-confirmations allow applications to react earlier by providing immediate feedback about a transaction's expected outcome without waiting for full block finalization.

Additionally, pre-confirmations expose processed outputs (such as OutputChange and OutputVariable) that can be immediately reused in new transactions.

Available Outputs for Pre-Confirmations

When a transaction reaches the pre-confirmation stage, certain resolvedOutputs become available:

  • OutputChange: Represents the change UTXO generated from unspent inputs, grouped by assetId (one per asset).

  • OutputVariable: Similar to OutputCoin, but only created if the transaction succeeds.

These outputs can be:

  • Extracted directly from the pre-confirmation response.
  • Used immediately to fund new transactions, without waiting for block confirmation.

This significantly improves the ability to build transaction sequences or reactive transaction flows.

This is the ResolvedOutput interface structure:

<<< @/../../../packages/account/src/providers/transaction-summary/types.ts#resolved-output-type{ts:line-numbers}

Example Workflow

Suppose you send a transaction that will send funds to another wallet.

As soon as you receive a PreconfirmationSuccessStatus, you can:

  • Use the OutputChange in a new transaction.
  • Submit the next transaction without waiting for block finalization.

This reduces wait times and accelerates transaction chaining.

Code Examples

Using Pre-Confirmations when Submitting a Transfer

The following example sends a transfer, waits for the pre-confirmation success, and then submits another transfer using the resolved outputs from the first:

<<< @./snippets/pre-confirmation/send-transaction.ts#pre-confirmation-send-transaction-1{ts:line-numbers}

Using Pre-Confirmations with a Contract Call

This example performs a contract call, waits for pre-confirmation success, and then uses the resolved output to execute another contract call:

<<< @./snippets/pre-confirmation/contract-call.ts#pre-confirmation-contract-call-1{ts:line-numbers}


Apps Docs Src Guide Types Address (`apps/docs/src/guide/types/address.md`)

Address

In Sway, the Address type serves as a type-safe wrapper around the primitive B256 type. The SDK takes a different approach and has its own abstraction for the Address type.

Address Class

The Address class also provides a set of utility functions for easy manipulation and conversion between address formats along with one property; b256Address, which is of the B256 type.

<<< @/../../../packages/address/src/address.ts#address-2{ts:line-numbers}

Creating an Address

There are several ways to create an Address instance:

From a b256 address

To create an Address from a 256-bit address, use the following code snippet:

<<< @./snippets/address/from-a-b256.ts#full{ts:line-numbers}

From a Public Key

To create an Address from a public key, use the following code snippet:

<<< @./snippets/address/from-a-public-key.ts#full{ts:line-numbers}

From an EVM Address

To create an Address from an EVM address, use the following code snippet:

<<< @./snippets/address/from-an-evm-address.ts#full{ts:line-numbers}

From an existing Address

To create an Address from an existing Address instance, use the following code snippet:

<<< @./snippets/address/from-an-existing-address.ts#full{ts:line-numbers}

Utility functions

`equals`

As you may already notice, the equals function can compare addresses instances:

<<< @./snippets/address/utilities-function-equals.ts#full{ts:line-numbers}

`toChecksum`

To convert an address to a checksum address, use the toChecksum function:

<<< @./snippets/address/utilities-function-to-checksum.ts#full{ts:line-numbers}


Apps Docs Src Guide Types Arrays (`apps/docs/src/guide/types/arrays.md`)

Arrays

In Sway, an Array is a fixed-size collection of elements of the same type, similar to a Tuple. Arrays can hold arbitrary types, including non-primitive types, with their size determined at compile time.

Using Arrays in the SDK

You can pass a TypeScript Array into your contract method seamlessly just like you would pass an Array to a TypeScript function.

The SDK handles the conversion from TypeScript to Sway in the background, allowing the expected data to be passed through the type regardless of the Array type.

An Array in Sway is simply a typed Array, as demonstrated in the following example:

<<< @./snippets/arrays.ts#arrays-1{ts:line-numbers}

In Sway, Arrays are fixed in size, so the storage size is determined at the time of program compilation, not during runtime.

Let's say you have a contract that takes an Array of type u64 with a size length of 2 as a parameter and returns it:

<<< @/../../docs/sway/echo-values/src/main.sw#arrays-2{rust:line-numbers}

To execute the contract call using the SDK, you would do something like this:

<<< @./snippets/arrays.ts#arrays-3{ts:line-numbers}

You can easily access and validate the Array returned by the contract method, as demonstrated in the previous example.

As previously mentioned, Sway Arrays have a predefined type and size, so you need to be careful when passing Arrays as parameters to contract calls.

Passing an Array with an incorrect size, whether it has more or fewer elements than the specified length, will result in an error:

<<< @./snippets/arrays.ts#arrays-4{ts:line-numbers}

Similarly, passing an Array with an incorrect type will also result in an error:

<<< @./snippets/arrays.ts#arrays-5{ts:line-numbers}

Vectors

If your Array size is unknown until runtime, consider using the Vectors type, which is more suitable for dynamic-sized collections.


Apps Docs Src Guide Types Asset Id (`apps/docs/src/guide/types/asset-id.md`)

Asset ID

An Asset ID can be represented using the AssetId type. It's definition matches the Sway standard library type being a Struct wrapper around an inner B256 value.

<<< @./snippets/asset-id/intro.ts#full{ts:line-numbers}

Using an Asset ID

You can easily use the AssetId type within your Sway programs. Consider the following contract that can compares and return an AssetId:

<<< @/../../docs/sway/echo-asset-id/src/main.sw#asset-id-2{ts:line-numbers}

The AssetId struct can be passed to the contract function as follows:

<<< @./snippets/asset-id/using-an-asset-id-1.ts#snippet-1{ts:line-numbers}

And to validate the returned value:

<<< @./snippets/asset-id/using-an-asset-id-2.ts#snippet-1{ts:line-numbers}


Apps Docs Src Guide Types B256 (`apps/docs/src/guide/types/b256.md`)

`B256`

The type B256 in Fuel represents hashes and holds a 256-bit (32-bytes) value. The TypeScript SDK represents B256 as a hexlified string value for portability and provides utilities to convert to Uint8Array when the raw bytes are required.

Generating random `B256` values

To generate a random B256 value, you can use the getRandomB256() function:

<<< @./snippets/b256/generating-random-b256.ts#full{ts:line-numbers}

Converting between `B256` and `Uint8Array`

To convert between a B256 hexlified string and a Uint8Array, you can use the arrayify and hexlify functions:

<<< @./snippets/b256/converting-between-b256-uint8.ts#full{ts:line-numbers}

Support from `Address` Class

A B256 value is also supported as part of the Address class, providing seamless integration with other components of your application. To create an Address instance from a b256 value, use the new Address() method:

<<< @./snippets/b256/support-from-address-class.ts#full{ts:line-numbers}


Apps Docs Src Guide Types B512 (`apps/docs/src/guide/types/b512.md`)

B512

In Sway, the B512 type is commonly used to handle public keys and signatures. This guide will explain how the B512 type is defined in Sway, how to visualize a B512 value using the SDK, and how to interact with a contract function that accepts a B512 parameter.

The B512 type in Sway is a wrapper around two B256 types, allowing for the representation of 64-byte values. It is defined as a struct:

<<< @/../../docs/sway/bytecode-input/src/main.sw#b512-1{rs:line-numbers}

`B512` in the SDK

In the SDK, you can visualize a B512 value by examining a wallet's public key:

<<< @./snippets/b512/b512-in-the-sdk.ts#snippet-1{ts:line-numbers}

Example: Echoing a `B512` Value in a Contract Function

Let's consider a contract function that accepts a B512 parameter and returns the same value:

<<< @/../../docs/sway/echo-values/src/main.sw#b512-3{rust:line-numbers}

To call this function and validate the returned value, follow these steps:

<<< @./snippets/b512/echoing-a-b512.ts#snippet-1{ts:line-numbers}

In this example, we generate a wallet, use its public key as the B512 input, call the echo_b512 contract function, and expect the returned value to match the original input.


Apps Docs Src Guide Types Bytes (`apps/docs/src/guide/types/bytes.md`)

Bytes

A dynamic array of byte values can be represented using the Bytes type, which represents raw bytes.

Using Bytes

The Bytes type can be integrated with your contract calls. Consider the following contract that can compare and return a Bytes:

<<< @/../../docs/sway/echo-bytes/src/main.sw#bytes-1{ts:line-numbers}

A Bytes array can be created using a native JavaScript array of numbers or Big Numbers, and sent to a Sway contract:

<<< @./snippets/bytes.ts#snippet-1{ts:line-numbers}


Apps Docs Src Guide Types Bytes32 (`apps/docs/src/guide/types/bytes32.md`)

Bytes32

In Sway and the FuelVM, bytes32 is used to represent hashes. It holds a 256-bit (32-bytes) value.

Generating Random bytes32 Values

To generate a random bytes32 value, you can use the randomBytes function from the fuels module:

<<< @./snippets/bytes32/generating-random-bytes32.ts#snippet-1{ts:line-numbers}

Converting Between Byte Arrays and Strings

You can use the hexlify function to convert a byte array to a hex string, and the arrayify function to convert a hex string back to a byte array:

<<< @./snippets/bytes32/converting-between-byte.ts#snippet-1{ts:line-numbers}

Working with b256 in Fuel

In Fuel, there is a special type called b256, which is similar to bytes32. Like bytes32, B256 is also used to represent hashes and holds a 256-bit value. You can learn more about working with B256 values in the B256 documentation.


Apps Docs Src Guide Types Enums (`apps/docs/src/guide/types/enums.md`)

Enums

Sway Enums are a little distinct from TypeScript Enums. In this document, we will explore how you can represent Sway Enums in the SDK and how to use them with Sway contract functions.

Basic Sway Enum Example

Consider the following basic Sway Enum called StateError:

<<< @/../../docs/sway/echo-enum/src/main.sw#enums-1{rust:line-numbers}

The type () indicates that there is no additional data associated with each Enum variant. Sway allows you to create Enums of Enums or associate types with Enum variants.

Using Sway Enums As Function Parameters

Let's define a Sway contract function that takes a StateError Enum variant as an argument and returns it:

<<< @/../../docs/sway/echo-enum/src/main.sw#enums-2{rust:line-numbers}

To execute the contract function and validate the response, we can use the following code:

<<< @./snippets/enums/using-sway-enums.ts#snippet-1{ts:line-numbers}

In this example, we simply pass the Enum variant as a value to execute the contract function call.

Enum of Enums Example

In this example, the Error Enum is an Enum of two other Enums: StateError and UserError.

<<< @/../../docs/sway/echo-enum/src/main.sw#enums-4{rust:line-numbers}

Using Enums of Enums with Contract Functions

Now, let's create a Sway contract function that accepts any variant of the Error Enum as a parameter and returns it immediately. This variant could be from either the StateError or UserError Enums.

<<< @/../../docs/sway/echo-enum/src/main.sw#enums-5{rust:line-numbers}

Since the Error Enum is an Enum of Enums, we need to pass the function parameter differently. The parameter will be a TypeScript object:

<<< @./snippets/enums/using-enums-of-enums-1.ts#snippet-1{ts:line-numbers}

In this case, since the variant InsufficientPermissions belongs to the UserError Enum, we create a TypeScript object using the Enum name as the object key and the variant as the object value.

We would follow the same approach if we intended to use a variant from the StateError Enum:

<<< @./snippets/enums/using-enums-of-enums-2.ts#snippet-1{ts:line-numbers}

Errors

While working with enums, you may run into the following issues:

Using an invalid enum type

Thrown when the type being passed to the enum does not match that expected by it.

<<< @./snippets/enums/using-an-invalid-enum-type.ts#snippet-1{ts:line-numbers}

Using an invalid enum value

Thrown when the parameter passed is not an expected enum value.

<<< @./snippets/enums/using-an-invalid-enum-value.ts#snippet-1{ts:line-numbers}

Using an invalid enum case key

Thrown when the passed enum case is not an expected enum case value.

<<< @./snippets/enums/using-an-invalid-enum-case.ts#snippet-1{ts:line-numbers}


Apps Docs Src Guide Types Evm Address (`apps/docs/src/guide/types/evm-address.md`)

`EvmAddress`

An Ethereum Virtual Machine (EVM) Address can be represented using the EvmAddress type. It's definition matches the Sway standard library type being a Struct wrapper around an inner B256 value.

<<< @./snippets/evm-address/intro.ts#snippet-1{ts:line-numbers}

Creating an EVM Address

An EVM Address only has 20 bytes therefore the first 12 bytes of the B256 value are set to 0. Within the SDK, an Address can be instantiated and converted to a wrapped and Sway compatible EVM Address using the toEvmAddress() function:

<<< @./snippets/evm-address/creating-an-evm.ts#snippet-1{ts:line-numbers}

Using an EVM Address

The EvmAddress type can be integrated with your contract calls. Consider the following contract that can compare and return an EVM Address:

<<< @/../../docs/sway/echo-evm-address/src/main.sw#evm-address-1{ts:line-numbers}

The EvmAddress type can be used with the SDK and passed to the contract function as follows:

<<< @./snippets/evm-address/using-an-evm-address-1.ts#snippet-1{ts:line-numbers}

And to validate the returned value:

<<< @./snippets/evm-address/using-an-evm-address-2.ts#snippet-1{ts:line-numbers}


Apps Docs Src Guide Types Native Parameters (`apps/docs/src/guide/types/native-parameters.md`)

Native Parameter Types

Below you can find examples of how to convert between common native Sway program input and output types:

`Address`

`AddressInput`

To pass an Address as an input parameter to a Sway program, you can define the input as shown below:

<<< @./snippets/native-parameters/address.ts#address-input

`AddressOutput`

For a Sway program that returns an Address type, you can convert the returned value to an Address type in fuels as shown below:

<<< @./snippets/native-parameters/address.ts#address-output

`ContractId`

`ContractIdInput`

To pass a ContractId as an input parameter to a Sway program, you can define the input as shown below:

<<< @./snippets/native-parameters/contract-id.ts#contract-id-input

`ContractIdOutput`

For a Sway program that returns a ContractId type, you can convert the returned value to a string as shown below:

<<< @./snippets/native-parameters/contract-id.ts#contract-id-output

`Identity`

`IdentityInput`

To pass an Identity as an input parameter to a Sway program, you can define the input as shown below:

For an address:

<<< @./snippets/native-parameters/identity-address.ts#identity-address-input

For a contract:

<<< @./snippets/native-parameters/identity-contract.ts#identity-contract-input

`IdentityOutput`

For a Sway program that returns an Identity type, you can convert the returned value to an Address or string as shown below:

For an address:

<<< @./snippets/native-parameters/identity-address.ts#identity-address-output

For a contract:

<<< @./snippets/native-parameters/identity-contract.ts#identity-contract-output

`AssetId`

`AssetIdInput`

To pass an AssetId as an input parameter to a Sway program, you can define the input as shown below:

<<< @./snippets/native-parameters/asset-id.ts#asset-id-input

`AssetIdOutput`

For a Sway program that returns an AssetId type, you can convert the returned value to a string as shown below:

<<< @./snippets/native-parameters/asset-id.ts#asset-id-output


Apps Docs Src Guide Types Numbers (`apps/docs/src/guide/types/numbers.md`)

Numbers

In Sway, there are multiple primitive number types:

  1. u8 (8-bit unsigned integer)
  2. u16 (16-bit unsigned integer)
  3. u32 (32-bit unsigned integer)
  4. u64 (64-bit unsigned integer)
  5. u256 (256-bit unsigned integer)

This guide explains how to create and interact with Sway numbers while using the SDK.

Creating Numbers

For `u64` and `u256`

When you pass in a u64 or a u256 to a Sway program from JavaScript, you must first convert it to a BigNum object. This is because these types can have extremely large maximum values (2^64 and 2^256 respectively), and JavaScript's Number type can only hold up to 53 bits of precision (2^53).

<<< @./snippets/numbers/for-u64-and-u256-1.ts#snippet-1{ts:line-numbers}

You can also create a BigNum from a string. This is useful when you want to pass in a number that is too large to be represented as a JavaScript number. Here's how you can do that:

<<< @./snippets/numbers/for-u64-and-u256-2.ts#snippet-1{ts:line-numbers}

For `u8`, `u16`, and `u32`

You don't need to do anything special to create these numbers. You can pass in a JavaScript number directly. See the examples below for more details.

Examples: Interacting with Numbers in Contract Methods

For `u64` and `u256`

<<< @./snippets/numbers/for-u64-and-u256-3.ts#snippet-1{ts:line-numbers}

Note: If a contract call returns a number that is too large to be represented as a JavaScript number, you can convert it to a string using the .toString() method instead of .toNumber().

For `u8`, `u16`, and `u32`

<<< @./snippets/numbers/for-u8-u16-and-u32-1.ts#snippet-1{ts:line-numbers}

Using a `BigNum` from `ethers` with `fuels`

<<< @./snippets/numbers/for-u8-u16-and-u32-2.ts#snippet-1{ts:line-numbers}


Apps Docs Src Guide Types Options (`apps/docs/src/guide/types/options.md`)

Options

Sway provides the Option (optional) container for handling variables that can have a value or be marked as no-value. This concept is useful when dealing with situations where a variable may or may not have a defined value.

In this guide, we'll explain how to work with Option types in Sway and demonstrate their usage through a practical example.

Overview of `Option` Type

The Option type in Sway is a special wrapper type of Enum. In TypeScript, you can represent the Option type by using the undefined keyword, as shown in the following example

<<< @./snippets/options/overview-of-option.ts#snippet-1{ts:line-numbers}

In this example, the variable input1 can be either a number or undefined.

Example: `Option` Parameters

Let's say we have a contract function that accepts two Option parameters. Both of these parameters can have a value or be undefined. The function checks whether each input has a value; if not, it assigns a value of 0. Finally, the function returns the sum of the two inputs.

Here's the contract function written in Sway:

<<< @/../../docs/sway/sum-option-u8/src/main.sw#options-2{rust:line-numbers}

You can interact with the contract function using the SDK as follows:

<<< @./snippets/options/overview-of-option.ts#snippet-2{ts:line-numbers}

In this case, the result of the contract function call is the sum of both input parameters. If we pass only one parameter, the contract function will default the other parameter's value to 0.

<<< @./snippets/options/example-option-u8.ts#snippet-1{ts:line-numbers}

Using Option types in Sway allows you to elegantly handle situations where a variable may or may not have a defined value.


Apps Docs Src Guide Types Raw Slice (`apps/docs/src/guide/types/raw-slice.md`)

`RawSlice`

A dynamic array of values can be represented using the RawSlice type. A raw slice can be a value reference or a raw pointer.

Using a `RawSlice`

The RawSlice type can be integrated with your contract calls. Consider the following contract that can compare and return a RawSlice:

<<< @/../../docs/sway/echo-raw-slice/src/main.sw#raw-slice-1{ts:line-numbers}

A RawSlice can be created using a native JavaScript array of numbers or Big Numbers, and sent to a Sway contract:

<<< @./snippets/raw-slice.ts#raw-slice-2{ts:line-numbers}


Apps Docs Src Guide Types Std String (`apps/docs/src/guide/types/std-string.md`)

`StdString`

A dynamic string of variable length can be represented using the StdString type, also known as a Standard Lib String or std-lib-string. It behaves much like a dynamic string in most languages, and is essentially an array of characters.

Using a `StdString`

The StdString type can be integrated with your contract calls. Consider the following contract that can compare and return a String:

<<< @/../../docs/sway/echo-std-string/src/main.sw#std-string-1{ts:line-numbers}

A string can be created using a native JavaScript string, and sent to a Sway contract:

<<< @./snippets/std-string.ts#std-string-2{ts:line-numbers}


Apps Docs Src Guide Types String (`apps/docs/src/guide/types/string.md`)

String

In Sway, strings are statically-sized, which means you must define the size of the string beforehand. Statically-sized strings are represented using the str[x] syntax, where x indicates the string's size.
This guide explains how to create and interact with statically-sized strings while using the SDK.

Creating Statically-Sized Strings

<<< @./snippets/string.ts#string-1{ts:line-numbers}

Interacting with Statically-Sized Strings in Contract Methods

When a contract method accepts and returns a str[8], the corresponding SDK wrapper method will also take and return a string of the same length. You can pass a string to the contract method like this:

<<< @./snippets/string.ts#string-2{ts:line-numbers}

When working with statically-sized strings, ensure that the input and output strings have the correct length to avoid erroneous behavior.

If you pass a string that is either too long or too short for a contract method, the call will fail like this:

<<< @./snippets/string.ts#string-3{ts:line-numbers}


Apps Docs Src Guide Types Structs (`apps/docs/src/guide/types/structs.md`)

Structs

In Sway, a struct serves a similar purpose as an Object in TypeScript. It defines a custom data structure with specified property names and types. The property names and types in the Sway struct must match the corresponding TypeScript definition.

Example

Here is an example of a struct in Sway:

<<< @/../../docs/sway/employee-data/src/lib.sw#struct-1{rust:line-numbers}

And here is the equivalent structure represented in TypeScript:

<<< @./snippets/structs.ts#struct-2{ts:line-numbers}

Handling Different Data Types

Please note that TypeScript does not have native support for u8 and u64 types. Instead, use the number type to represent them.

Additionally, TypeScript does not support specifying string length, so just use string for the name.

In a similar way, since the type B256 on the SDK is just an hexlified string, we use string as well.


Apps Docs Src Guide Types Tuples (`apps/docs/src/guide/types/tuples.md`)

Tuples

In Sway, Tuples are fixed-length collections of heterogeneous elements. Tuples can store multiple data types, including basic types, structs, and enums. This guide will demonstrate how to represent and work with Tuples in TypeScript and interact with a contract function that accepts a tuple as a parameter.

In TypeScript, you can represent Sway tuples using arrays with specified types for each element:

<<< @./snippets/tuples.ts#tuples-1{ts:line-numbers}

In this example, the Typescript tuple variable contains three elements of different types: a number, a boolean, and another number.

Example: Passing Tuple as a Parameter

Let's consider a contract function that accepts a tuple as a parameter and returns the same Tuple:

<<< @/../../docs/sway/echo-values/src/main.sw#tuples-2{rust:line-numbers}

To execute and validate the contract function using the SDK, follow these steps:

<<< @./snippets/tuples.ts#tuples-3{ts:line-numbers}

In this example, we create a Tuple with three elements, call the echo_tuple contract function, and expect the returned tuple to match the original one. Note that we convert the third element of the returned tuple to a number using new BN(value[2]).toNumber().

Tuples in Sway provide a convenient way to store and manipulate collections of heterogeneous elements. Understanding how to represent and work with tuples in TypeScript and Sway contracts will enable you to create more versatile and expressive code.


Apps Docs Src Guide Types Vectors (`apps/docs/src/guide/types/vectors.md`)

Vectors

In Sway, a Vector is a dynamic-sized collection of elements of the same type. Vectors can hold arbitrary types, including non-primitive types.

Working with Vectors in the SDK

A basic Vector in Sway is similar to a TypeScript Array:

<<< @./snippets/vectors.ts#vector-1{ts:line-numbers}

Consider the following example of a EmployeeData struct in Sway:

<<< @/../../docs/sway/employee-data/src/lib.sw#struct-1{rust:line-numbers}

Now, let's look at the following contract method. It receives a Vector of the Transaction struct type as a parameter and returns the last Transaction entry from the Vector:

<<< @/../../docs/sway/echo-employee-data-vector/src/main.sw#vector-3{ts:line-numbers}

The code snippet below demonstrates how to call this Sway contract method, which accepts a Vec:

<<< @./snippets/vectors.ts#vector-4{ts:line-numbers}

Converting Bytecode to Vectors

Some functions require you to pass in bytecode to the function. The type of the bytecode parameter is usually Vec, here's an example of how to pass bytecode to a function:

<<< @/../../docs/sway/bytecode-input/src/main.sw#vector-bytecode-input-sway{ts:line-numbers}

To pass bytecode to this function, you can make use of the arrayify function to convert the bytecode file contents into a UInt8Array, the TS compatible type for Sway's Vec type and pass it the function like so:

<<< @./snippets/vectors.ts#vector-bytecode-input-ts{ts:line-numbers}


Apps Docs Src Guide Utilities Address Conversion (`apps/docs/src/guide/utilities/address-conversion.md`)

Address

Addresses and varying address formats are commonplace when interacting with decentralized applications. Furthermore, different networks may enforce different address formats.

The Fuel Network uses the B256 address format for its interactions, an example of which can be seen below:

<<< @/../../docs/src/guide/types/snippets/b256.ts#addresses-1{ts:line-numbers}

However, a hexlified B256 (hex) is another common address format; an example can be seen below:

<<< @/../../docs/src/guide/types/snippets/evm-address/creating-an-evm.ts#snippet-2{ts:line-numbers}
apps/

At times, these can even be wrapped in a Struct. Such as an Asset ID or a EVM Address:

<<< @/../../docs/src/guide/types/snippets//evm-address/using-an-evm-address-1.ts#snippet-2{ts:line-numbers}

The TS-SDK makes converting between these addresses simple using the Address helper, which provides various utilities for conversion.

The following conversion guide will show how to utilize this class to convert between address formats, as well as Sway Standard Types.

Address Conversion

This guide demonstrates how to convert between address formats and Sway Standard Types using helper functions. Native types are wrappers for bytes, and you can perform conversions between them by leveraging these functions and classes.

Converting a Contract ID

The Contract id property is an instance of the Address class. Therefore, it can be converted using the Address class functions such as toAddress and toB256:

<<< @./snippets/address-conversion/contract.ts#conversion-2{ts:line-numbers}

Converting a Wallet Address

Similarly, the Wallet address property is also of type Address and can therefore use the same Address class functions for conversion:

<<< @./snippets/address-conversion/wallet.ts#conversion-3{ts:line-numbers}

Converting an Asset ID

Asset IDs are a wrapped B256 value. The following example shows how to create an Address from a B256 type:

<<< @./snippets/address-conversion/asset-id.ts#conversion-4{ts:line-numbers}


Apps Docs Src Guide Utilities Asset Api (`apps/docs/src/guide/utilities/asset-api.md`)

Asset API

The Asset API is a RESTful API that allows you to query the assets on the Fuel blockchain. We allow for querying the Asset API on both the Mainnet and Testnet.

Endpoint
Mainnet https://mainnet-explorer.fuel.network
Testnet https://explorer-indexer-testnet.fuel.network

For more information about the API, please refer to the Wiki page.

Asset by ID

We can request information about an asset by its asset ID, using the getAssetById function. This will leverage the endpoint /assets/<assetId> to fetch the asset information.

<<< @./snippets/asset-api/asset-by-id.ts#full{ts:line-numbers}

By default, we will request the asset information for mainnet. If you want to request the asset information from other networks, you can pass the network parameter (this is the same for the getAssetsByOwner function).

<<< @./snippets/asset-api/asset-by-id.ts#testnet{ts:line-numbers}

Assets by Owner

We can request information about an asset by its owner, using the getAssetsByOwner function. This will leverage the endpoint /accounts/<owner>/assets to fetch the asset information.

<<< @./snippets/asset-api/assets-by-owner.ts#full{ts:line-numbers}

You can change the pagination parameters to fetch more assets (up to 100 assets per request).

<<< @./snippets/asset-api/assets-by-owner.ts#pagination{ts:line-numbers}


Apps Docs Src Guide Utilities Date Conversion (`apps/docs/src/guide/utilities/date-conversion.md`)

Date conversion

To allow for easier manipulation of date and time, the SDK exports the DateTime class which is a wrapper around the built-in Date class. Below we will go over the methods of instantiation, utility functions and time formats.

Internally the transactions and other time/date assets are encoded using the TAI64 format. We return a DateTime class, to allow of easier conversion and formatting between the two formats.

Instantiating a `DateTime`

We have a host of static method for instantiation of our DateTime class.

<<< @./snippets/date-conversion/instantiation.ts#create-from-multiple-sources{ts:line-numbers}

TAI64

fromTai64 is a static method, that allows the creation of DateTime class from a TAI64 string.

toTai64 is an instance method, that allows the conversion of a DateTime class to a TAI64 string.

<<< @./snippets/date-conversion/tai64.ts#from-tai-64-and-to-tai-64{ts:line-numbers}

UNIX

fromUnixMilliseconds is a static method, that allows the creation of DateTime class from a UNIX Milliseconds number.

toUnixMilliseconds is an instance method, that allows the conversion of a DateTime class to a UNIX number in milliseconds.

<<< @./snippets/date-conversion/unix-milliseconds.ts#from-unix-milliseconds-and-to-unix-milliseconds{ts:line-numbers}

fromUnixSeconds is a static method, that allows the creation of DateTime class from a UNIX Seconds number.

toUnixSeconds is an instance method, that allows the conversion of a DateTime class to a UNIX number in seconds.

<<< @./snippets/date-conversion/unix-seconds.ts#from-unix-seconds-and-to-unix-seconds{ts:line-numbers}

Date

The DateTime class extends the functionality of the Date object, so all method are available for your usages.

<<< @./snippets/date-conversion/date-object.ts#date-object-methods{ts:line-numbers}

Formats

Here we will go over the different date/time formats that we use in the SDK. Internally the blockchain uses the TAI64 format, but we also support the UNIX format for ease of use.

UNIX Format

UNIX time is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus leap seconds. Every day is treated as if it contains exactly 86400 seconds, so leap seconds are ignored.

TAI Format

TAI stands for Temps Atomique International and is the current international real-time standard Source.

We use TAI64 is a 64-bit integer representing the number of nanoseconds since the epoch.

  • the TAI second beginning exactly (2^62 - s) seconds before the beginning of 1970 TAI, if s is between 0 inclusive and 2^62 exclusive; or

  • the TAI second beginning exactly (2^62 + s) seconds after the beginning of 1970 TAI, if s is between -2^62 inclusive and 0 exclusive.

Source


Apps Docs Src Guide Utilities Unit Conversion (`apps/docs/src/guide/utilities/unit-conversion.md`)

Unit conversion

Internally, we use Arbitrary-precision arithmetic (also known as Big Number arithmetic) to allow for the handling of large numbers and different assets.

On the Fuel network, we work with 9 decimals to represent amounts under a unit. This differs from chain to chain, so it is important to know the number of decimals used on the chain you are working with.

Note: The package @fuels/assets provides a list of assets and their decimals.

Below we will go over some common use cases for unit conversion.

Using our BN class we can instantiate these numbers.

<<< @./snippets/unit-conversion.ts#instantiation-1{ts:line-numbers}

Or using our bn utility function.

<<< @./snippets/unit-conversion.ts#instantiation-2{ts:line-numbers}

Contract calls

Generally, we will need to convert u64 and u256 numbers to a BN object when passing them to a Sway program from JavaScript. More information on this can be found here.

<<< @./snippets/unit-conversion.ts#contract-calls-1{ts:line-numbers}

Note: If a contract call returns a number that is too large to be represented as a JavaScript number, you can convert it to a string using the toString method instead of toNumber.

Parsing

Parsing string-represented numbers (from user input) has never been easier, than using the parseUnits function.

<<< @./snippets/unit-conversion.ts#parse-units-1{ts:line-numbers}

We can parse large numbers.

<<< @./snippets/unit-conversion.ts#parse-units-2{ts:line-numbers}

Or numbers formatted for human readability.

<<< @./snippets/unit-conversion.ts#parse-units-3{ts:line-numbers}

We can also parse numbers in other units of measure.

<<< @./snippets/unit-conversion.ts#parse-units-4{ts:line-numbers}

Formatting

We can format common units of measure using the format function.

In the following example, we format a BigNumber representation of one Gwei, into units for the Fuel network (with 3 decimal place precision).

<<< @./snippets/unit-conversion.ts#format-1{ts:line-numbers}

We can also format numbers in other units of measure by specifying the units variable.

<<< @./snippets/unit-conversion.ts#format-2{ts:line-numbers}

A precision variable will allow for the formatting of numbers with a specific number of decimal places.

<<< @./snippets/unit-conversion.ts#format-3{ts:line-numbers}

Format units

The formatUnits function is a lesser alternative to the format function, as it will maintain the same precision as the input value.

<<< @./snippets/unit-conversion.ts#format-units-1{ts:line-numbers}

We can also format numbers in other units of measure by specifying the units variable.

<<< @./snippets/unit-conversion.ts#format-units-2{ts:line-numbers}

See also

Full Example

For the full example of unit conversion see the snippet below:

<<< @./snippets/unit-conversion.ts#full{ts:line-numbers}


Apps Docs Src Guide Utilities Using Assets (`apps/docs/src/guide/utilities/using-assets.md`)

Assets

We export an array of Asset objects, that can be useful when creating your dApp. The Asset object has useful metadata about the different assets that are available on blockchain networks (Fuel and Ethereum).

Included assets such as:

  • Ethereum (ETH)
  • Tether (USDT)
  • USD Coin (USDC)
  • Wrapped ETH (WETH)

The helper functions getAssetFuel and getAssetEth can be used to get an asset's details relative to each network. These return a combination of the asset, and network information (the return types are AssetFuel and AssetEth respectively).

<<< @./snippets/using-assets.ts#using-assets-1{ts:line-numbers}


Apps Docs Src Guide Wallets Checking Balances (`apps/docs/src/guide/wallets/checking-balances.md`)

Checking balances

To check the balance of a specific asset, you can use getBalance method. This function aggregates the amounts of all unspent coins of the given asset in your wallet.

<<< @./snippets/checking-balances.ts#checking-balances-1{ts:line-numbers}

To retrieve the balances of all assets in your wallet, use the getBalances method, it returns an array of CoinQuantity. This is useful for getting a comprehensive view of your holdings.

<<< @./snippets/checking-balances-two.ts#checking-balances-2{ts:line-numbers}


Apps Docs Src Guide Wallets Connectors (`apps/docs/src/guide/wallets/connectors.md`)

Connectors

Fuel Wallet Connectors offer a standardized interface to integrate multiple wallets with your DApps, simplifying wallet integration and ensuring smooth user interactions.

Fuel Connectors

Fuel Connectors are a set of standardized interfaces that provide a way to interact with various wallets and services. They offer a consistent way to interact with different wallets and services, allowing developers to focus on building their applications rather than worrying about wallet integration.

To build your own wallet integration, you can create a custom connector that extends the abstract FuelConnector class. This interface provides a set of methods and events that allow you to interact with the wallet and handle various operations such as connecting, disconnecting, signing messages, and sending transactions.

<<< @./snippets/connectors.ts#fuel-connector-extends{ts:line-numbers}

Properties

The FuelConnector abstract class provides several properties that should be implemented to provide information about the connector.

`name`

The name property is simply a string on the connector that serves as an identifier and will be displayed to the end-user when selecting a connector.

<<< @./snippets/connectors.ts#fuel-connector-name{ts:line-numbers}

`external`

The external property is simply a boolean that indicates when a connector is external or not.
Connectors are considered external, or non-native, when they do not support the Fuel Network (e.g. Solana, WalletConnect).

`metadata`

The metadata property on the connector provides additional information about the connector. This information will be displayed to the end-user when selecting a connector. The following is the structure of the metadata object:

<<< @/../../../packages/account/src/connectors/types/connector-metadata.ts#fuel-connector-metadata{ts:line-numbers}

`install`

The metadata.install property (required) is used to provide information about how to install the connector.

The install object requires three properties:

  • action (required) - a string that will contain an action string that will be displayed to the user (e.g. "Install").

  • link (required) - a string that will contain a URL that will be opened when the user clicks the action.

  • description (required) - a string that will contain a description of the installation process.

<<< @./snippets/connectors.ts#fuel-connector-metadata-install{ts:line-numbers}

`image`

The metadata.image property (optional) provides an image that will be displayed to the end-user when selecting a connector. The image will be a URL to the image to be displayed (this can be an inline data URI, encoded in base64).

<<< @./snippets/connectors.ts#fuel-connector-metadata-image{ts:line-numbers}

You can even define a light and dark theme for the image by providing an object with the light and dark keys (these will take a similar URI as above).

<<< @./snippets/connectors.ts#fuel-connector-metadata-image-theme{ts:line-numbers}

Events

The FuelConnector class provides a number of events that enable developers to listen for changes in the connector state. As part of implementing a custom connector, you can emit these events to notify the consumer dApp of changes.

`accounts`

The accounts event is emitted every time a connector's accounts change. The event data is an array of string addresses available on the network.

<<< @./snippets/connectors.ts#fuel-connector-events-accounts{ts:line-numbers}

`connectors`

The connectors event is emitted when the connectors are initialized. The event data is an array of FuelConnector objects available on the network.

<<< @./snippets/connectors.ts#fuel-connector-events-connectors{ts:line-numbers}

`currentConnector`

The currentConnector event is emitted every time the current connector changes. The event data is a FuelConnector object that is currently connected.

<<< @./snippets/connectors.ts#fuel-connector-events-currentConnector{ts:line-numbers}

`currentAccount`

The currentAccount event is emitted every time the current account changes. The event data is a string containing the current account address.

<<< @./snippets/connectors.ts#fuel-connector-events-currentAccount{ts:line-numbers}

`connection`

The connection event is emitted every time the connection status changes. The event data is a boolean value that is true if the connection is established and false otherwise.

<<< @./snippets/connectors.ts#fuel-connector-events-connection{ts:line-numbers}

`networks`

The networks event is emitted every time the network changes. The event data will be a Network object containing the current network information.

<<< @./snippets/connectors.ts#fuel-connector-events-networks{ts:line-numbers}

`currentNetwork`

The currentNetwork event is emitted every time the current network changes. The event data will be a Network object containing the current network information.

<<< @./snippets/connectors.ts#fuel-connector-events-currentNetwork{ts:line-numbers}

`assets`

The assets event is emitted every time the assets change. The event data will be an array of Asset objects available on the network.

<<< @./snippets/connectors.ts#fuel-connector-events-assets{ts:line-numbers}

`abis`

The abis event is emitted every time an ABI is added to a connector. The event data will be an array of FuelABI object.

<<< @./snippets/connectors.ts#fuel-connector-events-assets{ts:line-numbers}

Methods

The FuelConnector abstract class provides a number of methods that can be implemented to perform various functions. Not all the methods are required to be implemented; if you choose not to implement a given method, then just don't include it in your connector.

`ping`

The ping method is used to check if the connector is available and connected.

It will return a promise that resolves to true if the connector is available and connected; otherwise, it will resolve to false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-ping{ts:line-numbers}

`version`

The version method is used to get the current supported version of the connector. It returns a promise that resolves to an object containing the app and network versions.

The returned version strings can be in a range of formats:

  • Caret Ranges (e.g. ^1.2.3)
  • Tilde Ranges (e.g. ~1.2.3)
  • Exact Versions (e.g. 1.2.3)

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-version{ts:line-numbers}

`isConnected`

The isConnected method informs if the connector is currently connected.

It will return a promise that resolves to true if the connector is established and currently connected; otherwise, it will return false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-isConnected{ts:line-numbers}

`connect`

The connect method initiates the current connectors authorization flow if a connection has not already been made.

It will return a promise that resolves to true if the connection has been established successfully, or false if the user has rejected it.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-connect{ts:line-numbers}

`disconnect`

The disconnect method revokes the authorization of the current connector (provided by the connect methods).

It will return a promise that resolves to true if the disconnection is successful; otherwise, it will resolve to false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-connect{ts:line-numbers}

`accounts`

The accounts method should return a list of all the accounts for the current connection.

It returns a promise that resolves to an array of addresses, pointing to the accounts currently available on the network.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-accounts{ts:line-numbers}

`currentAccount`

The currentAccount method will return the default account address if it's authorized with the connection.

It will return a promise to resolve the issue to an address, or if the account is not authorized for the connection, it will return null.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-currentAccount{ts:line-numbers}

`signMessage`

The signMessage method initiates the sign message flow for the current connection.

It requires two arguments:

  • address (string)
  • message (string)

Providing the message signing flow is successful, it will return the message signature (as a string).

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-signMessage{ts:line-numbers}

`sendTransaction`

The signTransaction method initiates the send transaction flow for the current connection.

It requires two arguments:

It will return the transaction signature (as a string) if it is successfully signed.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-sendTransaction{ts:line-numbers}

`assets`

The assets method returns a list of all the assets available for the current connection.

It will return a promise that will resolve to an array of assets (see Asset) that are available on the network.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-assets{ts:line-numbers}

`addAsset`

The addAsset method adds asset metadata to the connector.

It requires a single argument:

It returns a promise that resolves to true if the asset is successfully added; otherwise, it resolves to false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-addAsset{ts:line-numbers}

`addAssets`

The addAssets method adds multiple asset metadata to the connector.

It requires a single argument:

  • assets (an Array of Asset).

Returns a promise that resolves to true if the assets are successfully added; otherwise, resolves to false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-addAssets{ts:line-numbers}

`addNetwork`

The addNetwork method starts the add network flow for the current connection.

It requires a single argument:

  • networkUrl (string)

Returns a promise that resolves to true if the network is successfully added; otherwise, false.

It should throw an error if the network is not available or the network already exists.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-addNetwork{ts:line-numbers}

`networks`

The networks method returns a list of all the networks available for the current connection.

Returns a promise that resolves to an array of available networks (see Network).

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-networks{ts:line-numbers}

`currentNetwork`

The currentNetwork method will return the current network that is connected.

It will return a promise that will resolve to the current network (see Network).

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-currentNetwork{ts:line-numbers}

`selectNetwork`

The selectNetwork method requests the user to select a network for the current connection.

It requires a single argument:

You call this method with either the providerUrl or chainId to select the network.

It will return a promise that resolves to true if the network is successfully selected; otherwise, it will return false.

It should throw an error if the network is not available or the network does not exist.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-selectNetwork{ts:line-numbers}

`addABI`

The addABI method adds ABI information about a contract to the connector. This operation does not require an authorized connection.

It requires two arguments:

  • contractId (string)
  • abi (FuelABI).

It will return a promise that will resolve to true if the ABI is successfully added; otherwise false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-addABI{ts:line-numbers}

`getABI`

The getABI method is used to get the ABI information that is sorted about a contract.

It requires a single argument:

  • contractId (string)

Returns a promise that resolves to the ABI information (as a FuelABI) or null if the data is unavailable.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-getABI{ts:line-numbers}

`hasABI`

The hasABI method checks if the ABI information is available for a contract.

It requires a single argument:

  • contractId (string)

Returns a promise that resolves to true if the ABI information is available; otherwise false.

<<< @/../../../packages/account/src/connectors/fuel-connector.ts#fuel-connector-method-hasABI{ts:line-numbers}

Connectors Manager

The TS SDK exports the Fuel class, which serves as the connectors manager. This class provides the interface for interacting with the TS SDK and the broader Fuel ecosystem.

It can be instantiated as follows:

<<< @./snippets/fuel-instantiation-one.ts#fuel-instantiation-1{ts:line-numbers}

[!NOTE] Note
We recommend initializing the Fuel class with the init method to avoid any potential race conditions that may arise from the async nature of instantiating a connector.

Options

Several options can be passed to the Fuel connector manager:

`connectors`

The connectors option provides a list of connectors with which the Fuel connector manager can interact. The manager interacts with the connectors, which in turn handle communication with the respective wallet. You can find a list of all the connectors in our FuelLabs/fuel-connectors.

Below, we initialize the manager using the defaultConnectors method which provides an array of all the default connectors available in the fuel-connectors package. It's being mocked here for the purposes of this example, but you can provide your own custom connectors. Supplying the devMode flag as true will enable the development wallet for the connectors (to install visit our wallet documentation).

<<< @./snippets/fuel-instantiation-options.ts#fuel-options-connectors{ts:line-numbers}

`storage`

The storage is used internally to store the current connector state. It can be overridden by passing an instance that extends the StorageAbstract class.

<<< @./snippets/fuel-options-storage-memory.ts#fuel-options-storage-memory{ts:line-numbers}

The default behavior will use LocalStorage if the window is available:

<<< @./snippets/fuel-options-storage-local.ts#fuel-options-storage-local{ts:line-numbers}

`targetObject`

The targetObject provides a target with which the Fuel manager can interact. Used for registering events and can be overridden as follows:

<<< @./snippets/fuel-options-target-object.ts#fuel-options-target-object{ts:line-numbers}

Methods

The Fuel manager provides several methods to interact with the Manager:

All methods from connectors

The Fuel manager provides all the methods available from the connected connectors. Thus, you can interact with the current connector as if you were interacting with the Fuel manager directly.

If no current connector is available or connected, it will throw an error.

`connectors`

The connectors method gets the current list of installed and connected connectors.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-connectors{ts:line-numbers}

`getConnector`

The getConnector method resolves a connector by its name. This is useful for finding a specific connector with which to interact. If the connector is not found, it will return null.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-getConnector{ts:line-numbers}

`hasConnector`

The hasConnector method will return true under the following conditions:

  • There is a current connector that is connected.
  • A connector is connected within two seconds of calling the method.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-hasConnector{ts:line-numbers}

`selectConnector`

The selectConnector method accepts a connector name and will return true when it is available and connected. Otherwise, if not found or unavailable, it will return false.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-selectConnector{ts:line-numbers}

`currentConnector`

The currentConnector method will return the current connector that is connected or if one is available and connected, otherwise it'll return null or undefined.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-currentConnector{ts:line-numbers}

`getWallet`

The getWallet method accepts an address (string or instance) as the first parameter and a provider or network as the second parameter. It will return an Account instance for the given address (providing it is valid).

The provider or network will default to the current network if not provided. When a provider cannot be resolved, it will throw an INVALID_PROVIDER error.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-getWallet{ts:line-numbers}

`clean`

The clean method removes all the data currently stored in the storage instance.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-clean{ts:line-numbers}

`unsubscribe`

The unsubscribe method removes all currently registered event listeners.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-unsubscribe{ts:line-numbers}

`destroy`

The destroy method unsubscribes from all the event listeners and clears the storage.

<<< @/../../../packages/account/src/connectors/fuel.ts#connector-manager-method-destroy{ts:line-numbers}

Learning Resources

For a deeper understanding of Fuel Connectors and how to start using them in your projects, consider the following resources:


Apps Docs Src Guide Wallets Encrypting And Decrypting (`apps/docs/src/guide/wallets/encrypting-and-decrypting.md`)

Encrypting and Decrypting

JSON wallets are a standardized way of storing wallets securely. They follow a specific schema and are encrypted using a password. This makes it easier to manage multiple wallets and securely store them on disk. This guide will take you through the process of encrypting and decrypting JSON wallets using the Typescript SDK.

Encrypting a Wallet

We will be calling encrypt from the WalletUnlocked instance which will take a password as the argument. It will encrypt the private key using a cipher and returns the JSON keystore wallet. You can then securely store this JSON wallet.

Here is an example of how you can accomplish this:

<<< @./snippets/encrypting-and-decrypting-wallets.ts#encrypting-and-decrypting-json-wallets-1{ts:line-numbers}

Please note that encrypt must be called within an instance of WalletUnlocked. This instance can only be achieved through passing a private key or mnemonic phrase to a locked wallet.

Decrypting a Wallet

To decrypt the JSON wallet and retrieve your private key, you can call fromEncryptedJson on a Wallet instance. It takes the encrypted JSON wallet and the password as its arguments, and returns the decrypted wallet.

Here is an example:

<<< @./snippets/encrypting-and-decrypting-json-wallets-two.ts#encrypting-and-decrypting-json-wallets-2{ts:line-numbers}

In this example, decryptedWallet is an instance of WalletUnlocked class, now available for use.

Important

Remember to securely store your encrypted JSON wallet and password. If you lose them, there will be no way to recover your wallet. For security reasons, avoid sharing your private key, encrypted JSON wallet or password with anyone.


Apps Docs Src Guide Wallets Instantiating Wallets (`apps/docs/src/guide/wallets/instantiating-wallets.md`)

Instantiating Wallets

Wallets can be instantiated in multiple ways within the SDK.

Generating new wallets

To generate a new, unlocked wallet, use the generate method. This method creates a new WalletUnlocked instance, which is immediately ready for use.

<<< @./snippets/instantiating/generate.ts#instantiating-wallets-1{ts:line-numbers}

Instantiating Unlocked Wallets

Creating WalletUnlocked instances of your existing wallets is easy and can be done in several ways:

From a private key:

<<< @./snippets/instantiating/from-private-key.ts#instantiating-wallets-2{ts:line-numbers}

From a mnemonic phrase:

<<< @./snippets/instantiating/from-mnemonic-phrase.ts#instantiating-wallets-3{ts:line-numbers}

From a seed:

<<< @./snippets/instantiating/from-seed.ts#instantiating-wallets-4{ts:line-numbers}

From a Hierarchical Deterministic (HD) derived key:

<<< @./snippets/instantiating/from-hd-derived-key.ts#instantiating-wallets-5{ts:line-numbers}

From a JSON wallet:

<<< @./snippets/instantiating/from-json-wallet.ts#instantiating-wallets-6{ts:line-numbers}

It's possible to instantiate a WalletUnlocked from a WalletLocked:

<<< @./snippets/instantiating/unlock-from-private-key.ts#instantiating-wallets-7{ts:line-numbers}

Instantiating Locked Wallets

You can also instantiate WalletLocked instances using just the wallet address:

<<< @./snippets/instantiating/from-b256-address.ts#instantiating-wallets-8{ts:line-numbers}

Connecting to a Provider

While wallets can be used independently of a Provider, operations requiring blockchain interaction will need one.

Connecting an existing wallet to a Provider:

<<< @./snippets/instantiating/connect-existing-wallet.ts#instantiating-wallets-9{ts:line-numbers}

Instantiating a wallet with a Provider:

<<< @./snippets/instantiating/connect-new-wallet.ts#instantiating-wallets-10{ts:line-numbers}


Apps Docs Src Guide Wallets Locking And Unlocking (`apps/docs/src/guide/wallets/locking-and-unlocking.md`)

Locking and Unlocking

The kinds of operations we can perform with a Wallet instance depend on
whether or not we have access to the wallet's private key.

In order to differentiate between Wallet instances that know their private key
and those that do not, we use the WalletUnlocked and WalletLocked types
respectively.

Wallet States

The WalletUnlocked type represents a wallet whose private key is known and
stored internally in memory. A wallet must be of type WalletUnlocked in order
to perform operations that involve signing messages or transactions.

The WalletLocked type represents a wallet whose private key is not known or stored
in memory. Instead, WalletLocked only knows its public address. A WalletLocked cannot be
used to sign transactions, however it may still perform a whole suite of useful
operations including listing transactions, assets, querying balances, and so on.

Note that the WalletUnlocked type implements most methods available on the WalletLocked
type. In other words, WalletUnlocked can be thought of as a thin wrapper around WalletLocked that
provides greater access via its private key.

Basic Example

<<< @./snippets/access.ts#wallets{ts:line-numbers}

Optional Provider

You can choose not to pass through a provider argument on Wallet construction:

<<< @./snippets/wallet-optional-provider.ts#wallet-optional-provider{ts:line-numbers}

Transitioning States

A WalletLocked instance can be unlocked by providing the private key:

<<< @./snippets/locked-to-unlocked.ts#wallet-locked-to-unlocked{ts:line-numbers}

A WalletUnlocked instance can be locked using the lock method:

<<< @./snippets/unlocked-to-locked.ts#wallet-unlocked-to-locked{ts:line-numbers}

Most wallet constructors that create or generate a new wallet are provided on
the WalletUnlocked type. Consider locking the wallet with the lock method after the new private
key has been handled in order to reduce the scope in which the wallet's private
key is stored in memory.

Design Guidelines

When designing APIs that accept a wallet as an input, we should think carefully
about the kind of access that we require. API developers should aim to minimise
their usage of WalletUnlocked in order to ensure private keys are stored in
memory no longer than necessary to reduce the surface area for attacks and
vulnerabilities in downstream libraries and applications.

Full Example

For a full example of how to lock and unlock a wallet, see the snippet below:

<<< @./snippets/access.ts#full{ts:line-numbers}


Apps Docs Src Guide Wallets Mnemonic Wallet (`apps/docs/src/guide/wallets/mnemonic-wallet.md`)

Creating a wallet from mnemonic phrases

A mnemonic phrase is a cryptographically-generated sequence of words that's used to derive a private key. For instance: "oblige salon price punch saddle immune slogan rare snap desert retire surprise"; would generate the address 0xdf9d0e6c6c5f5da6e82e5e1a77974af6642bdb450a10c43f0c6910a212600185.

In addition to that, we also support Hierarchical Deterministic Wallets and derivation paths, allowing multiple wallets to be derived from a single root mnemonic. You may recognize a derivation path like:

text
"m/44'/1179993420'/0'/0/0"

In simple terms, this structure enables the creation of multiple wallet addresses from the same mnemonic phrase.

The SDK gives you two wallets from mnemonic instantiation methods: one that takes a derivation path and one that uses the default derivation path, in case you don't want or don't need to configure that.

Here's how you can create wallets with both mnemonic phrases and derivation paths:

1 - Using the default derivation path m/44'/1179993420'/0'/0/0

<<< @./snippets/mnemonic/from-mnemonic-phrases-1.ts#snippet-full{ts:line-numbers}

2 - Using a Custom Derivation Path

<<< @./snippets/mnemonic/from-mnemonic-phrases-2.ts#snippet-full{ts:line-numbers}


Apps Docs Src Guide Wallets Private Keys (`apps/docs/src/guide/wallets/private-keys.md`)

Creating a wallet from a private key

A new wallet with a randomly generated private key can be created by supplying Wallet.generate.

<<< @./snippets/access.ts#wallets{ts:line-numbers}

Alternatively, you can create a wallet from a Private Key:

<<< @./snippets/instantiating/from-wallet.ts#wallet-from-private-key{ts:line-numbers}

You can obtain an address to a private key using the Signer package

<<< @./snippets/instantiating/signer.ts#signer-address{ts:line-numbers}


Apps Docs Src Guide Wallets Signing (`apps/docs/src/guide/wallets/signing.md`)

Signing

Signing Messages

Signing messages with a wallet is a fundamental security practice in a blockchain environment. It can be used to verify ownership and ensure the integrity of data.

Here's how to use the wallet.signMessage method to sign messages (as string):

<<< @./snippets/signing/sign-message.ts#signing-1{ts:line-numbers}

The signMessage method internally:

  • Hashes the message (via hashMessage)
  • Signs the hashed message using the wallet's private key
  • Returns the signature as a hex string

The hashMessage helper will:

  • Performs a SHA-256 hash on the UTF-8 encoded message.

The recoverAddress method from the Signer class will take the hashed message and the signature to recover the signer's address. This confirms that the signature was created by the holder of the private key associated with that address, ensuring the authenticity and integrity of the signed message.

Signing Personal Message

We can also sign arbitrary data, not just strings. This is possible by passing an object containing the personalSign property to the hashMessage and signMessage methods:

<<< @./snippets/signing/sign-personal-message.ts#signing-personal-message{ts:line-numbers}

The primary difference between this personal message signing and message signing is the underlying hashing format.

To format the message, we use a similar approach to a EIP-191:

console
\x19Fuel Signed Message:\n<message length><message>

Note: We still hash using SHA-256, unlike Ethereum's EIP-191 which uses Keccak-256.

Signing Transactions

Signing a transaction involves using your wallet to sign the transaction ID (also known as transaction hash) to authorize the use of your resources. Here's how it works:

  1. Generate a Signature: Using the wallet to create a signature based on the transaction ID.

  2. Using the Signature on the transaction: Place the signature in the transaction's witnesses array. Each Coin / Message input should have a matching witnessIndex. This index indicates your signature's location within the witnesses array.

  3. Security Mechanism: The transaction ID is derived from the transaction bytes (excluding the witnesses). If the transaction changes, the ID changes, making any previous signatures invalid. This ensures no unauthorized changes can be made after signing.

The following code snippet exemplifies how a Transaction can be signed:

<<< @./snippets/signing/sign-transaction.ts#signing-2{ts:line-numbers}

Similar to the sign message example, the previous code used Signer.recoverAddress to get the wallet's address from the transaction ID and the signed data.

When using your wallet to submit a transaction with wallet.sendTransaction(), the SDK already handles these steps related to signing the transaction and adding the signature to the witnesses array. Because of that, you can skip this in most cases:

<<< @./snippets/signing/fund-transaction.ts#signing-3{ts:line-numbers}


Apps Docs Src Guide Wallets Wallet Manager (`apps/docs/src/guide/wallets/wallet-manager.md`)

Wallet Manager

The WalletManager is a robust tool designed for managing vaults of wallets. It offers robust management of vaults, including support for custom storage and powerful encryption of all held vaults.

Key Features

Managing Vaults with `WalletManager`

This includes adding new wallets to specific vaults, retrieving all wallets from a vault, exporting specific vaults, and exporting private keys. The WalletManager class currently supports two types of vaults: PrivateKeyVault and MnemonicVault.

Custom Storage Solutions

The WalletManager supports defining a custom storage solution, allowing you to specify how and where the encrypted vaults are saved. With support for custom storage, you can make the WalletManager to fit your specific needs and security requirements.

Locking and Unlocking `WalletManager`

The WalletManager implements an automatic encryption mechanism, securely saving the wallet's held vaults. This not only preserves the state of your vaults but also ensures robust protection of the stored information. When needed, you can easily unlock and decrypt the vaults using the previously defined password.

Getting Started with `WalletManager`

This guide provides step-by-step instructions on how to use WalletManager.

Instantiating `WalletManager`

The WalletManager constructor accepts an optional object to define its storage. The storage describes how and where the WalletManager will store its vaults of wallets. If storage is not provided, the WalletManager uses a default one that does not persist data.

For now, let's keep it simple and not worry about the storage. Later we will discuss it in more detail.

To instantiate a WalletManager you can simply:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-1{ts:line-numbers}

Setting `WalletManager` Password

By default, a WalletManager instance is locked when created. Before using it, you need to unlock it by setting a password. You can do this by calling the unlock method.

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-2{ts:line-numbers}

Once your WalletManager is unlocked, it can manage your wallets.

Managing Vaults with `WalletManager`

A vault in WalletManager serves as a secure container for wallets. The WalletManager manages wallets by interacting with these vaults, supporting operations such as getAccounts, which returns public information about all wallets stored in the vault, and exportAccount, which exports a private key for a given wallet address.

To add a vault, we utilize the addVault method. Here's how we can create a private key vault and add a private key from a wallet we own:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-3{ts:line-numbers}

The addVault method requires an object with three properties: type, secret, and title. The WalletManager currently supports two types of vaults: privateKeyVault and mnemonicVault. For the secret, we use our wallet's private key, and for the title, we can provide a custom name.

By running this code, WalletManager creates a new vault instance of the type privateKey and adds one account (our wallet) to this newly created vault.

A key feature of the WalletManager is its ability to manage multiple vaults, even of the same type. This implies that if you run the addVault method again, with the same parameters, WalletManager will create another vault of the type privateKey, holding the same wallet. Here's an example:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-4{ts:line-numbers}

After executing this, you will find that your WalletManager is managing two privateKey vaults, both storing the same wallet.

Remember, both title and secret are optional when adding vaults, but providing a title makes it easier to manage your vaults and wallets. If you add a vault without providing a secret, this will result in one new account (wallet) being generated by the vault it self.

Using The `WalletManager`

With your WalletManager set up, you can now access your vaults and wallets. Here's how to retrieve the details of your vaults:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-5{ts:line-numbers}

This will output something like this:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-6{bash:line-numbers}

As you can see, the WalletManager assigns unique vaultIds for each vault. The first vault you added has a vaultId of 0, and the second one has a vaultId of 1.

Let's retrieve your wallet instance with the getWallet method:

<<< @./snippets/getting-started-with-wallet-manager.ts#getting-started-with-wallet-manager-7{ts:line-numbers}

This guide walked through the steps to instantiate a WalletManager, set up its first vault, and retrieve vault information. The following sections will explore more functionalities of WalletManager, and go deeper into the usage of its vaults and the details of its storage system.

Locking and Unlocking `WalletManager`

This guide will walk you through the process of managing the lock state of your wallets using the WalletManager.

Initializing and Unlocking the `WalletManager`

As mentioned earlier, a WalletManager instance begins in a locked state. Before usage, you need to unlock it by providing a password via the unlock method.

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-1{ts:line-numbers}

Locking the `WalletManager`

When you lock the WalletManager using the lock method, all its vaults and associated accounts (wallets) are cleared. This clearance is possible due to the encryption and saving of all data by the storage system. WalletManager frequently uses the storage system to preserve its state. Consequently, sensitive operations including exporting vaults, private keys, accessing wallets, and saving/loading the WalletManager state are not possible when it is locked.

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-2{ts:line-numbers}

Remember, it's crucial to lock your WalletManager when it's not in use to ensure the safety of your funds.

Reaccessing Your Wallets by Unlocking the `WalletManager`

The unlock method requires the previously set password to unlock the WalletManager and all its vaults. The password decrypts the stored vaults, allowing WalletManager to load its saved data.

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-3{ts:line-numbers}

Providing an incorrect password will result in an error. However, when unlocked successfully, WalletManager is ready for use again.

Verifying the Lock State

You can confirm the current lock state of the WalletManager by using the isLocked method:

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-4{ts:line-numbers}

Updating the Password

To change the current password, invoke the updatePassphrase method, and provide both the old and new passwords:

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-5{ts:line-numbers}

Reminder: Always Lock Your `WalletManager`

Always ensure you lock the WalletManager after completing operations. This step is critical for securing your wallets.

<<< @./snippets/locking-and-unlocking-wallet-manager.ts#locking-and-unlocking-wallet-manager-6{ts:line-numbers}

By using WalletManager to manage lock and unlock states, you introduce an additional layer of security. Never forget to lock your WalletManager when it's not in use.


Apps Docs Src Guide Wallets Wallet Transferring (`apps/docs/src/guide/wallets/wallet-transferring.md`)

Wallet Transferring

This guide provides instructions for transferring assets between wallets and contracts using the SDK. It includes methods to validate balances and initiate and configure transfer requests.

Transferring Assets Between Accounts

The transfer method initiates a transaction request that transfers an asset from one wallet to another. This method requires three parameters:

  1. The receiver's wallet address
  2. The amount of the asset to be transferred
  3. The ID of the asset to be transferred (optional - defaults to the base asset ID)

Upon execution, this function returns a promise that resolves to a transaction response. To wait for the transaction to be processed, call response.waitForResult().

Example

Here is an example of how to use the transfer function:

<<< @./snippets/wallet-transferring/between-accounts.ts#transferring-assets-1{ts:line-numbers}

In the previous example, we used the transfer method which creates a ScriptTransactionRequest, populates its data with the provided transfer information and submits the transaction.

However, there may be times when you need the Transaction ID before actually submitting it to the node. To achieve this, you can simply call the createTransfer method instead.

This method also creates a ScriptTransactionRequest and populates it with the provided data but returns the request object prior to submission.

<<< @./snippets/wallet-transferring/create-transfer.ts#transferring-assets-2{ts:line-numbers}

Note: Any changes made to a transaction request will alter the transaction ID. Therefore, you should only get the transaction ID after all modifications have been made.

<<< @./snippets/wallet-transferring/create-transfer-2.ts#transferring-assets-3{ts:line-numbers}

Transferring Assets To Multiple Wallets

To transfer assets to multiple wallets, use the Account.batchTransfer method:

<<< @./snippets/transfers/batch-transfer.ts#wallet-transferring-6{ts:line-numbers}

Transferring Assets To Contracts

When transferring assets to a deployed contract, we use the transferToContract method, which shares a similar parameter structure with the transfer method.

However, instead of supplying the target wallet's address, as done in destination.address for the transfer method, we need to provide an instance of Address created from the deployed contract id.

If you have the Contract instance of the deployed contract, you can simply use its id property. However, if the contract was deployed with forc deploy or not by you, you will likely only have its ID in a hex string format. In such cases, you can create an Address instance from the contract ID using new Address('0x123...').

Here's an example demonstrating how to use transferToContract:

<<< @./snippets/wallet-transferring/transferring-to-contracts.ts#transferring-assets-4{ts:line-numbers}

Note: Use transferToContract exclusively for transfers to a contract. For transfers to an account address, use transfer instead.

Transferring Assets To Multiple Contracts

Similar to the Account.batchTransfer method, you can transfer multiple assets to multiple contracts using the Account.batchTransferToContracts method. Here's how it works:

<<< @./snippets/wallet-transferring/transferring-to-multiple-contracts.ts#transferring-assets-5{ts:line-numbers}

Always remember to call the waitForResult() function on the transaction response. That ensures the transaction has been mined successfully before proceeding.

Note: Use batchTransferToContracts solely for transferring assets to contracts. Do not use account addresses with this method. For multiple account transfers, use batchTransfer instead.

Checking Balances

Before you transfer assets, please make sure your wallet has enough funds. Attempting a transfer without enough funds will result in the error: The transaction does not have enough funds to cover its execution.

You can see how to check your balance at the checking-balances page.


--- METRICS ---