Skip to content

Commit

Permalink
docs: improve cookbook/transaction-request (#3440)
Browse files Browse the repository at this point in the history
  • Loading branch information
Torres-ssf authored Dec 4, 2024
1 parent 260274a commit 2c60078
Show file tree
Hide file tree
Showing 16 changed files with 214 additions and 91 deletions.
4 changes: 4 additions & 0 deletions .changeset/spicy-mails-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

docs: improve `cookbook/transaction-request`
4 changes: 2 additions & 2 deletions apps/docs/scripts/launcher-snippet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { launchTestNode } from 'fuels/test-utils';
import { launchTestNode, TestMessage } from 'fuels/test-utils';

using node = await launchTestNode({ walletsConfig: { count: 5 } });
using node = await launchTestNode({ walletsConfig: { count: 5, messages: [new TestMessage()] } });

const LOCAL_NETWORK_URL = node.provider.url;

Expand Down
2 changes: 1 addition & 1 deletion apps/docs/scripts/wrap-snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const wrapSnippet = (filepath: string) => {
Adds `launchTestNode` import, always right below the last `fuels` import
and before the next relative one.
*/
const launchImport = `import { launchTestNode } from 'fuels/test-utils';`;
const launchImport = `import { launchTestNode, TestMessage } from 'fuels/test-utils';`;

const searchStr = `from 'fuels';`;
const lastIndexStart = imports.lastIndexOf(searchStr);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Provider, ScriptTransactionRequest, Wallet } from 'fuels';
import { TestAssetId } from 'fuels/test-utils';

import {
LOCAL_NETWORK_URL,
WALLET_PVT_KEY,
WALLET_PVT_KEY_2,
} from '../../../../env';
import { ScriptSum } from '../../../../typegend';

// #region transaction-request-3
const provider = await Provider.create(LOCAL_NETWORK_URL);

const recipient1 = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
const recipient2 = Wallet.fromPrivateKey(WALLET_PVT_KEY_2, provider);

const baseAssetId = provider.getBaseAssetId();
const assetA = TestAssetId.A.value;

const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
});

transactionRequest.addCoinOutput(recipient1.address, 1000, baseAssetId);
transactionRequest.addCoinOutput(recipient2.address, 500, assetA);
// #endregion transaction-request-3
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { ScriptSum, SimplePredicate } from '../../../../typegend';
const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

// #region transaction-request-5
// #region transaction-request-9
// Instantiate the transaction request
const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
Expand Down Expand Up @@ -42,4 +42,4 @@ const predicateCoins = await predicate.getResourcesToSpend([

// Add the predicate input and resources
transactionRequest.addResources(predicateCoins);
// #endregion transaction-request-5
// #endregion transaction-request-9
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
import type { Account } from 'fuels';
import {
Provider,
ScriptTransactionRequest,
WalletUnlocked,
ZeroBytes32,
} from 'fuels';

import { LOCAL_NETWORK_URL } from '../../../../env';
import { Provider, ScriptTransactionRequest, Wallet } from 'fuels';

import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env';
import { ScriptSum } from '../../../../typegend';

// #region transaction-request-10
const provider = await Provider.create(LOCAL_NETWORK_URL);
const witness = ZeroBytes32;
const accountA = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
const accountB = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
});

// #region transaction-request-6
// Add a witness directly
transactionRequest.addWitness(witness);
// Add a witness signature directly
const signature = await accountA.signTransaction(transactionRequest);
transactionRequest.addWitness(signature);

// Add a witness using an account
const account: Account = WalletUnlocked.generate({ provider });
await transactionRequest.addAccountWitnesses(account);
// #endregion transaction-request-6
// Or add multiple via `addAccountWitnesses`
await transactionRequest.addAccountWitnesses([accountB]);
// #endregion transaction-request-10

// #region transaction-request-7
// #region transaction-request-11
// Get the chain ID
const chainId = provider.getChainId();

// Get the transaction ID using the Chain ID
const transactionId = transactionRequest.getTransactionId(chainId);
// TX ID: 0x420f6...
// #endregion transaction-request-7
// #endregion transaction-request-11

console.log('transactionId', transactionId);
console.log('witnesses', transactionRequest.witnesses.length === 2);
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Provider, ScriptTransactionRequest, Wallet } from 'fuels';

import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env';
import { ScriptSum } from '../../../../typegend';

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

// #region transaction-request-4
const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
});

const cost = await wallet.getTransactionCost(transactionRequest);

transactionRequest.gasLimit = cost.gasUsed;
transactionRequest.maxFee = cost.maxFee;

await wallet.fund(transactionRequest, cost);

await wallet.sendTransaction(transactionRequest);
// #endregion transaction-request-4
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Provider, ScriptTransactionRequest, Wallet } from 'fuels';

import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env';
import { ScriptSum } from '../../../../typegend';

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
const baseAssetId = provider.getBaseAssetId();

const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
});

