Icon HelpCircleForumIcon Link


Icon HelpCircleForumIcon Link
Deploying Contracts

Icon LinkDeploying Contracts

This guide walks you through deploying a contract using the SDK, covering loading contract artifacts, initializing a contract factory, and deploying the contract.

Icon Link1. Obtaining Contract Artifacts

After writing a contract in Sway and compiling it with forc build (read more Icon Link on how to work with Sway), you will obtain two important artifacts: the compiled binary file and the JSON ABI file. These files are required for deploying a contract using the SDK.

Icon Link2. Setting up the SDK Environment

Before deploying a contract, set up the necessary environment by importing the required SDK components and initializing a wallet and a provider.

const PRIVATE_KEY = "..."
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(PRIVATE_KEY, provider);

Icon Link3. Loading Contract Artifacts

Load the contract bytecode and JSON ABI, generated from the Sway source, into the SDK.

const contractsDir = join(__dirname, '../path/to/contracts/dir')
const contractName = "contract-name"
const byteCodePath = join(projectsPath, `${contractName}/out/release/${contractName}.bin`);
const byteCode = readFileSync(byteCodePath);
const abiJsonPath = join(projectsPath, `${contractName}/out/release/${contractName}-abi.json`);
const abi = JSON.parse(readFileSync(abiJsonPath, 'utf8'));

Icon Link4. Deploying the Contract

To deploy the contract, instantiate the ContractFactory with the bytecode, ABI, and wallet. Then, call the deployContract method. This call resolves as soon as the transaction to deploy the contract is submitted and returns three items: the contractId, the transactionId and a waitForResult function.

const factory = new ContractFactory(byteCode, abi, wallet);
const { contractId, transactionId, waitForResult } = await factory.deployContract();

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.

const { contract, transactionResult } = await waitForResult();

Icon Link5. Executing a Contract Call

Now that the contract is deployed, you can interact with it. In the following steps, you'll learn how to execute contract calls.

const call = await contract.functions.echo_u8(15).call();
const { value } = await call.waitForResult();

For a more comprehensive TypeScript-backed Fuel usage, learn how to generate types from ABI