Swap dex - open back end

hi there jusr wondering how to open the back end on the swap dex many thanks

also if you can charge a commission on the swaps

also i have check the code in the swap.js buit still getting the stop sign when entering amount

Hi, what tutorial are you following?

I used the /dexstarter but then used the /dexfinal

All apis are the one installed

Node.js v18.16.0
PS C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback> node index.js
Listening for API Calls
C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\common-evm-utils\lib\dataTypes\EvmAddress\EvmAddress.js:50
throw new common_core_1.CoreError({
^

MoralisError [Moralis SDK Core Error]: [C0005] Invalid address provided
at EvmAddress.parse (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\common-evm-utils\lib\dataTypes\EvmAddress\EvmAddress.js:50:19)
at new EvmAddress (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\common-evm-utils\lib\dataTypes\EvmAddress\EvmAddress.js:18:34)
at EvmAddress.create (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\common-evm-utils\lib\dataTypes\EvmAddress\EvmAddress.js:46:16)
at Object.getRequestUrlParams (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\common-evm-utils\lib\operations\token\getTokenPriceOperation.js:38:41)
at OperationRequestBuilder.prepareUrl (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\api-utils\lib\resolvers2\OperationRequestBuilder.js:15:40)
at OperationResolver. (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\api-utils\lib\resolvers2\OperationResolver.js:58:50)
at step (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\api-utils\lib\resolvers2\OperationResolver.js:33:23)
at Object.next (C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\api-utils\lib\ at C:\Users\Dell\Documents\dex\dexFinal\dexfinal\dexback\node_modules@moralisweb3\api-utils\lib\resolvers2\OperationResolver.js:8:71
at new Promise () {
isMoralisError: true,
code: ‘C0005’,
details: undefined,
[cause]: undefined

getting this error when trying to listen with the api and it isnt opening the local3001/tokenPrice

gives me this error in the terminal when i request the page

const express = require(“express”);

const Moralis = require(“moralis”).default;

const app = express();

const cors = require(“cors”);

require(“dotenv”).config();

const port = 3001;

app.use(cors());

app.use(express.json());

app.get("/tokenPrice", async (req, res) => {

const {query} = req;

const responseOne = await Moralis.EvmApi.token.getTokenPrice({

address: query.addressOne

})

const responseTwo = await Moralis.EvmApi.token.getTokenPrice({

address: query.addressTwo

})

const usdPrices = {

tokenOne: responseOne.raw.usdPrice,

tokenTwo: responseTwo.raw.usdPrice,

ratio: responseOne.raw.usdPrice/responseTwo.raw.usdPrice

}

return res.status(200).json({});

});

Moralis.start({

apiKey: process.env.MORALIS_KEY,

}).then(() => {

app.listen(port, () => {

console.log(`Listening for API Calls`);

});

});

Object.defineProperty(exports, “__esModule”, { value: true });

exports.getTokenPriceOperation = void 0;

var common_core_1 = require("@moralisweb3/common-core");

var dataTypes_1 = require("…/…/dataTypes");

var EvmChainResolver_1 = require("…/…/EvmChainResolver");

/** Get the token price denominated in the blockchains native token and USD. */

exports.getTokenPriceOperation = {

var dataTypes_1 = require("…/…/dataTypes");

giving me this AS A PROBLEM

Hi @Dippydoge

This error here means then the address param is sent correctly to the backend API request. So address value is invalid.

Please try adding some console.log on your front end and backend code to debug further where the error is happening.

coulod you explain how to do this

On backend, you have to use console.log(query) inside the /tokenPrice endpoint.
And on the frontend check the code where you are calling the backend /tokenPrice route and add console.log for the params which you are passing to the backend.

To answer the question about the logo, you will have to find where we use the moralis logo image inside the code and swap it with your image

brill thats done now i need to add some params for fee collection please could you aduve me where to add them

referrerAddress string referrer’s address
fee number this percentage of fromTokenAddress token amount will be sent to referrerAddress, the rest will be used as input for a swap

min: 0; max: 3; default: 0
example to set a fee to 1.5%: &fee=1.5|

import React, { useState, useEffect } from “react”;

import { Input, Popover, Radio, Modal, message } from “antd”;

import {

ArrowDownOutlined,

DownOutlined,

SettingOutlined,

} from “@ant-design/icons”;

import tokenList from “…/tokenList.json”;

import axios from “axios”;

import { useSendTransaction, useWaitForTransaction } from “wagmi”;

function Swap(props) {

const { address, isConnected } = props;

const [messageApi, contextHolder] = message.useMessage();

const [slippage, setSlippage] = useState(2.5);

const [tokenOneAmount, setTokenOneAmount] = useState(null);

const [tokenTwoAmount, setTokenTwoAmount] = useState(null);

const [tokenOne, setTokenOne] = useState(tokenList[0]);

const [tokenTwo, setTokenTwo] = useState(tokenList[1]);

const [isOpen, setIsOpen] = useState(false);

const [changeToken, setChangeToken] = useState(1);

const [prices, setPrices] = useState(null);

const [txDetails, setTxDetails] = useState({

to:null,

data: null,

value: null,

});

const {data, sendTransaction} = useSendTransaction({

request: {

  from: address,

  to: String(txDetails.to),

  data: String(txDetails.data),

  value: String(txDetails.value),

}

})

const { isLoading, isSuccess } = useWaitForTransaction({

hash: data?.hash,

})

function handleSlippageChange(e) {

setSlippage(e.target.value);

}

function changeAmount(e) {

setTokenOneAmount(e.target.value);

if(e.target.value && prices){

  setTokenTwoAmount((e.target.value * prices.ratio).toFixed(2))

}else{

  setTokenTwoAmount(null);

}

}

function switchTokens() {

setPrices(null);

setTokenOneAmount(null);

setTokenTwoAmount(null);

const one = tokenOne;

const two = tokenTwo;

setTokenOne(two);

setTokenTwo(one);

fetchPrices(two.address, one.address);

}

function openModal(asset) {

setChangeToken(asset);

setIsOpen(true);

}

function modifyToken(i){

setPrices(null);

setTokenOneAmount(null);

setTokenTwoAmount(null);

if (changeToken === 1) {

  setTokenOne(tokenList[i]);

  fetchPrices(tokenList[i].address, tokenTwo.address)

} else {

  setTokenTwo(tokenList[i]);

  fetchPrices(tokenOne.address, tokenList[i].address)

}

setIsOpen(false);

}

async function fetchPrices(one, two){

  const res = await axios.get(`http://localhost:3001/tokenPrice`, {

    params: {addressOne: one, addressTwo: two}

  })

 

  setPrices(res.data)

}

async function fetchDexSwap(){

const allowance = await axios.get(`https://api.1inch.io/v5.0/1/approve/allowance?tokenAddress=${tokenOne.address}&walletAddress=${address}`)



if(allowance.data.allowance === "0"){

  const approve = await axios.get(`https://api.1inch.io/v5.0/1/approve/transaction?tokenAddress=${tokenOne.address}`)

  setTxDetails(approve.data);

  console.log("not approved")

  return

}

const tx = await axios.get(

  `https://api.1inch.io/v5.0/1/swap?fromTokenAddress=${tokenOne.address}&toTokenAddress=${tokenTwo.address}&amount=${tokenOneAmount.padEnd(tokenOne.decimals+tokenOneAmount.length, '0')}&fromAddress=${address}&slippage=${slippage}`

)

let decimals = Number(`1E${tokenTwo.decimals}`)

setTokenTwoAmount((Number(tx.data.toTokenAmount)/decimals).toFixed(2));

setTxDetails(tx.data.tx);

}

useEffect(()=>{

fetchPrices(tokenList[0].address, tokenList[1].address)

}, [])

useEffect(()=>{

  if(txDetails.to && isConnected){

    sendTransaction();

  }

}, [txDetails])

useEffect(()=>{

messageApi.destroy();

if(isLoading){

  messageApi.open({

    type: 'loading',

    content: 'Transaction is Pending...',

    duration: 0,

  })

}    

},[isLoading])

useEffect(()=>{

messageApi.destroy();

if(isSuccess){

  messageApi.open({

    type: 'success',

    content: 'Transaction Successful',

    duration: 1.5,

  })

}else if(txDetails.to){

  messageApi.open({

    type: 'error',

    content: 'Transaction Failed',

    duration: 1.50,

  })

}

},[isSuccess])

const settings = (

<>

  <div>Slippage Tolerance</div>

  <div>

    <Radio.Group value={slippage} onChange={handleSlippageChange}>

      <Radio.Button value={0.5}>0.5%</Radio.Button>

      <Radio.Button value={2.5}>2.5%</Radio.Button>

      <Radio.Button value={5}>5.0%</Radio.Button>

    </Radio.Group>

  </div>

</>

);

return (

<>

  {contextHolder}

  <Modal

    open={isOpen}

    footer={null}

    onCancel={() => setIsOpen(false)}

    title="Select a token"

  >

    <div className="modalContent">

      {tokenList?.map((e, i) => {

        return (

          <div

            className="tokenChoice"

            key={i}

            onClick={() => modifyToken(i)}

          >

            <img src={e.img} alt={e.ticker} className="tokenLogo" />

            <div className="tokenChoiceNames">

              <div className="tokenName">{e.name}</div>

              <div className="tokenTicker">{e.ticker}</div>

            </div>

          </div>

        );

      })}

    </div>

  </Modal>

  <div className="tradeBox">

    <div className="tradeBoxHeader">

      <h4>Swap</h4>

      <Popover

        content={settings}

        title="Settings"

        trigger="click"

        placement="bottomRight"

      >

        <SettingOutlined className="cog" />

      </Popover>

    </div>

    <div className="inputs">

      <Input

        placeholder="0"

        value={tokenOneAmount}

        onChange={changeAmount}

        disabled={!prices}

      />

      <Input placeholder="0" value={tokenTwoAmount} disabled={true} />

      <div className="switchButton" onClick={switchTokens}>

        <ArrowDownOutlined className="switchArrow" />

      </div>

      <div className="assetOne" onClick={() => openModal(1)}>

        <img src={tokenOne.img} alt="assetOneLogo" className="assetLogo" />

        {tokenOne.ticker}

        <DownOutlined />

      </div>

      <div className="assetTwo" onClick={() => openModal(2)}>

        <img src={tokenTwo.img} alt="assetOneLogo" className="assetLogo" />

        {tokenTwo.ticker}

        <DownOutlined />

      </div>

    </div>

    <div className="swapButton" disabled={!tokenOneAmount || !isConnected} onClick={fetchDexSwap}>Swap</div>

  </div>

</>

);

}

export default Swap;

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.