// #region transaction-request-6
// Fetching coins
const { coins } = await wallet.getCoins(baseAssetId);
const { messages } = await wallet.getMessages();

// Adding a specific coin or message
transactionRequest.addCoinInput(coins[0]);
transactionRequest.addMessageInput(messages[0]);
// #endregion transaction-request-6
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { CoinQuantity } from 'fuels';
import { bn, Provider, ScriptTransactionRequest, Wallet } from 'fuels';
import { TestAssetId } from 'fuels/test-utils';

import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env';
import { ScriptSum } from '../../../../typegend';

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

// #region transaction-request-5
// Instantiate the transaction request
const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
});

const baseAssetId = provider.getBaseAssetId();
const assetA = TestAssetId.A.value;

// Define the quantities to fetch
const quantities: CoinQuantity[] = [
{
amount: bn(10000),
assetId: baseAssetId,
},
{
amount: bn(100),
assetId: assetA,
},
];

// Fetching resources
const resources = await wallet.getResourcesToSpend(quantities);

// Adding resources (coins or messages)
transactionRequest.addResources(resources);
// #endregion transaction-request-5

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Provider, ScriptTransactionRequest, Wallet } from 'fuels';

import { LOCAL_NETWORK_URL, WALLET_PVT_KEY } from '../../../../env';
import { CounterFactory, ScriptSum } from '../../../../typegend';

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

// #region transaction-request-8
const deploy = await CounterFactory.deploy(wallet);
const { contract } = await deploy.waitForResult();

const transactionRequest = new ScriptTransactionRequest({
script: ScriptSum.bytecode,
scriptData: contract.id.toB256(),
});

// Add the contract input and output using the contract ID
transactionRequest.addContractInputAndOutput(contract.id);
// #endregion transaction-request-8
42 changes: 33 additions & 9 deletions apps/docs/src/guide/transactions/transaction-request.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,55 @@ A `CreateTransactionRequest` is used for create transactions, which are transact

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 Resources to a Transaction Request
### Adding `OutputCoin`

Resources populate the inputs and outputs of a transaction request. This can take the form of coins, messages or contracts. The SDK provides a range of methods for dealing with resources. Below will detail how coins and messages can be added to a transaction request.
Including `OutputCoin`s 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/fund-request.ts#transaction-request-3{ts:line-numbers}
<<< @./snippets/transaction-request/add-output-coin.ts#transaction-request-3{ts:line-numbers}

### Adding a Contract to a Transaction Request
### Estimating and Funding the Transaction Request

Scripts can perform multiple actions on chain, therefore you may want to chain contract calls. For this you will need to add a contract to the transaction request. This can be done like so:
Before submitting a transaction, it is essential to ensure it is properly funded to meet its requirements and cover the associated fee:

<<< @./snippets/transaction-request/fund-request.ts#transaction-request-4{ts:line-numbers}
<<< @./snippets/transaction-request/estimate-and-fund.ts#transaction-request-4{ts:line-numbers}

This is the recommended approach for manually estimating and funding a transaction before submission. It ensures that the `gasLimit` and `maxFee` are accurately calculated and that the required amounts for `OutputCoin`s are fulfilled. The `fund` method automatically fetches any missing resource amounts from the calling account and adds them to the transaction request.

### 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:

<<< @../../../../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-5{ts:line-numbers}
<<< @./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](../predicates/index.md).
### 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-6{ts:line-numbers}
<<< @./snippets/transaction-request/add-witness.ts#transaction-request-10{ts:line-numbers}

A more complex example of adding multiple witnesses to a transaction request can be seen in the multiple signers guide [here](../cookbook/transactions-with-multiple-signers.md), which validates the signatures inside the script itself.

Expand All @@ -64,6 +88,6 @@ A more complex example of adding multiple witnesses to a transaction request can

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-7{ts:line-numbers}
<<< @./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.
1 change: 1 addition & 0 deletions apps/docs/sway/Forc.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ members = [
"simple-predicate",
"simple-token",
"simple-token-abi",
"script-call-contract",
"storage-test-contract",
"sum-option-u8",
"token",
Expand Down
7 changes: 7 additions & 0 deletions apps/docs/sway/script-call-contract/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
license = "Apache-2.0"
name = "script-call-contract"

[dependencies]
12 changes: 12 additions & 0 deletions apps/docs/sway/script-call-contract/src/counter.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
library;

abi CounterAbi {
#[storage(read)]
fn get_count() -> u64;

#[storage(write, read)]
fn increment_count(amount: u64) -> u64;

#[storage(write, read)]
fn decrement_count(amount: u64) -> u64;
}
11 changes: 11 additions & 0 deletions apps/docs/sway/script-call-contract/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
script;

mod counter;

// #region transaction-request-7
use counter::CounterAbi;
fn main(contract_id: ContractId) -> u64 {
let counter_contract = abi(CounterAbi, contract_id.into());
counter_contract.get_count()
}
// #endregion transaction-request-7

0 comments on commit 2c60078

Please sign in to comment.