Skip to content

Commit

Permalink
docs: optimistic transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
danielbate committed Dec 31, 2024
1 parent 7e26880 commit 2da9c34
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 3 deletions.
15 changes: 15 additions & 0 deletions apps/docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,21 @@ export default defineConfig({
},
],
},
{
text: 'Optimizing Transactions',
link: '/guide/optimizing-transactions/',
collapsed: true,
items: [
{
text: 'Optimistic Transactions',
link: '/guide/optimizing-transactions/optimistic-transactions',
},
{
text: 'Optimistic Contract Calls',
link: '/guide/optimizing-transactions/optimistic-contract-calls',
},
],
},
{
text: 'Encoding',
link: '/guide/encoding/',
Expand Down
4 changes: 1 addition & 3 deletions apps/docs/src/guide/encoding/snippets/working-with-bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,12 @@ const encodedU256 = u256Coder.encode(255);
// #region working-with-bytes-2
const booleanCoder = new BooleanCoder();
const encodedTrue = booleanCoder.encode(true);

const encodedFalse = booleanCoder.encode(false);

// #endregion working-with-bytes-2

// #region working-with-bytes-3
const stringCoder = new StringCoder(5);
const encoded = stringCoder.encode('hello');
const encodedString = stringCoder.encode('hello');
// #endregion working-with-bytes-3

// #region working-with-bytes-4
Expand Down
16 changes: 16 additions & 0 deletions apps/docs/src/guide/optimizing-transactions/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Optimizing Transactions

When submitting transactions using the SDK, the following actions are being performed:

- Fetching chain information to compute transaction data
- Retrieving the gas price for cost estimation
- Simulating the transaction to obtain missing or estimating transaction data
- Fetching funds for the transaction

Depending on how you are performing the transaction, all of the above may have been abstracted away underneath a single function call that is performing multiple calls to the network to retrieve necessary information. Which gives the appearance of slowness for users interacting with your application.

This can be mitigated by optimistically building the transaction before your user submits the transaction. Pre-preparation of the transaction can speed increases for your users of **~2x**.

Check out the following guides on implementing optimistic transaction building:
- [Optimistic Transactions](./optimistic-transactions)
- [Optimistic Contract Calls](./optimistic-contract-calls)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Optimistic Contract Calls

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Optimistic Transactions

Imagine we have an application that allows users to transfer funds between accounts.

On the frontend, we'd have a button that would allow the user to submit a transfer to a specified address.

```tsx
<Input
placeholder="Enter recipient address"
value={recipientAddress}
onChange={(e) => setRecipientAddress(e.target.value)}
/>
<Button onClick={() => onTransferPressed(recipientAddress)}>Transfer</Button>
```

This would likely have the following handler function:

<<< @./snippets/optimistic-transactions-before.ts#main{ts:line-numbers}

Under the hood, the `transfer` call is making multiple calls to the network to both simulate and fund the transaction, then submitting it. This may give the appearance of slowness for users interacting with your application.

This process can be optimized by optimistically building the transaction on page load, like so:

<<< @./snippets/optimistic-transactions-after.ts#main{ts:line-numbers}

> [!NOTE]
> Any change to the underlying transaction will require re-estimation and re-funding of the transaction. Otherwise the transaction could increase in size and therefore cost, causing the transaction to fail.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// #region main
import type { Account } from 'fuels';
import { ScriptTransactionRequest, Address, Provider, Wallet, bn } from 'fuels';

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

const { info } = console;

let provider: Provider;
let sender: Account;
let request: ScriptTransactionRequest;

// This is a generic page load function which should be called
// as soon as the user lands on the page
async function onPageLoad() {
// Initialize the provider and sender
provider = await Provider.create(LOCAL_NETWORK_URL);
sender = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
// Create and prepare the transaction request
request = new ScriptTransactionRequest();
// Estimate and fund the transaction with enough resources to cover
// both the transfer and the gas
const txCost = await sender.getTransactionCost(request, {
quantities: [
{
assetId: provider.getBaseAssetId(),
amount: bn(1_000_000),
},
],
});
await sender.fund(request, txCost);
}

async function onTransferPressed(recipientAddress: string) {
// When the user presses the transfer button, we add the output
// to the transaction request
request.addCoinOutput(
Address.fromString(recipientAddress),
1_000_000,
provider.getBaseAssetId()
);
// And submit the transaction, ensuring that the dependencies are
// not re-estimated and making redundant calls to the network
const transaction = await sender.sendTransaction(request, {
estimateTxDependencies: false,
});
info(`Transaction ID Submitted: ${transaction.id}`);
const result = await transaction.waitForResult();
info(`Transaction ID Successful: ${result.id}`);
}
// #endregion main

await onPageLoad();
await onTransferPressed(Wallet.generate().address.toString());
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// #region main
import { Provider, Wallet } from 'fuels';

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

const { info } = console;

async function onTransferPressed(recipientAddress: string) {
// Initialize the provider and sender
const provider = await Provider.create(LOCAL_NETWORK_URL);
const sender = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
// Calling the transfer function will create the transaction,
// and then perform multiple network requests to fund, simulate and submit
const transaction = await sender.transfer(recipientAddress, 1_000_000);
info(`Transaction ID Submitted: ${transaction.id}`);
const result = await transaction.waitForResult();
info(`Transaction ID Successful: ${result.id}`);
}
// #endregion main

await onTransferPressed(Wallet.generate().address.toString());

0 comments on commit 2da9c34

Please sign in to comment.