# 
Building A Chain Selector For AirSwap

By [starrdev](https://paragraph.com/@starrdev) · 2023-06-09

---

My Introduction to AirSwap
--------------------------

My introduction to AirSwap dates back to 2017 during the ICO boom. The project's resilience and its part in the Consensys ecosystem piqued my interest. Encouraged by AirSwap's open-source philosophy, I considered contributing to its growth.

![](https://storage.googleapis.com/papyrus_images/b8e0127d9954e08caceb72e1e98ebfaf1e533fd0ffa0c8a071bca6212ed2f59c.png)

As a software enthusiast, my path led me to front-end development. The allure of instant feedback and the real-time reflection of JavaScript code sparked my interest in this field. For this reason, I joined as a front-end developer.

Understanding AirSwap
=====================

AirSwap's primary product is a decentralized exchange (DEX) allowing for peer-to-peer swaps. Its unique model circumvents common issues such as slippage and front-running, typically associated with fully on-chain exchanges like UniSwap. The platform's ability to facilitate trades against institutional market makers adds to its appeal. Recently, AirSwap also launched a white-labelled NFT marketplace.

![How AirSwap works](https://storage.googleapis.com/papyrus_images/881d605b52989bc67a7f1053781edd0b8c55381b861b970bb70ff51bdb3a0350.webp)

How AirSwap works

Why AirSwap?
============

Before AirSwap, I was with RaidGuild, building apps in startup type of environments. Seeking a new challenge on a larger scale led me to AirSwap. With a substantial user base, a robust treasury, and a stimulating community, AirSwap became my chosen destination.

![](https://storage.googleapis.com/papyrus_images/247666b47ce588808399aacff7c1d42e84cd0a69062c4ed7b43e418198cd7016.png)

Acclimating to AirSwap
======================

Exploring the Codebase of AirSwap
---------------------------------

Comprehending AirSwap's extensive codebase was an initial hurdle. A week of rigorous code perusal helped me understand the structure of its components. The process involved meticulous code scrutiny, peer consultations, and leveraging tools like ChatGPT and StackOverflow. Also diving deep into its documentations and reading its smart contract code was important for understanding what was happening.

The New Feature: Network Selector
=================================

Web3's interoperability, enabling apps to function across different blockchains, gives users the power to choose their preferred blockchain. Given that AirSwap's smart contracts are written in Solidity, they can be deployed on any EVM-compatible chain.

![](https://storage.googleapis.com/papyrus_images/a06997db419cedc17931e7428ffc21e5fc4c4a5a6caf38807b18eb4d32d96b01.png)

Multiple Chains, One Selector
-----------------------------

The ChainSelectionPopover and ChainSelector components are the feature's core. The ChainSelector button reveals a popover listing user-selectable chains.

Here are key code snippets and explanations illustrating the feature's core functionality:

    import addEthereumChain from "../../../helpers/addEthereumChain";
    import switchToChain from "../../../helpers/switchToChain";
    
    const addAndSwitchToEthereumChain = async (chainId: number) => {
      const chainNotAddedCode = 4902;
    
      await switchToChain(chainId).catch((error: any) => {
        if (error.code === chainNotAddedCode) {
          addEthereumChain(chainId);
        }
      });
    };
    
    export default addAndSwitchToEthereumChain;
    

![Each of these buttons with different chains has the \`addAndSwitchToEthereumChain\` under the hood](https://storage.googleapis.com/papyrus_images/4b7a44519778d07d1ab673b3937404f667715d11c02c5a9f44104f13190d36d3.png)

Each of these buttons with different chains has the \\\`addAndSwitchToEthereumChain\\\` under the hood

`addAndSwitchToEthereumChain` function: This function is designed to either switch the user to a specified chain or, if the chain hasn't been added to their MetaMask wallet, add it. If the chain switch fails with a specific error code (indicating the chain hasn't been added), it triggers the addition of the chain.

    import { CHAIN_PARAMS } from "../constants/supportedNetworks";
    
    // https://eips.ethereum.org/EIPS/eip-3085
    
    const addEthereumChain = (chainId: number): Promise<null> => {
      return window.ethereum.request({
        method: "wallet_addEthereumChain",
        params: [
          {
            chainId: `0x${CHAIN_PARAMS[chainId].chainId.toString(16)}`,
            rpcUrls: CHAIN_PARAMS[chainId].rpcUrls,
            chainName: CHAIN_PARAMS[chainId].chainName,
          },
        ],
      });
    };
    
    export default addEthereumChain;
    

![The \`wallet_addEthereumChain\` method will bring up this prompt if a user doesn't have the network added on MetaMask already](https://storage.googleapis.com/papyrus_images/90e51f076ef279ed913fc2276b6641dfcfde99ff22ac591fd464dffd68354c31.png)

The \\\`wallet\_addEthereumChain\\\` method will bring up this prompt if a user doesn't have the network added on MetaMask already

`addEthereumChain` function: This function adds a specified chain to the user's MetaMask wallet. The function uses the `wallet_addEthereumChain` method from the Ethereum Provider API to add the chain and requires parameters such as `chainId`, `rpcUrls`, and `chainName`. These details are fetched from `CHAIN_PARAMS` constant, which presumably contains all the necessary information about the supported networks.

    import nativeCurrency from "../
    
    constants/nativeCurrency";
    
    const switchToChain = (chainId = 1): Promise<null> => {
      return window.ethereum.request({
        method: "wallet_switchEthereumChain",
        params: [
          {
            chainId: `0x${nativeCurrency[chainId].chainId.toString(16)}`,
          },
        ],
      });
    };
    
    export default switchToChain;
    

![The \`wallet_switchEthereumChain\` Method will open this prompt when switching networks](https://storage.googleapis.com/papyrus_images/f491e2473b455913393746a8269f5852a2f3f8b189f06a6db0aa68cde7e801b6.png)

The \\\`wallet\_switchEthereumChain\\\` Method will open this prompt when switching networks

`switchToChain` function: This function switches the currently active chain in the MetaMask wallet to a specified chain. The function uses the `wallet_switchEthereumChain` method from the Ethereum Provider API to switch chains. The `chainId` parameter is used to specify which chain to switch to.

Styling the Network Selector
============================

AirSwap employs React Styled-Components for styling. These are CSS-in-JS tools that enable traditional CSS writing in JavaScript files. In our codebase, these Styled-Components are imported into other components, creating a structured, maintainable, and reusable styling scheme. This modular architecture enhances code maintainability and improves the development workflow.

![](https://storage.googleapis.com/papyrus_images/bdc5fe46b4e0044d37332c7748cfdfc3f72e380e920f38dabf8d28a3796cfb85.png)

Making the Feature Mobile Responsive
====================================

Ensuring mobile responsiveness is critical in today's digital age. AirSwap follows a "mobile-first" design approach, which means we design for the smallest screen first, then progressively enhance the design for larger screens.

To ensure mobile responsiveness, we used CSS breakpoints. These are points where a website's content responds to provide the user with the best possible layout. By using CSS breakpoints, we managed to define different styles for different devices according to their screen size. This ensured that our new feature looked good and functioned correctly across all devices, maintaining the usability and overall aesthetic.

![Side-by-side comparison of desktop vs. mobile design. (Desktop is left, mobile is right)](https://storage.googleapis.com/papyrus_images/b96caad646f81a777d55a1361437516ac4b231e20b24957c84dcbbf01871359a.png)

Side-by-side comparison of desktop vs. mobile design. (Desktop is left, mobile is right)

Conclusion
==========

Contributing to AirSwap has been a profoundly educational journey into the realm of decentralized finance (DeFi). The opportunity to delve into its documentation and smart contracts has provided me with invaluable insights and learning experiences.

While my contributions thus far have focused primarily on front-end development, I'm enthusiastic about expanding my role as I enhance my Solidity skills. The prospect of contributing to smart contract work excites me, as it opens a new avenue of impact and learning.

One aspect of open-source work that truly appeals to me is its transparency. Having my contributions publicly displayed, and my name now associated with the AirSwap project, is a source of pride and motivation.

Looking forward, my excitement to contribute to AirSwap goes beyond its core DEX product. I anticipate lending my skills and efforts to further enhance the platform, fostering innovation, and bolstering user experiences across the board. The journey thus far has been enriching, and I am enthusiastic about the opportunities that lie ahead.

---

*Originally published on [starrdev](https://paragraph.com/@starrdev/building-a-chain-selector-for-airswap)*
