Add/Import cusotm token on dex

Good day,
I would like to know how to add/import custom token on dex,

The token already added on bsc network
and already selling on pancakeswap but it need to be import the contract address
so it will show the token symbol. I want to create my own dex where i can also import token address.

What you mean by your own dex?

i want to create same like this site
https://app.uniswap.org/#/swap

ok maybe my question
how that work when you want to add other token so you can import on your own dex site
pls. see screenshot

how can i make a search field function and import token function when you search token within a network ex. BSC network

ok, so you want to add a custom token to 1Inch

what is the token address? I don’t know exactly how it is done, but it may be possible to do it

i see
i think by using search function to search token within the network
ex. this contract address that run on etheruem network:

name: saitama
address: 0x8b3192f5eebd8579568a2ed41e6feb402f93f73f

it’s already displaying on 1inch exchange but you need to search for that name

you can manually push needed token objects to the supportedTokens list

1 Like

you can manually push needed token objects to the supportedTokens list

may i know how exactly i will do it?

is this also what you mean under the text below
is it also possible to preload token i want the user see on the exchange once they visit the dex website page?

ex.
from: bnb
to: saitama -<-- i want this to be a default token display

1 Like

hey @dcoderk. So theres two ways you could go bout this Im. you could do a more crude way where the user needs to know the address of the token before hand and if they do they can add it to the dex.

This i know is probably not what you rlooking for as it doesnt involve querying an API of existing tokens. but i will explain that method below (although it will be more progrmatic and you maybe be able to achieve something with less work through morlaiis). This first way could be a good way to add your own custom tokens that arent gonna be listed on an API, especially if you developing locally. You could add the following function sin your dex contract

import "../node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract Dex {

    ......
    .....
    struct Token {
        
        string ticker;
        address tokenAddress;
    }

    modifier tokenExists(string memory ticker) {
        
        require(tokenMapping[ticker].tokenAddress != address(0), "token does not exixts");
        
        _;
    }
    
    function addToken(string memory ticker, address _tokenAddress) public onlyowners {
        
        for (uint i = 0; i < tokenList.length; i++) {
            
            require(keccak256(bytes(tokenList[i])) != keccak256(bytes(ticker)), "cannot add duplicate tokens");
        }
        
        require(keccak256(bytes(ERC20(_tokenAddress).symbol())) == keccak256(bytes(ticker)));
        
        tokenMapping[ticker] = Token(ticker, _tokenAddress);
        
        tokenList.push(ticker);
        
        emit tokenAdded(msg.sender, ticker, _tokenAddress, block.timestamp);
    }


function getTokenList() public view returns(string[] memory) {
        
        return tokenList;
    }
}

so you could create a token struct which has the address of your custom token and the ticker of it aswell. Then in the addToken() function you can add a custom token using the ticker and the address. But we have to be careful. a user could provide the right address but the wrong ticker so we need to handle this. The first check just makes sure duplicate tokens arent being added. The reason im using keccak256 here is because you cannot directly compare strings in soldiity. You could get over this by changimng the ticker type in your struct to bytes32 but i prever having it as a string then we can get around the string comparison problem by hashing the string and comparing the hashes.

Note how we import the ERC20 interface. We use this to make sure that they ticker the user is passing in is equal to the specified ticker of the token defined in the actual token contract. Once we do this we know that the user has inputted the correct tickerr for the address provided. Then we can instiate the token instance and push the ticker to the list of supported tokens for the dex.

Fetch from API through search bar
Now this approach is only for custom tokens. Im not sure if morallis has any functionality to allow you to append this to some database in your font end which you could do so you could query it there but if you really wanted to you could set up your own implementation this through mongoDB or something

Thats one approach for custom tokens. But this does not use any API and requires the user knows the token information before hand. Really this is for custom tokens. If you wanted to make a search bar toke search alreading exisiting tokens in some API then if your using react you could use somethong like the following. Note that i am taking this code from an application i made previous so you may have to fiddle with it to get it to work for your exact use case but its the structure that might help you. We can use react useState and useEffect to query an api from a search bar and each time the text in the search bar cahnges we can update the state and rerender an this will give you the result you want.

Ok so there is gonna be three files here and ill explain them but im not sure how used you are to react. So the first file is going to be our serach bar component. This component will be responsible for allowing the suser to search a token in a search bar and rerender the page each time the search term changes. Consider the code below

import React, { useState, useEffect } from "react";
import { Wrapper, Content } from "./SearchBar.styles";

