Zyfi - A Deep Dive

Zyfi - A Deep Dive

Undestanding Gasless Transactions: A Comprehensive Introduction to Zyfi's Paymaster-as-a-Service

Warm welcome to my Zk Nation. In this article, I'll try to get you started with
Zyfi - Paymaster as a service. We will cover from the introduction to Zyfi to setting up Zyfi for your project and get you introduced to the partners that are moving to the world of Account abstraction with the help ZkSync and Zyfi.

Let's get started 💪

Introduction to Zyfi 🤓

Zyfi is a Paymaster-as-a-Service that represents a significant innovation in the realm of blockchain technology by providing a robust Gas Abstraction Layer specifically designed for ZK-Sync native Account Abstraction.
As a free, open-source, and audited Paymasters-As-A-Service, Zyfi aims to streamline the user experience for decentralized applications (dApps) by eliminating the need for users to manage gas fees directly and worrying about having native tokens to interact with the Dapp. This abstraction not only enhances usability but also empowers developers to focus on building innovative solutions without the complexities associated with Paymaster and transactions infra.

How Zyfi Simplifies Gas Abstraction on ZK-Sync

The Concept of Gas Abstraction

Gas abstraction refers to the separation of transaction fees from the user experience. Traditionally, users must hold Ether (ETH) or (ZK) to pay for gas fees, which can be a barrier to entry for many potential users. Zyfi addresses this challenge by allowing developers to implement gasless transactions, where the application itself can cover the transaction costs.

Zyfi’s Paymasters-As-A-Service

Lets now understand how Zyfi’s Paymasters-As-A-Service framework simplifies the implementation of gas abstraction by providing developers with:

  1. Easy Integration: Zyfi offers a straightforward API that developers can use to integrate gasless transactions into their dApps without needing to understand the underlying complexities of gas management.

  2. Customizable Payment Options: Developers can configure how gas fees are handled, including options for subsidizing fees, allowing users to pay in tokens other than ZK/ETH, or even implementing loyalty programs that reward users for engaging with the application. This solves a lot of blockchain UX problem for developers, so they can focus more on implementing their innovative solutions.

  3. Audited and Secure: As an open-source solution, Zyfi is subject to community scrutiny and has undergone thorough audits to ensure security and reliability, giving developers peace of mind when integrating the service into their applications.

Benefits of Using Zyfi for Developers and Users

For Developers

  • Reduced Development Time: By leveraging Zyfi’s pre-built solutions like paymaster API, developers can save significant time and resources that would otherwise be spent on creating their own gas abstraction mechanisms.

  • Enhanced User Engagement: With gasless transactions, developers can attract a broader audience, including those who may be hesitant to interact with blockchain applications due to gas fees.

  • Flexibility and Control: Zyfi allows developers to customize their gas abstraction strategies, enabling them to create unique user experiences that can differentiate their applications in a competitive market.

For Users

  • Lower Barriers to Entry: Users can engage with dApps without needing to acquire ETH for gas fees, making it easier for newcomers to enter the blockchain space.

  • Improved User Experience: The elimination of gas fees simplifies the transaction process, allowing users to focus on the application’s functionality rather than the complexities of managing transaction costs.

  • Faster Transactions: With Zyfi operating on ZK-Sync, users benefit from quicker transaction confirmations, enhancing the overall experience and usability of dApps.


But as we all know🤨, EIP 4337 was already a significant move towards Account abstraction, that brought the concepts of Bundlers, Paymasters, Entrypoint, UserOp and so on for EVM based networks. What's Zyfi is doing different for ZkSync?

To answer these questions and Zyfi innovative solution to tackle the challenges for existing problems with AA stack, lets dive a bit more on what is the difference between ZkSync where account abstraction is enabled on protocol level and other EVM based L2 networks.

Difference between Account abstraction on ZkSync and other L2/L1 EVM networks

As we all know with ERC 4337, all Ethereum based networks can now enable Account abstraction for their users using a suit of AA products. This works by switching from traditional wallets and EOAs to Smart wallets and smart accounts that can send UserOps via bundlers to entrypoint contracts that then add them in the next blockchain blocks. Here's a small diagram by me to help you understand how it works:

Let me explain above ERC 4337 architecture

  1. Users: On the left side, there are multiple users represented, indicating that this system handles operations from multiple users.

  2. UserOp Mempool: This is a pool where user operations (UserOps) are collected. It acts as a temporary storage for user requests before they're processed further.

  3. User Operations: These are individual transactions or operations requested by users. Multiple user operations are shown within the mempool.

  4. Bundler: This component takes multiple user operations from the mempool and combines them into a single bundle transaction.

  5. Bundle Transaction: This is the result of the bundler's work - a single transaction that contains multiple user operations.

  6. Ethereum Block: On the top right, an Ethereum block is shown. It contains the bundle transaction along with other transactions, representing how the bundled operations are eventually included in the Ethereum blockchain.

The flow appears to work as follows:

  1. Users submit their operations.

  2. These operations are collected in the UserOp Mempool.

  3. The Bundler takes multiple operations from the mempool.

  4. The Bundler creates a Bundle Transaction containing these operations.

  5. The Bundle Transaction is then included in an Ethereum block along with other transactions.

So when we apply this ERC 4337 architcture that comprises of smart accounts, users ops with traditonal transaction mempool architecture, we get something like this:

Here we can see that, although we have account abstraction infrastrcuture, most of the accounts that are EOAs can't access this infrastructure. Infact, even the smart accounts require gas to be deployed, resulting in costs for the user or the app and provides bad UX for already EOA using users.

This is where ZkSync native account abstraction comes in place. As ZkSync have already AA enabled on protocol level, accounts in zkSync Era can initiate smart transactions, like an EOA, but can also have arbitrary logic implemented in them, like a smart contract.

You can understand it much better by below flowchart:

As you can see, rather than having two separate mempools for EOAs and Smart Accounts, ZkSync native abstrcation enables every transaction to go through the same unified mempool.

You can see, in the right down side of the above flowchart, when the transactions are trying to enter the Entrypoint contract to become a part of blockchain, at that moment Paymaster comes place to cover the gas fees structure for these mempool transaction to get added in the blockchain.

And this is where Zyfi comes in place. 😼

How Zyfi Works

At the core of Zyfi's functionality lies its Paymasters-As-A-Service framework. This service allows developers to easily integrate gasless transactions into their applications through a simple API. Lets see how a simple transaction with Zyfi works:

When a user initiates a transaction, the Zyfi API retrieves the necessary transaction data from the front-end and adds the paymaster parameters, including the fee taken in the ERC-20 token that will be used to pay for the gas costs.The user then signs the transaction data, granting the Zyfi paymaster the ERC-20 fee allowance and authorization to execute the transaction. Once the signed transaction data is received by the paymaster, it validates the user's signature and checks if the ERC-20 fee is sufficient to cover the gas costs. If everything checks out, the paymaster executes the transaction, paying the gas fees in ETH on behalf of the user.

The whole process can be simplified by the above workflow diagram from Zyfi team.

Interaction of Zyfi with ZK-Sync

Zyfi's seamless integration with ZK-Sync is what enables it to offer gasless transactions. ZK-Sync's native Account Abstraction feature allows EOAs (Externally Owned Accounts) to send transactions without the need for gas tokens, as long as they have enough of the specified ERC-20 token to cover the gas fees.When a user initiates a transaction through a Zyfi-integrated application, the transaction is processed off-chain by ZK-Sync. ZK-Sync bundles multiple transactions into a single proof and periodically submits it to the Ethereum mainnet for final settlement. This process significantly reduces the computational burden on the mainnet, allowing for faster and cheaper transactions.

Security Measures by Zyfi

Zyfi places a strong emphasis on security to ensure the safe and reliable operation of its service. As an open-source solution, Zyfi's code is subject to community scrutiny and has undergone thorough audits to identify and address potential vulnerabilities.Moreover, the Zyfi paymaster operates in a completely trustless manner. The paymaster never holds user funds or has direct access to their wallets. Instead, it relies on the user's signed transaction data to validate the ERC-20 fee allowance and execute the transaction. This design ensures that even if the paymaster were to be compromised, user funds would remain safe.

