### Install Biconomy SDK and Viem Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/README.md Installs the necessary Biconomy SDK package and Viem for blockchain interactions using the bun package manager. ```bash bun add @biconomy/account viem ``` -------------------------------- ### Define Session Rules (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Illustrates the creation of session rules, specifying conditions and reference values for transaction validation. The example shows how to define a rule for an 'equal' condition based on the smart account address. ```typescript /** * Rule * * https://docs.biconomy.io/Modules/abiSessionValidationModule#rules * * Rules define permissions for the args of an allowed method. With rules, you can precisely define what should be the args of the transaction that is allowed for a given Session. Every Rule works with a single static arg or a 32-byte chunk of the dynamic arg. * Since the ABI Encoding translates every static param into a 32-bytes word, even the shorter ones (like address or uint8), every Rule defines a desired relation (Condition) between n-th 32bytes word of the calldata and a reference Value (that is obviously a 32-bytes word as well). * So, when dApp is creating a _sessionKeyData to enable a session, it should convert every shorter static arg to a 32bytes word to match how it will be actually ABI encoded in the userOp.callData. * For the dynamic args, like bytes, every 32-bytes word of the calldata such as offset of the bytes arg, length of the bytes arg, and n-th 32-bytes word of the bytes arg can be controlled by a dedicated Rule. */ const rules: Rule = [ { /** * * offset * * https://docs.biconomy.io/Modules/abiSessionValidationModule#rules * * The offset in the ABI SVM contract helps locate the relevant data within the function call data, it serves as a reference point from which to start reading or extracting specific information required for validation. When processing function call data, particularly in low-level languages like Solidity assembly, it's necessary to locate where specific parameters or arguments are stored. The offset is used to calculate the starting position within the calldata where the desired data resides. Suppose we have a function call with multiple arguments passed as calldata. Each argument occupies a certain number of bytes, and the offset helps determine where each argument begins within the calldata. * Using the offset to Extract Data: In the contract, the offset is used to calculate the position within the calldata where specific parameters or arguments are located. Since every arg is a 32-bytes word, offsets are always multiplier of 32 (or of 0x20 in hex). * Let's see how the offset is applied to extract the to and value arguments of a transfer(address to, uint256 value) method: * - Extracting to Argument: The to argument is the first parameter of the transfer function, representing the recipient address. Every calldata starts with the 4-bytes method selector. However, the ABI SVM is adding the selector length itself, so for the first argument the offset will always be 0 (0x00); * - Extracting value Argument: The value argument is the second parameter of the transfer function, representing the amount of tokens to be transferred. To extract this argument, the offset for the value parameter would be calculated based on its position in the function calldata. Despite to is a 20-bytes address, in the solidity abi encoding it is always appended with zeroes to a 32-bytes word. So the offset for the second 32-bytes argument (which isthe value in our case) will be 32 (or 0x20 in hex). * * If you need to deal with dynamic-length arguments, such as bytes, please refer to this document https://docs.soliditylang.org/en/v0.8.24/abi-spec.html#function-selector-and-argument-encoding to learn more about how dynamic arguments are represented in the calldata and which offsets should be used to access them. */ offset: 0, /** * Conditions: * * 0 - Equal * 1 - Less than or equal * 2 - Less than * 3 - Greater than or equal * 4 - Greater than * 5 - Not equal */ condition: 0, /** The value to compare against */ referenceValue: smartAccountAddress, }, ]; ``` -------------------------------- ### Initialize Smart Account Client with Viem Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/INITIALISE_A_SMART_CONTRACT.md Demonstrates how to create a Biconomy smart account client using viem for signing and transaction handling. It requires a signer (ethers.JsonRpcSigner or viemWallet), a bundler URL, and a paymaster URL, typically retrieved from the Biconomy dashboard. ```typescript import { createSmartAccountClient } from "@biconomy/account"; import { createWalletClient, http, createPublicClient } from "viem"; import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; import { mainnet as chain } from "viem/chains"; const account = privateKeyToAccount(generatePrivateKey()); const signer = createWalletClient({ account, chain, transport: http() }); const smartAccount = await createSmartAccountClient({ signer, bundlerUrl, paymasterUrl, }); // Retrieve bundler and pymaster urls from dashboard ``` -------------------------------- ### Initialize Biconomy Smart Account Client (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Sets up a Biconomy smart account client using provided signer and URLs. It demonstrates how to retrieve the smart account address which is used later in defining session rules. ```typescript import { createSmartAccountClient, createSession, createSessionSmartAccountClient, Rule, Policy, } from "@biconomy/account"; import { createWalletClient, http, createPublicClient } from "viem"; import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; import { mainnet as chain } from "viem/chains"; const withSponsorship = { paymasterServiceData: { mode: PaymasterMode.SPONSORED }, }; const account = privateKeyToAccount(generatePrivateKey()); const signer = createWalletClient({ account, chain, transport: http() }); const smartAccount = await createSmartAccountClient({ signer, bundlerUrl, paymasterUrl, }); // Retrieve bundler and pymaster urls from dashboard const smartAccountAddress = await smartAccount.getAccountAddress(); ``` -------------------------------- ### Initialize Smart Account Client and Send Transaction Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/README.md Demonstrates how to create a Biconomy smart account client using a provided signer and Biconomy URLs. It then shows how to send a transaction and wait for its completion, extracting the transaction hash and success status. ```typescript import { createSmartAccountClient } from "@biconomy/account"; const smartAccount = await createSmartAccountClient({ signer: viemWalletOrEthersSigner, bundlerUrl: "", // From dashboard.biconomy.io paymasterUrl: "", // From dashboard.biconomy.io }); const { wait } = await smartAccount.sendTransaction({ to: "0x...", value: 1 }); const { receipt: { transactionHash }, success, } = await wait(); ``` -------------------------------- ### POST /smartAccountClient Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/INITIALISE_A_SMART_CONTRACT.md Initializes a smart account client. This client is used for signing user operations and sponsoring transactions. ```APIDOC ## POST /smartAccountClient ### Description Initializes a smart account client. This client is used for signing user operations and sponsoring transactions. ### Method POST ### Endpoint /smartAccountClient ### Parameters #### Request Body - **signer** (object) - Required - The signer object used for signing userOps. Can be ethers.JsonRpcSigner or a viemWallet. - **paymasterUrl** (string) - Optional - The URL for the paymaster, necessary for sponsoring transactions. Retrieved from the Biconomy dashboard. - **bundlerUrl** (string) - Optional - The URL for the bundler, used for sending transactions. Retrieved from the Biconomy dashboard. ### Request Example ```json { "signer": "viemWalletObject", "paymasterUrl": "https://dashboard.biconomy.io/your-paymaster-url", "bundlerUrl": "https://dashboard.biconomy.io/your-bundler-url" } ``` ### Response #### Success Response (200) - **smartAccountClient** (object) - The initialized smart account client object. #### Response Example ```json { "smartAccountClient": "smartAccountClientObject" } ``` ``` -------------------------------- ### Create and Execute Batch Session with Biconomy SDK Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_BATCH_SESSION.md Demonstrates the creation of a batch session using the Biconomy SDK, including defining session data for ERC20 transfers and ABI calls. It also shows how to execute batched transactions after session creation. ```typescript import { createSmartAccountClient, createSession, createSessionSmartAccountClient, Rule, PaymasterMode, Policy, } from "@biconomy/account"; import { createWalletClient, http, createPublicClient } from "viem"; import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; import { mainnet as chain } from "viem/chains"; const withSponsorship = { paymasterServiceData: { mode: PaymasterMode.SPONSORED }, }; const account = privateKeyToAccount(generatePrivateKey()); const signer = createWalletClient({ account, chain, transport: http() }); const smartAccount = await createSmartAccountClient({ signer, bundlerUrl, paymasterUrl, }); // Retrieve bundler and pymaster urls from dashboard const smartAccountAddress = await smartAccount.getAccountAddress(); // creates a store for the session, and saves the keys to it to be later retrieved const { sessionKeyAddress, sessionStorageClient } = await createSessionKeyEOA( smartAccount, chain ); const leaves: CreateSessionParams[] = [ createERC20SessionDatum({ interval: { validUntil: 0, validAfter: 0, }, sessionKeyAddress, sessionKeyData: encodeAbiParameters( [ { type: "address" }, { type: "address" }, { type: "address" }, { type: "uint256" }, ], [sessionKeyAddress, token, recipient, amount] ), }), createABISessionDatum({ interval: { validUntil: 0, validAfter: 0, }, sessionKeyAddress, contractAddress: nftAddress, functionSelector: "safeMint(address)", rules: [ { offset: 0, condition: 0, referenceValue: smartAccountAddress, }, ], valueLimit: 0n, }), ]; const { wait, session } = await createBatchSession( smartAccount, sessionStorageClient, leaves, withSponsorship ); const { receipt: { transactionHash }, success } = await wait(); const smartAccountWithSession = await createSessionSmartAccountClient( { accountAddress: smartAccountAddress, // Set the account address on behalf of the user bundlerUrl, paymasterUrl, chainId, }, "DEFAULT_STORE", // Storage client, full Session or smartAccount address if using default storage "BATCHED" ); const transferTx: Transaction = { to: token, data: encodeFunctionData({ abi: parseAbi(["function transfer(address _to, uint256 _value)"]), functionName: "transfer", args: [recipient, amount], }), }; const nftMintTx: Transaction = { to: nftAddress, data: encodeFunctionData({ abi: parseAbi(["function safeMint(address _to)"]), functionName: "safeMint", args: [smartAccountAddress], }), }; const txs = [nftMintTx, transferTx]; const leafIndexes = [1, 0]; // The order of the txs from the sessionBatch const { wait: sessionWait } = await smartAccountWithSession.sendTransaction( txs, withSponsorship, { leafIndex: leafIndexes }, ); const { success } = await sessionWait(); ``` -------------------------------- ### Send Sponsored Ether Transaction with Biconomy SDK (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/SEND_SOME_ETH_WITH_SPONSORSHIP.md Demonstrates sending a single Ether transaction with sponsorship using the Biconomy SDK and viem. It includes setting up the wallet client, creating a smart account, defining the transaction, and waiting for the sponsored transaction receipt. Requires bundler and paymaster URLs. ```typescript import { createSmartAccountClient } from "@biconomy/account"; import { createWalletClient, http, createPublicClient } from "viem"; import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; import { mainnet as chain } from "viem/chains"; const account = privateKeyToAccount(generatePrivateKey()); const signer = createWalletClient({ account, chain, transport: http() }); const smartAccount = await createSmartAccountClient({ signer, bundlerUrl, paymasterUrl, }); // Retrieve bundler and paymaster urls from dashboard const oneOrManyTx = { to: "0x...", value: 1 }; const { wait } = await smartAccount.sendTransaction(oneOrManyTx, { paymasterServiceData: { mode: PaymasterMode.SPONSORED, }, }); const { receipt: { transactionHash }, userOpHash, success, } = await wait(); ``` -------------------------------- ### Create Smart Account Client with Session Management (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Initializes a Biconomy smart account client, enabling session management. It requires essential configuration like account address, bundler URL, paymaster URL, and chain ID, and specifies a storage client for session data. ```typescript const smartAccountWithSession = await createSessionSmartAccountClient( { accountAddress: smartAccountAddress, // Set the account address on behalf of the user bundlerUrl, paymasterUrl, chainId, }, "DEFAULT_STORE" // Storage client, full Session or smartAccount address if using default storage ); ``` -------------------------------- ### Create Biconomy Session with Sponsored Transactions (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Initiates a Biconomy session for a smart account, applying a predefined policy. It configures the session to use sponsored transactions via the Paymaster Mode. ```typescript const { wait, session } = await createSession(smartAccount, policy, null, { paymasterServiceData: { mode: PaymasterMode.SPONSORED }, }); const { receipt: { transactionHash }, } = await wait(); ``` -------------------------------- ### Define Policy for Contract Method with Rules and Interval (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Defines a policy structure for a Biconomy session, specifying contract details, function selectors, rules, validity intervals, and value limits. This is typically used when setting up session permissions. ```typescript /** The policy is made up of a list of rules applied to the contract method with and interval */ const policy: Policy[] = [ { /** The address of the sessionKey upon which the policy is to be imparted. Can be optional if creating from scratch */ sessionKeyAddress, /** The address of the contract to be included in the policy */ contractAddress: nftAddress, /** The specific function selector from the contract to be included in the policy */ functionSelector: "safeMint(address)", /** The list of rules which make up the policy */ rules, /** The time interval within which the session is valid */ interval: { validUntil: 0, validAfter: 0, }, /** The maximum value that can be transferred in a single transaction */ valueLimit: 0n, }, ]; ``` -------------------------------- ### Send Sponsored Transaction for Token Minting (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/CREATE_AND_USE_A_SESSION.md Executes a token minting transaction using a Biconomy smart account client with an active session. It encodes the transaction data, specifies the recipient and function, and allows for sponsorship. ```typescript const { wait: mintWait } = await smartAccountWithSession.sendTransaction( { to: nftAddress, data: encodeFunctionData({ abi: parseAbi(["function safeMint(address _to)"]), functionName: "safeMint", args: [smartAccountAddress], }), }, withSponsorship, { leafIndex: "LAST_LEAF" }, ); const { success } = await mintWait(); ``` -------------------------------- ### Send Multi-Transaction with ERC20 Gas Payment (TypeScript) Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/SEND_A_MULTI_TX_AND_PAY_GAS_WITH_TOKEN.md This snippet shows how to send an array of transactions, pay for gas using a specified ERC20 token, and wait for the transaction receipt. It requires setting up a wallet client, a smart account client, and configuring the paymaster service data. ```typescript import { encodeFunctionData, parseAbi, createWalletClient, http, createPublicClient, } from "viem"; import { createSmartAccountClient } from "@biconomy/account"; import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; import { mainnet as chain } from "viem/chains"; const account = privateKeyToAccount(generatePrivateKey()); const signer = createWalletClient({ account, chain, transport: http() }); const smartAccount = await createSmartAccountClient({ signer, bundlerUrl, paymasterUrl, }); // Retrieve bundler and pymaster urls from dashboard const preferredToken = "0x747A4168DB14F57871fa8cda8B5455D8C2a8e90a"; // USDC const tx = { to: nftAddress, data: encodeFunctionData({ abi: parseAbi(["function safeMint(address to) public"]), functionName: "safeMint", args: ["0x..."], }), }; const buildUseropDto = { paymasterServiceData: { mode: PaymasterMode.ERC20, preferredToken, }, }; const { wait } = await smartAccount.sendTransaction( [tx, tx] /* Mint twice */, buildUseropDto ); const { receipt: { transactionHash }, userOpHash, success, } = await wait(); ``` -------------------------------- ### Send Multi Transaction and Pay Gas with Token Source: https://github.com/bcnmy/biconomy-client-sdk/blob/main/examples/SEND_A_MULTI_TX_AND_PAY_GAS_WITH_TOKEN.md This endpoint allows sending multiple transactions and specifies a preferred ERC20 token for gas payment. ```APIDOC ## POST /sendTransaction ### Description Sends multiple transactions and allows for paying gas fees using a specified ERC20 token. This is useful for batching operations and managing gas costs efficiently. ### Method POST ### Endpoint /sendTransaction ### Parameters #### Request Body - **txs** (Array) - Required - An array of transaction objects to be sent. - **buildUseropDto** (object) - Required - Options for building the user operation, including paymaster service data. - **paymasterServiceData** (object) - Required - Configuration for the paymaster service. - **mode** (string) - Required - The mode for the paymaster, e.g., `PaymasterMode.ERC20`. - **preferredToken** (string) - Required - The address of the ERC20 token to be used for gas payment. ### Request Example ```json { "txs": [ { "to": "0xNFTContractAddress", "data": "0xencodedFunctionData" }, { "to": "0xNFTContractAddress", "data": "0xencodedFunctionData" } ], "buildUseropDto": { "paymasterServiceData": { "mode": "ERC20", "preferredToken": "0xUSDCContractAddress" } } } ``` ### Response #### Success Response (200) - **wait** (function) - A function to wait for the transaction to be mined. - **receipt** (object) - The transaction receipt. - **transactionHash** (string) - The hash of the transaction. - **userOpHash** (string) - The hash of the user operation. - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "wait": async () => { return { receipt: { transactionHash: "0xTransactionHash" }, userOpHash: "0xUserOpHash", success: true }; } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.