const SearchBar = ({ setSearchTerm }) => {

    const [state, setState] = useState("");
    
    useEffect(() => {
        
        const timer = setTimeout(() => {

            setSearchTerm(state);
        }, 500);

        return () => clearTimeout(timer);

    }, [setSearchTerm, state])
    
    return (
        <Wrapper>
            <Content>
                <input type="text" placeholder="Search-Token" onChange={event => setState(event.currentTarget.value)} value={state} />
                
            </Content>
        </Wrapper>
    );
};

export default SearchBar;

so first things first we import react. We are going to need useState and useEffect to handle our rendering each time the user changes the search field. Note here that i import a Wrapper and Content. These are just styled components i made there only for css ill show that file at the bottom as its not important here.

we then create a component call searchBar. this component takes in a search term that the user types into the search bar. We set the inital state to an empty string because the user will not have typed anything initially.

I then use a useEffect() that will rerender the page 500 ms after the user changes the text in the search bar. Use a 500ms deylay or otherwise the page will rerender instantly on change which does not look nice

I then return my styled components. These are just for the structuring but you can think of the token search bar as an input field. Whenever the text in the input field changes (which we mionitor through the onChange event specified in the input filed we update or serach term state to the current value thats in the search bar.

Now that we have this component written we can go back to whatever you main index.js file is and put it all together

import React,  { useState, useEffect } from "react";
import SearchBar from "./SearchBar";

const initialSate = {
    results: [],
};

const TokenSearchComponent = () => {

    const [searchTerm, setSearchTerm] = useState("");
    const [state, setState] = useState(initialSate);
    const [isLoadingMore, setIsLoadingMore] = useState(false);

    console.log(searchTerm);
    const fetchTokens = async(searchTerm = "") => {

        try {

            setIsLoadingMore(true);

//you will havr to write this function yourslef. You could do some in a helper.js file no react needed
            const tokens = await TOKENAPI.fetchTokens(searchTerm);

            //now set state
            setState(prev => ({

                ...tokens,
                results:
                    [...tokens.results]
            }))
        } catch (err) {

            console.log(err)
        }
        setIsLoadingMore(false);
    }

    // //initial render
    useEffect(() => {

        console.log("grabbing from API")
        setState(initialSate)
        fetchTokens(searchTerm)
    }, [searchTerm]);
    console.log(state)
    
    return (
        <>
            <SearchBar setSearchTerm={setSearchTerm} /> 
        </>  
    );  
}

export default TokenSearchComponent;

Ok so this file is going to use our search bar component to use the search term we provide to fetch tokens for some API maybe the one Inch one for example.We again import react etc and also our search bar component. I define the inital state to an empty aray called resutls which will store the tokens. In the actual tokenSearch component We set the initial state to an empty string again and not here i have amde a loading state that you could use to set up a loading spinner inbetween API querys but its not really nessecary if you want to keep things as simple as possible. you should ideally also error handle by creating an error state.

But after i initialise the states i create a function call fecth token. I f you wanted to could use this as a custom hook to make this file read cleaner but for the purposes here its fine. This function will take in the search term and it will use it to fetch data from whatever API you want to fetch tokens from. Note that the line of code

const tokens = await TOKENAPI.fetchMovies(searchTerm);

is just something i made up here and you will have to configure this to be specific to how you would fecth token data really but im just using like this to show you the format and structure of how you could go about creating this dynamic search bar. So you query the api using the search term and when you finally get the results you can destructure them out using the es6 spread operstor as such and set them to the results array like i have done.

Once this is done just setLoading to false because we now have the tokens and are not awating results. WE then use a useEffect for the initial render where whch changes the initial state and here we also call our fetch token function so that each time the seraxh term changes we recall the fetch token fucntion.

I then just return the searchBar component above which takes in the search term as a prop. Theres one last file which will be app.js and this file you will just specify this main component above

import React from 'react';
import TokenSearchComponent from "./components/TokenSearchComponent"

const App = () => (
    
         <TokenSearchComponent />
         
);


export default App;

Lastly is the styles for the Wrapper and Content

import styled from "styled-components";

export const Wrapper = styled.div`

`;

export const Content = styled.div`
`;

just fill out here whatever styles you need.

Ok so a few things here. I edited this code from a different application i made for search data from an API. Now your gonna have to know specifically how the oneInchAPI works so that you can fecth data acordingly and modified the above structure to fit your needs. The code above is only to provide a structure of one possible solution for your problem and i hope it doesnt seem to complex or hard to follow and hat it gives you at least an idea of how to solve your problem

2 Likes

Thank for the info and sample code. I will check on it and see how can i use it.
I guess need to use react to achieve that because i am only using vanilla js
Pls. check screenshot to see what I want to achieve when user visit the swap page
so fromtoken is a default token ie. bnb and totoken is our own token which already on the network just need to load it first

Exchange-PancakeSwap-13-213

1 Like

you should be able to do it with simple javascript too, I don’t know the exact code that you have to use

1 Like

i see
is there no one can help or guide me how to implement that interface?

yeah it would be more tedious to use the serach bar technique using vanillajs. but you could get around this by just fecthing the entire list of tokens form say oneinch and then displaying the in a table. So when you click your BNB or CAKE there on that button click you would fecth the tokens from the API and then loop through the array of token responses and append them to a table that appears also when you click the button. Perhaps something like this

async function loadTokenTable() {
    
    //you would need to write this function yourself to fetch token data
    var results = FetchTokensFromAPI().then(function(result) {
      for (let i = 0; i < result.length; i++) {
        
        table.innerHTML += `
            <tr "class="tablerow">

     //again you will need to know the specifics of the 1inch api to know what these
     //return values are actually called for the address and token name
                <td id=${ result[i].tokenAddress}>${result[i].tokenName}</td>
            </tr>`
      }
    })
}

const tokenDropdown = document.geElementByID(""token-dropdown);
tokenDropdown.onclick = loadTokenData

You would need to make a lot of modifications to the above sample. Furstly the function that i say FetchTokensFromAPI() is something i made up and you would need to write this yourself to query the 1inch api to get the tokens. But after this functions finishes ideally the result would be the token list then you can use this token list to loop trhrough and dynamically populate a HTML table with the token names. Again i stress that you will need to make lot sof modications to the above as im just wrinting this out of my head.

Other What you can do here is also set the id of each table element to the token address. that way you can make an onliclck even so that when you click a certain table row, you will have access to the address of the token etc. By doing this you could use something like e.target.id on your table to realise this and get the address information onclick that is if you need it

note that im just grasping at many ideas here without detailled implementation because id have to actually set up a code editor and testing but hopefully it s enough to give you an idea.

Note one problem with this approach is dynamic HTML tables dissapear on page load. So preferabley what you could do is use local storage to prevent this or else on page load fecth the token data first so that you will always have the data to load the table when a user clicks the button shown in your snapshot above

ah ok thank you for more info
i will try working on this dex using react
as it easy to query/search api from react

1 Like

I passed my own token info into the trade.

onClick={() => {
              setToken({address: "0xc66cb95e814c10194313096c2dd660e77cf9b2de",
              decimals: 9,
              logoURI: "/logo.png",
              name: "JammaBeans",
              symbol: "Jamma"});
              onClose();
              }}

it seems to load the price and trade info.

however it fails when I try to do the trade. No metamask popup.

useInchDex.js:60

  1. {statusCode: 400, error: ‘Bad Request’, description: ‘cannot estimate’, meta: Array(0), requestId: ‘943a85b8-4f21-4955-a51a-67f98ce4e134’}

  2. description: “cannot estimate”

  3. error: “Bad Request”

  4. meta: Array(0)

1. length: 0
2. [[Prototype]]: Array(0)
  1. requestId: “943a85b8-4f21-4955-a51a-67f98ce4e134”
  2. statusCode: 400
  3. [[Prototype]]: Object
2 Likes

nice
that’s how i want to implement it
i think you need to fetch/call it from api
it cannot be hard coded as the token already on the network

1 Like

did you have enough funds in the account for that transaction? gas estimation may fail when there is not enough funds, but I don’t know if it is really related to that error

I have enough funds

It fails here in the useInchDex hook

await doSwap(params)
      .then((receipt) => {
        if (receipt.statusCode !== 400) {
          alert("Swap Complete");
        }
        console.log(receipt);
      })
      .catch((e) => alert(e.message));
  }

Im thinking it could be issue with coin slippage or maybe there is a list of supported tokens in the plugin that it rechecks, but could be anything.

Got it !!!

it was a slippage issue

useUnchDex.js

async function doSwap(params) {
    return await Moralis.Plugins.oneInch.swap({
      chain: params.chain, // The blockchain you want to use (eth/bsc/polygon)
      fromTokenAddress: params.fromToken.address, // The token you want to swap
      toTokenAddress: params.toToken.address, // The token you want to receive
      amount: Moralis.Units.Token(
        params.fromAmount,
        params.fromToken.decimals
      ).toString(),
      fromAddress: walletAddress, // Your wallet address
      slippage: 12,    //   I had to update here
    });
  }
3 Likes

amazing! We should add the slippage changer in the boilerplate I guess. Will work on it :muscle:

1 Like