Zyfi paymaster service uses the Signature Based paymaster, that also solves the problem of sybil defense against bad actors.

Benefits of Using ZyFi for a DApp

So we got to understand how Zyfi works, but there are still many paymaster platforms available, whats the point of using Zyfi?

These questions may be coming in your mind right now, so let's get into the benefits of using Zyfi for you dapp.

1. Enhanced User Experience

ZyFi allows users to interact with dApps without needing to hold ETH for gas fees, thereby eliminating a common barrier to entry.

2. Increased User Adoption

By removing the friction associated with gas fees, dApps that integrate ZyFi can attract a larger user base. The ability to transact without worrying about gas costs can lead to higher transaction volumes and increased daily active users.

3. Simplified Development Process

ZyFi’s Paymasters-As-A-Service model simplifies the integration of gas abstraction into dApps. Developers can implement ZyFi with just a single API call, significantly reducing development time and complexity.

4. Cost Savings

By leveraging ZyFi, dApps can reduce operational costs associated with gas fees. Developers can choose to sponsor gas fees for users or implement custom sponsorship models, potentially leading to cost savings for both the application and its users.

5. Customization and Flexibility

ZyFi provides developers with the flexibility to customize how gas fees are handled. They can decide to cover part or all of the gas costs or allow users to pay with various ERC-20 tokens.


Still no satified with the benefits of using Zyfi with your dapp, let's get into some of the Zyfi stats from the Dune Zyfi usage dashboard:

  1. Zyfi have processed more than 1.3 million sponsored transaction till now as well as more than 19k transactions in a single day. Zyfi is made for scalability.

  2. Zyfi cummulative users have jumped to more than 175k+ with more than 14k monthly users.

  3. Zyfi have saved more than $66k+ gas costs for users 💪

Case Studies of Existing DApps Using ZyFi

Several dApps have already integrated ZyFi, showcasing its positive impact on development and user engagement:

1. ZeroLend

ZeroLend, a decentralized lending platform, integrated ZyFi to enhance user experience by allowing users to borrow and lend assets without worrying about gas fees. This integration has led to an increase in transaction volume and user retention, as users appreciate the seamless experience of not needing to manage ETH for gas.

2. Gravita

Gravita, a collateralized debt position (CDP) platform, has also benefited from ZyFi's gas abstraction. By enabling users to interact with the platform using any ERC-20 token such as Gravita Protocol native token GRAI for gas fees, Gravita has seen a significant uptick in user engagement and transaction frequency, as users find it easier to manage their assets without the hassle of gas costs.

3. zkMarkets

As an NFT marketplace, zkMarkets has leveraged ZyFi to provide a gasless trading experience. This has not only improved the user experience but also attracted more traders to the platform, contributing to increased liquidity and transaction volumes.


There a lot more project that are using Zyfi paymaster service right now. You can keep a tap on Zyfi blog posts to learn about new projects getting onboarded.

Practical Tutorial for integrating Zyfi

Its time to cook. Follow the tutorial below, to get started with building and integrating your dapp with Zyfi. 😎

Lets get started. This tutorial will guide you through integrating Zyfi's paymaster service into your decentralized application (Dapp). We'll cover both the ERC20 Paymaster and Sponsored Paymaster options.

Prerequisites

  • Basic knowledge of JavaScript and blockchain development

  • A Dapp project set up with Ethers.js or a similar library

  • Access to Zyfi API (for Sponsored Paymaster, you'll need an API key)

Step 1: Choose Your Paymaster Type

Decide whether you want to use the ERC20 Paymaster or Sponsored Paymaster:

  • ERC20 Paymaster: Users pay gas fees in ERC20 tokens

  • Sponsored Paymaster: Your protocol can sponsor a portion of the gas fees

Step 2: Set Up the API Request

For ERC20 Paymaster:

const payload = {
  chainId: 324, // ZkSync Era Mainnet
  feeTokenAddress: "0x...", // ERC20 token address for gas payment
  txData: {
    from: "0x...",
    to: "0x...",
    data: "0x..."
  }
};

async function getERC20PaymasterQuote() {
  try {
    const response = await fetch('https://api.zyfi.org/api/erc20_paymaster/v1', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching ERC20 Paymaster quote:', error);
  }
}

For Sponsored Paymaster:

const payload = {
  chainId: 324, // ZkSync Era Mainnet
  feeTokenAddress: "0x...", // ERC20 token address for user's portion
  sponsorshipRatio: 50, // Percentage of fee to be sponsored (0-100)
  replayLimit: 5, // Optional, default is 5
  txData: {
    from: "0x...",
    to: "0x...",
    data: "0x..."
  }
};

async function getSponsoredPaymasterQuote() {
  try {
    const response = await fetch('https://api.zyfi.org/api/erc20_sponsored_paymaster/v1', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': '<Your-API-Key>'
      },
      body: JSON.stringify(payload),
    });
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching Sponsored Paymaster quote:', error);
  }
}

