How Biconomy Paymaster Works - Sponsor gas or pay in any token
September 18, 2023
Navigating gas fees has been one of the biggest Web3 UX painpoint. In the past, we at Biconomy have solved this with meta-transactions. We enabled 300+ dApps to sponsor 41 million gasless transactions of thousands of users. Now, with ERC-4337, we have taken this to the next level with Paymasters. This blog dives deeper into why Paymasters & gas abstraction play such a key role, and how they work technically in the ERC-4337 account abstraction flow.
The 2 ways of abstracting Gas complexities
Gas fees have consistently posed a significant hurdle to both newcomers and established users within the web3 ecosystem, hampering the overall user experience. This issue becomes particularly evident when users are forced to leave an application to procure native tokens for covering transaction gas fees. Even users well-versed in web3 with sufficient token balances can encounter this inconvenience due to the essential requirement of native tokens for gas fees on EVM chains. Addressing this fundamental issue is paramount for improving the user experience.
The emergence of ERC4337 has ushered in a standardized protocol, offering solutions to enhance user experience, with gas abstraction being a prominent one. Within the context of the ERC4337 specification, a paymaster contract assumes the role of a participant responsible for shouldering gas expenses on behalf of users.
Within this framework, dApps and wallets possess the capacity to establish a range of paymasters. Presently, Biconomy's paymaster service provides two distinct modes of gas sponsorship:
1. Conditional gas sponsorship
2. Empowering users to employ any token for covering gas expenses
Why Biconomy is better than other paymaster services
Issues with current Paymaster services
In the market, there are products that offer gas abstraction through either of the aforementioned approaches. Nevertheless, these solutions come with certain issues:
1. A business might establish specific conditions under which it commits to sponsoring gas on behalf of users. However, if the condition check for sponsorship fails, users will find themselves once again tasked with the burden of acquiring native tokens to cover gas fees.
2. It may not be practical for a business to consistently cover gas fees across all application interactions. Consequently, users may enjoy seamless transactions in certain instances but still find themselves grappling with gas fees for the majority of their transactions.
3. Utilizing both sponsorship and token paymaster functionalities necessitates the management of two distinct paymaster instances. Developers must be proficient in understanding where to integrate each paymaster, potentially introducing a heightened margin for error and diminishing the overall developer experience.
Biconomy's novel Hybrid Paymaster approach
The Biconomy Paymaster solution effectively resolves these issues through a novel approach and can be easily configured through the Biconomy dashboard. This interface offers the flexibility to specify conditions for applying gas sponsorship. Additionally, the service simplifies the process of enabling users to cover gas expenses using their preferred tokens. Whether you choose to implement gas sponsorship or token-based payments, you only require a single instance of the paymaster for each blockchain network, streamlining the setup process.
The Biconomy paymaster service is also designed to also serve as a hybrid solution, blending gas sponsorship with the flexibility for users to cover gas fees using any token of their choice. This is achieved by allowing developers to configure policies within the Biconomy dashboard to determine when to sponsor gas fees. Should these sponsorship conditions not be met, a graceful fallback is enacted, permitting users to pay for gas using their preferred token.
Consider an example of a game that has seamlessly integrated the Biconomy paymaster service. Suppose this game incorporates a staking mechanism, and the developer has set up sponsorship conditions in the dashboard as follows:
1. Sponsoring gas for all staking transactions.
2. Sponsoring gas for the first 5 transactions per user for all other types of transactions.
In this scenario, once a user has surpassed their initial 5 transactions, they still retain the ability to cover gas costs using the dApp token or any other token at their disposal. This hybrid gas abstraction mechanism ensures a more comprehensive gas solution, ultimately enhancing the overall user experience (UX).
Advantages of Biconomy Paymaster
This distinctive approach sets Biconomy's paymaster service apart in the market, offering several distinct advantages:
Efficient Integration: Traditionally, if a dApp developer desired various forms of gas sponsorship (either by dApp or user in ERC20 tokens), they would need to set up multiple paymaster instances, leading to repetitive integrations. Biconomy's paymaster service streamlines this process by enabling a single setup and integration to accommodate a range of sponsorship options as needed.
Enhanced User Experience: In scenarios where sponsorship conditions are unmet, the usual recourse is to have users pay for gas using the native token. However, if users lack the native token, it could disrupt their experience as they exit the app to acquire the required token. Biconomy's solution circumvents this inconvenience, as users are given the option to cover gas fees using tokens they already possess.
Simplified Fallback Handling: Should sponsorship conditions fail, developers would generally need to implement a fallback mechanism themselves, directing users to pay in a token of their preference. Biconomy's paymaster service eliminates this concern by autonomously managing fallback processes.
Future-Proof Design: Biconomy's visionary approach extends to future developments. As plans include incorporating various paymaster types, the goal is to achieve this expansion through a unified integration point where feasible.
Gas Optimized: Unlike other services that combine sponsorship and token paymaster mechanisms within a single contract, Biconomy segregates these concerns into distinct paymasters: the Sponsorship Paymaster and the Token Paymaster. This segregation translates to highly efficient gas consumption during paymaster operations.
Comprehensive Token Support: The Biconomy paymaster service is poised to support approximately 500 tokens, facilitating widespread access for users. This is intended to prevent gas-related hindrances and ensure users can seamlessly engage with your application. Moreover, Biconomy's future ambition involves dynamically supporting any token backed by substantial liquidity on popular DEXs.
In summary, the Biconomy paymaster service's innovative hybrid model, encompassing gas sponsorship and flexible token-based gas payments, not only addresses current needs efficiently but also lays a foundation for anticipated enhancements and extensive token support in the future.
How to set up a Paymaster
To create a paymaster and acquire its associated PaymasterURL, simply access the Biconomy Dashboard and proceed to add a new paymaster as outlined below. After successfully configuring the paymaster, you will gain access to a paymasterURL that can be seamlessly integrated into your code for immediate use.
To introduce gas sponsorship into your platform, an essential additional step is to establish what we term a "gas tank" and generate a unique paymasterID for it. While we commonly refer to it as a "gas tank" for simplicity, it's essentially a deposit into the VerifyingPaymaster contract. Importantly, this deposit operates on a fully non-custodial basis, granting you the freedom to withdraw the funds whenever you deem necessary.
We maintain a comprehensive mapping of each dApp associated with a distinctive paymasterID directly within the contract. The paymasterID essentially functions as an identifier for your project. This mapping tracks the balances associated with your designated paymasterID, ensuring transparency and clarity throughout the gas sponsorship process.
mapping(address => uint256) public paymasterIdBalances;
When you access the Gas Tank page, it's imperative to take note of the wallet you employ during the initial setup. This address of this account will be your paymasterID. This specific wallet is granted the exclusive authorization to initiate fund withdrawals from the designated gas tank. Once you opt to proceed by clicking the "I understand and set up gas tank" button, your wallet will prompt you to provide a signature. It's important to be aware that this action does incur certain gas costs.
Off-chain Flow for processing paymaster request
Paymaster APIs can be now used to enable sponsorship within your dApp. Rather than managing multiple distinct paymaster URLs to distinguish paymaster types, this functionality is unlocked by inclusion of a parameter known as "MODE" within the API request body.
The purpose of this "MODE" parameter is to offer a clear directive to the system regarding the desired transaction handling within your dApp. It signifes whether your dApp aims to facilitate sponsored transactions for its users or intends to empower users to make payments using ERC20 tokens.
Upon receiving a request, the Biconomy Paymaster service initially examines the specified sponsorship MODE.
1. In case the MODE is set to "SPONSORED," : the Biconomy Paymaster Service follows a series of steps. It begins by decoding the call data to determine if the interaction is taking place with a contract that's been pre-whitelisted on the dashboard against the API Key. Simultaneously, the service verifies whether the developer-set limitations for the specific smart account or paymaster are not surpassed. If all these conditions are met and the paymaster holds sufficient gas balance, the service generates a suitable paymasterAndData. This data is subsequently signed by a signer affiliated with Biconomy. This signature plays a role in validation later within the on-chain process.
2. If the chosen MODE is "ERC20," the Biconomy Paymaster Service operates in a different manner. In this case, the service anticipates a selection of tokens to be included along with the request. These tokens signify those which the user potentially possesses in their wallet, and the dApp recognizes them. The service's response typically provides calculated fee quotes in the denomination of the mentioned tokens, along with the corresponding gas limits. However, this holds true only if at least one of the tokens is supported by Biconomy. Should this not be the case, the response would instead feature fee quotes within the exhaustive array of tokens that Biconomy supports. Following this, the dApp presents these fee quotes to the user, who then chooses a preferred token for gas payment. Subsequently, the dApp transmits a new request to the Biconomy Paymaster Service, specifying the selected token. In return, the service provides a signed paymasterAndData, completing the userOp creation process.
3. When the request doesn't include a specified MODE, the hybrid mode comes into play. In this scenario, we typically anticipate receiving a partial userOp along with a collection of potential tokens for gas payment. The call data is decoded and scrutinized to determine eligibility for sponsorship, based on the conditions configured for the respective API Key. If the conditions are met, the outcome is a signed paymasterAndData. However, if the conditions aren't satisfied, the response entails gas fee quotes basis list of tokens provided in the request. Subsequently, the user can pick a token of their preference for covering gas costs. This token selection leads to the issuance of another signed paymasterAndData, thereby finalizing the userOp creation process.
What Happens To A Sponsored UserOp On Chain
The bundler upon receiving the request performs off-chain simulation, validation checks & bundles it into a handleOps transaction and sends it on chain. Based on the type of sponsorship that was signed by the Biconomy Paymaster Service, the flow of control either goes to the Sponsorship Paymaster or Token Paymaster like so.
When the userOp qualifies for gas sponsorship, the subsequent flow unfolds in the following manner:
1. The Bundler initiates by invoking the EntryPoint contract, submitting the bundled transaction.
2. The EntryPoint contract, in turn, triggers the execution of the "validateOp" function within the smart account specified by the sender of the userOp.
3. In cases where the userOp contains a "paymasterAndData" field, the process proceeds to invoke the "validation(validatePaymasterOp)" function within the relevant paymaster contract (in this scenario, the Sponsorship Paymaster). Upon successful validation of the signature and other checks, the Sponsorship Paymaster commits to using its stored deposit on EntryPoint to cover gas expenses for the user.
4. With the necessary validations complete, EntryPoint proceeds to request execution by triggering the "executeOp" method within the smart account.
5. The smart account, in turn, can trigger additional contract calls or perform fund transfers based on the provided call data, either to other contracts or externally owned accounts (EOAs).
6. To conclude, EntryPoint performs the final step by invoking the "postOp" function on the sponsorship paymaster, thereby granting the paymaster the opportunity to perform any supplementary accounting tasks that might be necessary.
What Happens To A UserOp On Chain when gas can be paid in ERC20 token
If the userOp meets the criteria for token-based gas sponsorship, the ensuing flow proceeds as outlined below:
1. The Bundler initiates the process by making a call to the EntryPoint contract, providing the bundled transaction.
2. The EntryPoint contract, in turn, triggers the "validateOp" function within the specified smart account associated with the sender of the userOp.
3. Should the userOp contain a "paymasterAndData" field, the procedure advances to invoke the "validation(validatePaymasterOp)" function within the relevant paymaster contract (Token Paymaster). This involves validating the signature and other checks. If successful, the Token Paymaster commits to utilizing its stored deposit on EntryPoint for covering the user's gas expenses.
4. With validations completed, EntryPoint proceeds to initiate execution by calling the "executeOp" method within the smart account.
5. For cases involving a Token Paymaster, an approval transaction must be batched with the call data. This transaction authorizes the Token Paymaster contract to withdraw ERC20 tokens from the user's smart account. This authorization is executed first.
6. The execution process with a Token Paymaster involves a minor divergence. It encompasses an internal call to "postOp." Initially, the smart account might trigger other contract calls or fund transfers based on the provided call data.
7. Following the internal execution, EntryPoint invokes the "postOp" function (within the context of "executeOp") on the Token Paymaster. This step enables the Token Paymaster to withdraw ERC20 tokens equivalent to the utilized gas fee from the user's smart account using "safeTransferFrom," while also facilitating additional accounting if necessary. If this "postOp" encounters an issue, the entire callData execution of that userOp is reverted. This safeguard prevents potential malicious user attacks, safeguarding the paymaster's interests.
8. If the "executeOp" proceeds smoothly, the second "postOp" isn't triggered. However, if "executeOp" reverts due to an error, the second "postOp" is activated. This empowers the Token Paymaster to withdraw the gas tokens used for the failed transaction from the user's smart account.
Use Cases Unlocked With Paymasters
User Onboarding and Adoption:
New users exploring decentralized applications might be discouraged by the initial complexity and cost of setting up a cryptocurrency wallet and paying gas fees. By offering gas sponsorship, you can attract more users to try your application without the hurdle of upfront costs. Allowing payments in any ERC20 tokens can encourage wider user adoption, especially for those who might not hold the native token.
Users can choose from a variety of ERC20 tokens they already own, enhancing their convenience and allowing them to utilize assets they are more comfortable with.
Payments is taking off as a prominent use case for web3 in general. Its best to then allow users to pay for gas fees in the token that they will pay in or even transfer. Easing gas fee payments could also be a boost initially to enable seamless payments, supporting use cases like content monetization, pay-per-use services, and in-game item purchases.
Incentive for Token Holders:
Token holders might be incentivized to hold specific tokens that offer advantages or discounts when used for gas payments, potentially driving demand.
Voting and Governance:
Decentralized autonomous organizations (DAOs) often require participants to vote on proposals or governance matters. Sponsoring gas fees or allowing users to pay in DAO tokens for voting transactions can encourage wider community participation and decision-making.
Marketplaces and NFT Platforms:
Gas fees can hinder the buying, selling, and trading of non-fungible tokens (NFTs) and digital assets on marketplaces. By allowing user to pay for gas in token he is transacting in, you can create a more user-friendly experience for your platform's users.
Staking and DeFi Participation:
In decentralized finance (DeFi) and staking protocols, users often need to interact with smart contracts by providing liquidity or staking tokens. Gas deducted along with token being staked can encourage broader participation in these activities, driving the growth of the DeFi ecosystem.
Paymasters are a game changer for Web3 UX with huge repurcurssions on how the next billion users will interact with decentralised applications. By making it easier for developers to abstract gas complexities with Biconomy Paymasters, dApps can start building tons of use cases for mainstream users.