Skip to content

Commit

Permalink
docs: optimistic predicates
Browse files Browse the repository at this point in the history
  • Loading branch information
danielbate committed Dec 31, 2024
1 parent f157187 commit 43fbfc7
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 0 deletions.
4 changes: 4 additions & 0 deletions apps/docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,10 @@ export default defineConfig({
text: 'Optimistic Contract Calls',
link: '/guide/optimizing-transactions/optimistic-contract-calls',
},
{
text: 'Optimistic Predicates',
link: '/guide/optimizing-transactions/optimistic-predicates',
},
],
},
{
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/src/guide/optimizing-transactions/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,7 @@ Depending on how you are performing the transaction, all of the above may have b
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)
- [Optimistic Predicates](./optimistic-predicates)
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Optimistic Predicates

Imagine we have an application that allows a user to transfer funds to another user given a validated predicate condition, here we'll use a pin number.

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

This would likely have the following handler function:

<<< @./snippets/optimistic-predicates-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.
>
> For predicates, the data passed to validate it could potentially alter the amount of gas the predicate consumes. This may mean we need to re-estimate and re-fund the transaction.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// #region main
import type { Account } from 'fuels';
import { Provider, Wallet, ScriptTransactionRequest, Address } from 'fuels';

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

const { info } = console;

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

// 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 wallet
provider = await Provider.create(LOCAL_NETWORK_URL);
sender = Wallet.fromPrivateKey(WALLET_PVT_KEY_2, provider);

// Instantiate the predicate and fund it
predicate = new ConfigurablePin({ provider });
const fundTx = await sender.transfer(
predicate.address,
500_000,
provider.getBaseAssetId()
);
await fundTx.waitForResult();

// Create a new transaction request and add the predicate resources
request = new ScriptTransactionRequest();
const resources = await predicate.getResourcesToSpend([
[100_000, provider.getBaseAssetId()],
]);
request.addResources(resources);

// Estimate and fund the transaction, including the predicate gas used
const txCost = await predicate.getTransactionCost(request);
request.updatePredicateGasUsed(txCost.estimatedPredicates);
request.gasLimit = txCost.gasUsed;
request.maxFee = txCost.maxFee;
await predicate.fund(request, txCost);
}

async function onTransferPressed(pin: number, recipientAddress: string) {
// When the user presses the transfer button, we add the output
// to the transaction request
request.addCoinOutput(
Address.fromString(recipientAddress),
10_000,
provider.getBaseAssetId()
);
// Then we must alter any existing predicate data that may have changed
const predicateWithData = new ConfigurablePin({ provider, data: [pin] });
const requestWithData =
predicateWithData.populateTransactionPredicateData(request);
// And submit the transaction, ensuring that the dependencies are
// not re-estimated and making redundant calls to the network
const transaction = await sender.sendTransaction(requestWithData, {
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(1337, Wallet.generate().address.toString());
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// #region main
import { Provider, Wallet } from 'fuels';

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

const { info } = console;

async function onTransferPressed(pin: number, recipientAddress: string) {
// Initialize the provider and sender
const provider = await Provider.create(LOCAL_NETWORK_URL);
const sender = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

// Instantiate the predicate and fund it
const predicate = new ConfigurablePin({ provider, data: [pin] });
const fundTx = await sender.transfer(
predicate.address,
500_000,
provider.getBaseAssetId()
);
await fundTx.waitForResult();

// Calling the transfer function will create the transaction,
// and then perform multiple network requests to fund, simulate and submit
const transaction = await predicate.transfer(recipientAddress, 10_000);
info(`Transaction ID Submitted: ${transaction.id}`);
const result = await transaction.waitForResult();
info(`Transaction ID Successful: ${result.id}`);
}
// #endregion main

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

0 comments on commit 43fbfc7

Please sign in to comment.