diff --git a/.changeset/six-waves-search.md b/.changeset/six-waves-search.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/six-waves-search.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/apps/docs/.vitepress/config.ts b/apps/docs/.vitepress/config.ts index f1a007accd1..c5fdc32ee7c 100644 --- a/apps/docs/.vitepress/config.ts +++ b/apps/docs/.vitepress/config.ts @@ -195,6 +195,10 @@ export default defineConfig({ text: 'Methods', link: '/guide/contracts/methods', }, + { + text: 'Optimising Contract Calls', + link: '/guide/contracts/optimising-contract-calls', + }, { text: 'Call Parameters', link: '/guide/contracts/call-parameters', diff --git a/apps/docs/spell-check-custom-words.txt b/apps/docs/spell-check-custom-words.txt index aa3ebc175d7..ecadeff3085 100644 --- a/apps/docs/spell-check-custom-words.txt +++ b/apps/docs/spell-check-custom-words.txt @@ -181,6 +181,8 @@ Macbook macOS MacOS mainnet +memoize +memoized mempool merkle Merkle @@ -229,6 +231,7 @@ relayer relayers repo repos +reprepare reuploaded rhs RPC @@ -345,4 +348,4 @@ Workspaces WSL XOR XORs -YAML \ No newline at end of file +YAML diff --git a/apps/docs/src/guide/contracts/optimising-contract-calls.md b/apps/docs/src/guide/contracts/optimising-contract-calls.md new file mode 100644 index 00000000000..fcaf897413a --- /dev/null +++ b/apps/docs/src/guide/contracts/optimising-contract-calls.md @@ -0,0 +1,106 @@ +# Optimizing Contract Calls + +When you call a contract function via the SDK, it makes two essential network requests: + +1. **Preparing the transaction**: This involves creating the transaction request, fetching dependencies for it and funding it properly. + +2. **Sending the transaction**: This involves sending the transaction to the network and waiting for it to be confirmed. + +The below flowchart shows this entire process: + +![Transaction Lifecycle in the SDK without prefetching](../../public/txdep1.png) + +The SDK will prepare the contract call _after_ the user has submitted the transaction at the application level. This is so the transaction is funded in it's finalised state. However this makes the chain feel slower than it actually is as we are making two network requests. + +This can be mitigated by preparing the contract call _before_ the user submits the transaction. If the transaction is prepared beforehand, the SDK only has to send the transaction to the network and wait for it to be confirmed. This reflects the actual speed of the chain to the user. + +You can experience this yourself by trying out this [demo](https://fuel-wallet-prefetch-experiment-75ug.vercel.app/). + +![Transaction Lifecycle in the SDK with prefetching](../../public/txdep2.png) + +Because of the massive performance gains, we recommend this strategy for all contract calls. + +## Recommended Implementation + +> [!Note] This is an example for React, but the same logic can be applied to any framework. + +We recommend creating a `usePrepareContractCall` hook: + +```tsx +import { FunctionInvocationScope, ScriptTransactionRequest } from "fuels"; +import { useEffect, useState, useCallback, useRef } from "react"; + +export const usePrepareContractCall = (fn?: FunctionInvocationScope) => { + const [preparedTxReq, setPreparedTxReq] = + useState(); + const fnRef = useRef(fn); + + useEffect(() => { + if (fn && fn !== fnRef.current) { + fnRef.current = fn; + (async () => { + const txReq = await fn.fundWithRequiredCoins(); + setPreparedTxReq(txReq); + })(); + } + }, [fn]); + + const reprepareTxReq = useCallback(async () => { + if (!fnRef.current) { + return; + } + const txReq = await fnRef.current.fundWithRequiredCoins(); + setPreparedTxReq(txReq); + }, []); + + return { + preparedTxReq, + reprepareTxReq, + }; +}; +``` + +This hook will prepare the transaction request for your contract call beforehand, and you can use the `reprepareTxReq` function to reprepare the transaction request if needed. + +You can use this hook in your UI logic like this: + +```tsx +function YourPage() { + // It is important to memoize the function call object. + const incrementFunction = useMemo(() => { + if (!contract || !wallet) return undefined; + return contract.functions.increment_counter(amount); + }, [contract, wallet, amount]); + + const { preparedTxReq, reprepareTxReq } = + usePrepareContractCall(incrementFunction); + + const onIncrementPressed = async () => { + if (preparedTxReq) { + // Use the prepared transaction request if it is available. Much faster. + await wallet.sendTransaction(preparedTxReq); + } else { + // Fallback to the regular call if the transaction request is not available. + await contract.functions.increment_counter(1).call(); + } + + /* + * Reprepare the transaction request since the user may want to increment again. + * This is important, since the old `preparedTxReq` will not be valid anymore + * because it contains UTXOs that have been used among other things. + * + * You *must* re-prepare any prepared transaction requests whenever + * the user does any transaction. + */ + await reprepareTxReq(); + }; +} +``` + +You can view the full code for this example [here](https://github.com/Dhaiwat10/fuel-wallet-prefetch-experiment/blob/main/src/components/Contract.tsx). + +## Important Things to Note + +- You _must_ re-prepare any prepared transaction requests whenever the user does any transaction. This is because the prepared transaction request will contain UTXOs that have been used among other things, and will therefore not be valid anymore. + +- You _must_ memoize the function call object. This is because the function call object is used to prepare the transaction request, and if it is not memoized, the function call object will be recreated on every render, and the transaction request will not be prepared correctly. diff --git a/apps/docs/src/public/txdep1.png b/apps/docs/src/public/txdep1.png new file mode 100644 index 00000000000..823c461c1c4 Binary files /dev/null and b/apps/docs/src/public/txdep1.png differ diff --git a/apps/docs/src/public/txdep2.png b/apps/docs/src/public/txdep2.png new file mode 100644 index 00000000000..0739192b07c Binary files /dev/null and b/apps/docs/src/public/txdep2.png differ