Gas Fees is being deducted but not swap is performed (Uniswap v3 router)

Gas Fees is being deducted but not swap is performed (Uniswap v3 router), wrote this code for swap exchange between usdc and dai in node js, the swap function is working but there is no exchange being taken place, althought the gas fees is being deducted

const ethers = require('ethers');
require('dotenv').config();
const express = require('express');
const ABI = require('./abi.json');
const ERC = require('./ERC20abi.json');
const PRIVATE_KEY = process.env.PRIVATE_KEY;

const provider = new ethers.JsonRpcProvider('https://base-mainnet.g.alchemy.com/v2/alcht_ECRFwRe1pH5sKP1FSBGo3SpLFVTXNS');
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

const routerAddress = "0xE592427A0AEce92De3Edee1F18E0157C05861564";

const routerABI = ABI;

const routerContract = new ethers.Contract(routerAddress, routerABI, wallet);

async function swapTokens(inputToken, outputToken, amountIn, slippage, recipient) {
    const amountInWei = ethers.parseUnits(amountIn, 6); // assuming USDC has 6 decimals
    const slippageTolerance = ethers.parseUnits(slippage, 2);

    const tokenContract = new ethers.Contract(inputToken, ERC, wallet);
    const approveTx = await tokenContract.approve(routerAddress, amountInWei);
    await approveTx.wait();

    const swapParams = {
        tokenIn: inputToken,
        tokenOut: outputToken,
        fee: 3000, 
        recipient: recipient,
        deadline: Math.floor(Date.now() / 1000) + 60 * 10, // 10 minutes from now
        amountIn: amountInWei,
        amountOutMinimum: 0,
        sqrtPriceLimitX96: 0
    };

    const tx = await routerContract.exactInputSingle(swapParams);
    console.log(`Transaction hash: ${tx.hash}`);
    await tx.wait();
    console.log('Swap complete');
}

async function checkBalance(address,) {
  try {
      // Get the wallet's public address
      const address = wallet.address;

      // Get the balance of the wallet in wei (smallest denomination)
      const balanceWei = await provider.getBalance(address);

      // Convert the balance to Ether (Base chain uses ETH-like denominations)
      const balanceEth = ethers.utils.formatEther(balanceWei);

      console.log(`Balance of ${address}: ${balanceEth} ETH`);
  } catch (error) {
      console.error('Error checking balance:', error);
  }
}