Step 3: Display Quote to User

After receiving the API response, extract and display relevant information:

function displayQuote(quoteData) {
  console.log(`Token Address: ${quoteData.tokenAddress}`);
  console.log(`Fee Amount: ${quoteData.feeTokenAmount} ${quoteData.tokenAddress}`);
  console.log(`Fee in USD: $${quoteData.feeUSD}`);
  console.log(`Expiration Time: ${new Date(quoteData.expirationTime * 1000)}`);

  if (quoteData.sponsorshipRatio) {
    console.log(`Sponsored Percentage: ${quoteData.sponsorshipRatio}%`);
  }

  // Display to user in your UI
}

Step 4: Execute the Transaction

Using the returned transaction data from the API:

import { Web3Provider } from "zksync-ethers";

async function executeTransaction(quoteData) {
  const provider = new Web3Provider(window.ethereum);
  const signer = provider.getSigner();

  try {
    const txHash = await signer.sendTransaction(quoteData.txData);
    console.log(`Transaction sent: ${txHash}`);
    return txHash;
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

Step 5: Putting it in use

Here's how you might use these functions in your Dapp:

async function handleTransaction(isSponsored = false) {
  let quoteData;

  if (isSponsored) {
    quoteData = await getSponsoredPaymasterQuote();
  } else {
    quoteData = await getERC20PaymasterQuote();
  }

  if (quoteData) {
    displayQuote(quoteData);

    // Ask user for confirmation (implement your own UI for this)
    if (userConfirms()) {
      const txHash = await executeTransaction(quoteData);
      // Handle successful transaction (e.g., show success message, update UI)
    }
  }
}

By following steps, you can easily integrate Zyfi with dapp, and start using Zyfi paymaster services for users. If you are still confused, you can always refer to the Zyfi docs.

Also, if you want to follow some advance tutorials, you can checkout this Zyfi team tutorial on Integrating multi-signer paymaster into you Dapp.


Comparison of Zyfi with other paymaster services

As the account abstraction space is taking over in the last couple years, we are seeing more infra products getting build for Account abstraction on different chains. If I take reference of some of the products in AA space we have:

  • ZyFi standing out with its flexibility in allowing users to pay gas fees with any ERC-20 token, making it particularly attractive for dApps on the zkSync network.

  • Alchemy offering robust developer tools and a strong support system, but primarily requires ETH for gas fees, which could limit user accessibility.

  • Pimlico and Biconomy also providing gasless transaction capabilities, but their integration processes and payment methods vary.

  • Candide focuses on smart contract wallets, which may appeal to a different audience compared to traditional wallets like Coinbase and Argent, which prioritize user experience and security.

  • StackUp and JiffyScan provide additional functionalities like wallet services with paymaster/bundlers and transaction tracking, enhancing the overall ecosystem for users and developers.

According to BundlerBear, Biconomy is the most successful paymaster in the market till date, and have covered more than $1 million+ gas costs, followed by Stackup, Pimlico, Alchemy and Coinbase.

Many of these paymaster services are not available on ZkSync yet, which is what makes Zyfi a unique solution catering for the needs of Zksync era.

Conclusion

I hope, you got to learn more about ZkSync, zyfi, paymasters as well as account abstraction. If you want to learn more, follow Zyfi on socials as well as join Zyfi community.

🌐Website
🐦X
🏘️Discord
📃Docs

I will see you later in the next article. Till then, make account abstraction grow.💪