const app = express();
app.use(express.json());
app.post('/swap', async (req, res) => {
    const { inputToken, outputToken, amountIn, slippage, recipient } = req.body;
    try {
        await swapTokens(inputToken, outputToken, amountIn, slippage, recipient);
        res.status(200).send('Swap successful');
    } catch (error) {
        console.error(error);
        res.status(500).send('Swap failed');
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

the swap function is working but there is no exchange being taken place, althought the gas fees is being deducted

Bootstrap 5 Modal at input form accept only value “A, B, C or 0”

Triggered Input to perform Modal

<input class="btn btn-outline-dark w-100" data-bs-toggle="modal" data-bs-target="#updateEkskulModal" data-bs-cdcod="cdcod" data-bs-cdpts="cdpts" data-bs-cduid="cduid" data-bs-cdref="cdref" data-bs-cdsmt="cdsmt" type="button" value="cdpts"`>

Modal

<div class="modal-body">
<input class="form-control" maxlength="1" id="ekskulpts" name="ekskulpts" required style="text-transform:uppercase">
</div>

JS

<script>
    const cdptsModal = document.getElementById('updateEkskulModal')
    if (cdptsModal) {
      cdptsModal.addEventListener('show.bs.modal', event => {
        const button = event.relatedTarget
        const cdcod = button.getAttribute('data-bs-cdcod')
        const cduid = button.getAttribute('data-bs-cduid')
        const cdsub = button.getAttribute('data-bs-cdsub')
        const cdpts = button.getAttribute('data-bs-cdpts')
        const cdsmt = button.getAttribute('data-bs-cdsmt')
        $("#ekskulcod").val(cdcod);
        $("#ekskuluid").val(cduid);
        $("#ekskulsub").val(cdsub);
        $("#ekskulpts").val(cdpts);
        $("#ekskulsmt").val(cdsmt);
      })
    }
</script>

Bootstrap 5 input-form accept only value “A, B, C or 0” since JQuery is no longer used in BS 5 (Modal)

How to cache GraphQL response in Apollo Client?

I have a React app where I am using Apollo client to handle GraphQL queries and caching.

I have two GraphQL queries, one that fetches a whole menu and another that fetches top level menu sections.

I fetch the whole menu when I first load the app in an attempt to cache the menu data. I then call the query that fetches the menu top level sections which I would expect to fetch from the cache but for some reason the data is not available from the cache and must fetch from the network.

The first query that fetches the whole menu looks like this

query GetMenu(
  $menuId: ID
  $restaurantId: ID!
  $filter: MenuSectionFilterInput
) {
  getMenu(menuId: $menuId, restaurantId: $restaurantId) {
    id
    sections(filter: $filter) {
      ...Section
      sections {
        ...Section
      }
    }
  }
}

fragment Section on MenuSection {
  id
  items(restaurantId: $restaurantId) {
    ...Item
  }
}

The second query that fetches all the top level sections looks like this

query GetMenuSections($restaurantId: ID!, $getMenuFilter: MenuFilterInput) {
  getMenu(restaurantId: $restaurantId, filter: $getMenuFilter) {
    id
    sections {
      name
      id
    }
  }
}

Since the second query is run at a later stage than the first one, should the sections already be in the cache?

I am trying to run the following query with fetchPolicy: 'cache-only', which fails because the data isn’t in the cache. It passes if I allow it to fetch from network.

useQuery(GET_MENU_SECTIONS,
  {
    fetchPolicy: 'cache-only',
    variables: {
      restaurantId,
      getMenuFilter
    }
  }
);

Do the query args make a difference to how things get cached? Do both GetMenu and GetMenuSections need to have the same args in order for it to cache?

I don’t have any typePolicies set up in my Apollo Client that would override default caching policies. I did try to add a custom policy for getMenu but it didn’t work and shouldn’t even be necessary since both queries are querying for id fields which is what should get used for caching.

How do I make the GetMenuSections query use the already cached data?

ColumnDef Type error of “Type ‘AccessorKeyColumnDef’ is not assignable to type ‘ColumnDef’. in @tanstack/react-table

I am getting a TypeError of Type 'AccessorKeyColumnDef<Reservation, number>' is not assignable to type 'ColumnDef<Reservation>' while trying to create a column in @tanstack/react-table.

Here is my code:

type Reservation ={
 id: number
 shift: string
 quantity: number
}

const columnHelper = createColumnHelper<Reservation>()

// This is the area where the error comes up, when defining columns
const columns = useMemo<ColumnDef<Reservation>[]>(
        () => [
            columnHelper.accessor('id', {
                header: () => 'S/N',
                cell: info => info.getValue(),
            }),
            columnHelper.accessor('shift', {
                header: 'Shift',
            }),

            columnHelper.accessor('quantity', {
                header: () => 'Quantity',
                cell: info => info.renderValue(),
            }),
        ],
        [],
    )

This what my data looks like

export const data = [
    {
        id: 1,
        shift: 'BREAKFAST',
        quantity: 1,
    }
    ...
]

This is the full error

Type 'AccessorKeyColumnDef<Reservation, number>' is not assignable to type 'ColumnDef<Reservation>'.
 Type 'AccessorKeyColumnDefBase<Reservation, number> & Partial<StringHeaderIdentifier>' is not assignable to type 'ColumnDef<Reservation>'.
   Type 'AccessorKeyColumnDefBase<Reservation, number> & Partial<StringHeaderIdentifier>' is not assignable to type 'AccessorKeyColumnDefBase<Reservation, unknown> & Partial<IdIdentifier<Reservation, unknown>>'.
      Type 'AccessorKeyColumnDefBase<Reservation, number> & Partial<StringHeaderIdentifier>' is not assignable to type 'AccessorKeyColumnDefBase<Reservation, unknown>'.
        Types of property 'footer' are incompatible.
          Type 'ColumnDefTemplate<HeaderContext<Reservation, number>> | undefined' is not assignable to type 'ColumnDefTemplate<HeaderContext<Reservation, unknown>> | undefined'.
            Type '(props: HeaderContext<Reservation, number>) => any' is not assignable to type 'ColumnDefTemplate<HeaderContext<Reservation, unknown>> | undefined'.

I’ve tried several types but none seems to work and I think this is happening because the cell value returned for each columnHelper.accessor has a varying type like number and string.

"@tanstack/react-table": "^8.20.1"
"typescript": "^5"

How to execute a JavaScript Stored Function in MySQL 9.0 using NodeJS and Postman?

I recently came across the new features in MySQL 9.0 and found out about JavaScript Stored Programs in this link and in the MySQL docs.
I also read this part about the new feature here.

So, I decided to test it using NodeJS and Postman.

Let’s say I executed the below code in MySQL:

CREATE FUNCTION sum(arg1 INT, arg2 INT) 
RETURNS INT LANGUAGE JAVASCRIPT AS 
$$
  return arg1 + arg2;
$$;

I have the main NodeJS file (server.js) below:

const express = require('express');
const cors = require('cors');
const connection = require('./db/connection');
const try = require('./utilities/try');


//Creating an Express application
const app = express();

//Use CORS
app.use(cors());

//Routes
app.use('', try);

// Initializing server
app.listen(3000, "localhost", () => {
    console.log("Server is running on port 3000");
});

Below I have connection.js for connceting the server to the DB.

"use strict"
require('dotenv').config();
const mysql = require('mysql2');

//MySQL connection
const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME
});

connection.connect(err => {
    if (err) throw err;
    console.log('Connected to the MySQL server.');
});

module.exports = connection;

And here, I’ve got my try.js for executing the MySQL statements:

const express = require('express');
const router = express.Router();
const connection = require('./db/connection');

router.post('/sum', (req, res) => {
    const {num1, num2} = req.body;
    if(!num1 || !num2){
        return res.status(400).json({ error: 'The numbers are required' });
    } else {
        const sql = "SELECT sum(?, ?)";
        const values = [num1, num2];
        connection.execute(sql, values, (err, results) => {
            if (err) {
                res.status(500).json({ error: 'Error while executing the function' });
            } else {
                res.status(200).json({ message: `The sum is ${results[0]['sum(?, ?)']}` });
            }
        });
    }
});

module.exports = router;

However, I’m not sure how to display the sum of the 2 values. Is this the correct way to do this? Or is it different? Any help would be appreciated. Note: I’m using the Community Edition, not the Enterprise Edition.

Any help would be appreciated. Thanks!

NOTE: I am not using the Enterprise Edition, I am using the Communtity Edition.

EDIT: The code leads to this response:

{
    "error": "Error while executing the function"
}

JavaScript buttons work locally but not after deploying to GitHub and Netlify (function not defined error) [closed]

I’m working on a Scoreboard dashboard as part of a learning project. The JavaScript functions in my app work perfectly in Visual Studio Code. However, after deploying the project to GitHub Pages and Netlify, the buttons in my counter app don’t work at all. When I click them, I get a “function is not defined” error (404), which makes me think that the index.js file isn’t loading properly.

Here’s the live site: https://neon-lily-6553ae.netlify.app/
And here’s the GitHub repository: https://github.com/jaysonfeldman/scoreboard-final

I double-checked the script tags in my index.html file to ensure they are correctly pointing to the index.js file. I’ve also verified that the JavaScript code works in a local environment, so I expected the same behavior after deployment. However, the deployed version fails to load the script properly, leading to a 404 error when trying to call the functions. I suspect there might be an issue with how the files are referenced in the deployed environment, but I’m not sure

I’m new to programming and have been trying to fix this for about 2 hours, but I’m stuck. As This is the first time for me asking a question on Stackoverlow, any guidance or tips would be greatly appreciated!

Screenshot 1

Screenshot 2

How to get the value of selected text in select combobox by javascript in asp.net c#

How to get the value from selected text by select combobox?
Here is the aspx.cs code for bind combobox

service.BindHTMLDropdownList(cmb_labelno, "tbl_StockRunning", "StockTagNo", "StockId", "where IsActive = 1 and StockTypePrefix = 'T' and " +
    "BranchId = " + Session["BranchId"] + "");

Combobox Name : cmb_labelno
Table Name : tbl_StockRunning
Text : StockTagNo
Value : StockId

Here is the aspx code

<select id="cmb_labelno" runat="server"></select>
<input type="button" id="btnGetStock" value="VIEW"/>


$("#btnGetStock").click(function (e) {               
    alert(document.getElementById('cmb_labelno').value);
});

Now, the place of alert(document.getElementById(‘cmb_labelno’).value I used
alert(document.getElementById(‘cmb_labelno’).val also still value is not showing.

While the same thing if I am doing in Jquery still showing the selectedtext only not value
Here is my Jquery code,

document.getElementById('<%= cmb_labelno.ClientID %>').value

Is there any problem in code…???

Typescript type inference not working as expected

I have two very similar functions but typescript can infer the return value of only one of them:

interface URItoKind<A> {}
type URIS = keyof URItoKind<any>;
type Kind<URI extends URIS, A> = URItoKind<A>[URI];

const URI = "Option";
export type URI = typeof URI;
interface URItoKind<A> {
  readonly [URI]: Option<A>;
}
class Option<A> {
  static of: <A>(a: A) => Option<A>;
}

function test1<F extends URIS, A, B>(f: (a: A) => Kind<F, B>): Option<B>;

function test2<F extends URIS>(): <A, B>(f: (a: A) => Kind<F, B>) => Option<B>;

const func = (x: number) => Option.of(x.toString()); // (x: number) => Option<string>
const r1 = test1(func); // Option<unknown> - Doesn't work
const r2 = test2()(func); // Option<string> - Works Fine

Playground Link

I was hoping somebody could explain to me what’s the issue. Is this expected or is it a bug? Is there some kind of workaround to make test1 work without specifying the types manually?

How to get the classnames by node-tree-sitter?

I want to get all classNames, I think as long as I match all the class node, I could get the classname,

so I tried below code:

const Parser = require("tree-sitter")
const JavaScript = require("tree-sitter-javascript")
const { Query } = Parser 


const parser = new Parser()
parser.setLanguage(JavaScript)

const query = new Query(
  JavaScript,
  `
    (class_declaration name: (identifier) @class-name)
  `
);


const tree = parser.parse(`
class Person {}
 
const TestPerson = class {}

class Person2 {}
 
const TestPerson2 = class {}
  `);
const matches = query.matches(tree.rootNode);

matches.forEach(item => {
  console.log(item.captures[0])
})

When I execute it:

$ node query-test.js 
{
  name: 'class-name',
  node: IdentifierNode {
    type: identifier,
    startPosition: {row: 2, column: 6},
    endPosition: {row: 2, column: 12},
    childCount: 0,
  }
}
{
  name: 'class-name',
  node: IdentifierNode {
    type: identifier,
    startPosition: {row: 8, column: 6},
    endPosition: {row: 8, column: 13},
    childCount: 0,
  }
}

there is no classname ['Person', 'Person2'],

please tell me how to get the class names.

Returning an array in react after shuffling

I am using a function that takes an array as input and returns a shuffled array. When i return the shuffled array , the UI is not getting repainted. Code below –

import { useState } from "react";

function App() {
  const [items, setItems] = useState([
    "Amit",
    "Ashok",
    "Alok",
    "Vijay",
    "Kumar",
    "Raju",
  ]);

  console.log("App component is rendered");

  function shuffle(array) {
    let currentIndex = array.length;
    // While there remain elements to shuffle...
    while (currentIndex != 0) {
      // Pick a remaining element...
      let randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
      // And swap it with the current element.
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex],
        array[currentIndex],
      ];
    }
    //
    console.log(array);
      return array;
    //return [...array];
  }
  console.log(items);

  return (
    <>
      <button onClick={() => setItems(shuffle(items))}>Shuffle</button>
      {items?.map((item) => (
        <p key={item}>{item}</p>
      ))}
    </>
  );
}

export default App;

If i return the array using the spread operator , the UI is getting rendered again. Can anyone explain what is the reason for this.

antd Trigger onChange event manually instead of waiting for clicks

I’m using antd RangePicker version 3.22.0. I’ve defined an onCalendarChange function that given a single choice, forces the other choice, thus negating the need for a second click.
Problem is, the component still requires a second click which is not the behavior I’m interested in.
Is there any way to bypass this two click mechanism? I thought that by forcing values it would work but it doesn’t. Will triggering onChange manually help?
Heres the code:

        <DatePicker.RangePicker
            dropdownClassName={props.customParams && "custom-date-picker"}
            open={props.isOpen}
            value={props.markedDate}
            format={dateFormat}
            disabledDate={props.customParams?.disabledDates ?? TimeUtils.isDateAfterToday}
            showTime
            onOk={props.onOk}
            style={{opacity: 0}}
            separator={""}
            getCalendarContainer={props.calendarContainer}
            onCalendarChange={props.onCalendarChange}
            renderExtraFooter={props.renderExtraFooter}
            dateRender={renderDate}
        />

Thanks!

Effect of stack for todos

I am creating todo list application using react and Ant Design and i wanna to make the effect of stack for todos but i don’t know how.

Here is how it should look like: example.

I was looking for it in ant design components, but didn’t find anything like that.

Thanks in advance.

serialize and deserialize `undefined`

undefined is not a valid JSON value so I am using a custom replacer function to serialize it. It works fine. However, when deserializing it, it works for both values and arrays (so my reviver function seems to work) but not for objects where the undefined key disappears. What am I doing wrong?

function serialize(data) {
   return JSON.stringify(data, function (key, value) {
      if (this[key] === undefined) {
         return '__undef__'
      }

      return value
   })
}

function deserialize(data) {
   return JSON.parse(data, function (key, value) {
      if (this[key] === '__undef__') {
         return undefined
      }

      return value
   })
}

const undef = undefined
const obj1 = { undef: undefined }

console.log(serialize(undefined));
console.log(deserialize(serialize(undefined)));

console.log(serialize([undefined]));
console.log(deserialize(serialize([undefined])));

console.log(serialize({ undef: undefined }));
console.log(deserialize(serialize({ undef: undefined })));

Why can’t i access the protected routes even after the authentication, in clerk

enter image description here

import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)'])

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)'])
export default clerkMiddleware((auth, req) => {
  if (!isPublicRoute(req)) {
    auth().protect()
  }

  if (isProtectedRoute(req)) auth().protect()
})

export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    '/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)',
  ],
}

this is the middleware, before sign in i cant access any page. All the pages are protected except sign in and signup pages. After sign in the URL is{ http://localhost:3000/sign-in?redirect_url=http%3A%2F%2Flocalhost%3A3000%2F }

GET /sign-in?redirect_url=http%3A%2F%2Flocalhost%3A3000%2Ftest 200 in 88ms
GET /sign-in?redirect_url=http%3A%2F%2Flocalhost%3A3000%2Ftest 200 in 41ms
GET /sign-in/SignIn_clerk_catchall_check_1723370469288 200 in 46ms

After sign in this is the error i get in the terminal. i am being redirected to the above URL after sign in.
I cant access the dashboard or any other page. I am redirected to above URL.
how to change this.

I tried reading clerk docs, i tried chat-GPT i tried stack overflow. i tried every thing i can , but nothing changed.

chrome extension send multiple data and wait all of them before continue

I’m making an extension where I need to pass several data from content.js to my background.js so I can use chrome.downloads.download API. This information contains filepath, URL to download, images.

Since I only can pass one item at a time and can’t pass HTMLCollections, I thought to develop a small if statement that can help me handle all of this.
The problem: I need to wait until I receive all messages so I can start the work.

With the following code, the file tries to download several times since I guess it runs while the for loop for the images is still running.

content.js

//download link
chrome.runtime.sendMessage({
  data: downloadlink,
  type: "m1"
})

//filepath
chrome.runtime.sendMessage({
  data: filepath,
  type: "m2"
})

//filename
chrome.runtime.sendMessage({
  data: nomeficheiro,
  type: "m3"
})

//for loop to send each image in HTMLCollection
for (const element of images) {
  chrome.runtime.sendMessage({
    data: element.src,
    type: "m4"
  })
}

background.js

const img = [] 
chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
  // file url
  if (request.type == "m1") {
    downloadlink = request.data;
  // file path
  } else if (request.type == "m2") {
    filepath = request.data;
  // nome name
  } else if (request.type == "m3") {
    nomedoficheiro = request.data;
  // html collection images
  } else if (request.type == "m4") {
    img.push(request.data)
  }

  chrome.downloads.download({ 
    filename: filepath + "/" + nomedoficheiro, 
    url: downloadlink,
   });
  

});

How can I make all messages are sent, wait for all of them in background.js and only when I received all of them I would do the code to download the files? Sometimes it tries to download the same file several times (the number of times the images pushed into array), other times outputs error since filepath doesn’t exist, etc.

Thank you.