Facing Total Supply error in ethers if anyone could suggest something?

Error I’m facing continuosly with ethers.js

CODE

const pair = new Contract(
            pairAddress,
            blockchain.pairAbi,
            wallet
        );
        const totalSupply = await pair.totalSupply();  //LP * (Liquidity Provider)
        if(totalSupply === 0n){
            console.log(`Pair ${pairAddress} is empty, skipping...`);
            continue;
        }

ERROR

Error: could not decode result data (value="0x", info={ "method": "totalSupply", "signature": "totalSupply()" }, code=BAD_DATA, version=6.13.2)
    at makeError (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/utils/errors.js:129:21)
    at assert (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/utils/errors.js:149:15)
    at Interface.decodeFunctionResult (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/abi/interface.js:780:31)
    at staticCallResult (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/contract/contract.js:254:35)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async staticCall (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/contract/contract.js:219:24)
    at async Proxy.totalSupply (/mnt/d/Sniping Bot/sniperjavascript/node_modules/ethers/lib.commonjs/contract/contract.js:259:20)
    at async snipe (/mnt/d/Sniping Bot/sniperjavascript/bot_copy.js:61:29)
    at async main (/mnt/d/Sniping Bot/sniperjavascript/bot_copy.js:172:9) {
  code: 'BAD_DATA',
  value: '0x',
  info: { method: 'totalSupply', signature: 'totalSupply()' },
  shortMessage: 'could not decode result data'
}

Node.js v22.5.1
make: *** [Makefile:4: bot] Error 1

I just want that this erro go away I don’t want to see it again and again.

Window focus and blur events not working properly in chrome

I have very simple code to log some message on window focus and blur events. It works fine on edge, firefox and brave browser and is not working consistently in the chrome browser. Is there any workaround to overcome this? as i couldn’t see any one mentioning this issue on internet. Below is my code.

Few times, i noticed it works and when the same page is opened in the new tab, the events are not fired

<!DOCTYPE html>
<html>
<head>
    <title>Window Focus/Blur Logger</title>
    <script>
        window.addEventListener('focus', function() {
            console.log('Window gained focus');
        });

        window.addEventListener('blur', function() {
            console.log('Window  lost focus');
        });
    </script>
</head>
<body>
    </body>
</html>

I need solution for overlapping item image on top of another?

I’m trying to make a streaming service website as practice, but the problem is when I put images, titles and episode lists in a way like columns and rows. For the image on top over I, tried changing the margin or other things but it didn’t work.

I tried to change the margin, and perhaps put a container on it but it didn’t work, I want it to be like this:
existing streaming service

It ended up lining up. Likes this:
My Streaming Service

I want to line up at least four columns containing a poster, title and episode. At first, the row is ok but the second and further overlaps on top of the first. This is the code:

.column {
  background-color: rgb(249, 215, 142);
  float: left;
  width: 200px;
  padding: 20px;
  height: 200px;
  grid-template-columns: 1fr 1fr 1fr;
}

.row:after {
  content: "";
  display: grid;
  clear: both;
  
}

<div class="row">

  <div class="column">
    <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Oshi No Ko Season 2.jpg" 
    style="width:200px;height:270px; margin-bottom:10px; margin-right: 15px; border:none;">
<p class="video-title">Oshi No Ko Season 2</p>
<p class="video-episode">Episode 1</p>
<p class="video-title">Sub</p>
</img>
</div>

<div class="column">
  <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Failure Frame Season 1.jpg" 
  alt="Failure Frame Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
</img>
  <p class="video-title">Failure Frame</p>
<p class="video-episode">Season 1 Episode 1</p>
<p class="video-title">Sub</p>

</div>

<div class="column">
  <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Vanguard Divinez Season 2.jpg" 
  alt="Vanguard Divinez Season 2" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
</img>
  <p class="video-title">Vanguard Divinez Season 2</p>
<p class="video-episode">Episode 1</p>
<p class="video-title">Sub</p>

  </div>

  <div class="column">
    <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Alya Sometimes Hides Her Feelings in Russian Season 1.jpg" 
    alt="Alya Sometimes Hides Her Feelings in Russian Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
    <p class="video-title">Alya Sometimes Hides Her Feelings in Russian Season 1</p>
  <p class="video-episode">Episode 1</p>
  <p class="video-title"> Dub|Sub</p>
  </img>
    </div>

    <div class="column">
      <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/7th Time Loop The Villainess Enjoys a Carefree Life Married to Her Worst Enemy.jpg" 
      alt="7th Time Loop The Villainess Enjoys a Carefree Life Married to Her Worst Enemy Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
      <p class="video-title">7th Time Loop The Villainess Enjoys a Carefree Life Married to Her Worst Enemy Season 1</p>
    <p class="video-episode">Episode 1</p>
    <p class="video-title">Sub</p>
    </img>
      </div>
 
      <div class="column">
        <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/As A Reincarnated Aristocrat I'll Use My Appraisal Skill to Rise in The World.jpg" 
        alt="As A Reincarnated Aristocrat I'll Use My Appraisal Skill to Rise in The World Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
        <p class="video-title">As A Reincarnated Aristocrat I'll Use My Appraisal Skill to Rise in The World Season 1</p>
      <p class="video-episode">Episode 1</p>
      <p class="video-title"> Dub|Sub</p>
      </img>
        </div>

        <div class="column">
          <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Chillin' in Another World with Level 2 Cheats.jpg" 
          alt="Chillin' in Another World with Level 2 Cheats Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
          <p class="video-title">Chillin' in Another World with Level 2 Cheats Season 1</p>
        <p class="video-episode">Episode 1</p>
        <p class="video-title"> Dub|Sub</p>
        </img>
          </div>

          <div class="column">
            <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/Fairy Tail 100 Years Quest.jpg" 
            alt="Fairy Tail 100 Years Quest Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
            <p class="video-title">Fairy Tail 100 Years Quest Season 1</p>
          <p class="video-episode">Episode 1</p>
          <p class="video-title"> Dub|Sub</p>
          </img>
            </div>

            <div class="column">
              <img src="/Users/sebastianpendragon/Desktop/Software Engineer Project/Image Source/I Parry Everything.jpg" 
              alt="I Parry Everything Season 1" style="width:210px;height:270px; margin-bottom:10px; margin-right: 15px">
              <p class="video-title">I Parry Everything Season 1</p>
            <p class="video-episode">Episode 1</p>
            <p class="video-title"> Dub|Sub</p>
            </img>
              </div>

</div>

Anyone know how to fix it.

Efficiently calculate an availability date from a list of project assignments and known capacity

I’m looking for an efficient way to calculate the date each member of a team is available given a set of project assignments. There are 25 team members, each with a set of capacities and assignments.

Capacities are a percentage availability between two dates (this is how part-time hours are supported, 100% being full-time), with null end dates for scenarios where the capacity is indefinite. Capacities can be zero, to support things such as secondments or parental leave.

Assignments link a team member to a project for a percentage between two dates. This allows a member to have two projects at the same time (say a 60/40 split) and these add up to the capacity of the team member. So if a person has 60% capacity, they might have two projects 30% each.

All of this works perfectly, but now I want to calculate the date each person in the team is available next. I can do this in what feels like a brute-force way by using a loop to count forward one day at a time until I arrive at a point where the total assigned percentage is less than the capacity, but this feels wildly inefficient – is there a better way?

I’ve added a Gantt chart image to show what I mean, I’d like to calculate the dates where the red lines are. Any help, even pseudo-code, is greatly appreciated. The application stack is NodeJS and Vue, and I’m using the Luxon library in the brute-force method. Language doesn’t matter, I’m looking for help with the general approach to the problem that I can then implement in JS.

enter image description here

We are experiencing an issue where our scheduled Cloud Function is being triggered multiple times unexpectedly

Below is the configuration for the function:

.region("australia-southeast1")
.runWith({ secrets: ["***"], timeoutSeconds: 540, memory: "1GB", 
           vpcConnector: "nrl-grassroots", maxInstances: 1 }) 
.pubsub.schedule("0 0-6 * * 2-5")
.timeZone("Australia/Sydney")

The function is set to run on a schedule between 00:00 and 06:00 on Tuesday through Friday (Australia/Sydney time). However, we’ve observed instances where the function is triggered more than once during its scheduled time window, which is not the expected behavior.

Steps Taken:

  • Verified the configuration settings for the function.
  • Checked Cloud Function logs to confirm multiple triggers.

Any assistance in determining the root cause of this issue and guidance on how to prevent the function from being triggered multiple times. Could you provide any insights into why this might be happening and any recommended solutions to resolve it?

With the config we were expecting there will be 6 runs over night.

Anomaly in Updating React Array State

Updating state of array didn’t work like expected!

Hi Guys!

I’m making a Tic-Tac-Toe Game with this detail:

I have a state called gameBoardState (an 3×3 array) that contains the position of ‘X’ & ‘O’ with initial value of all ‘null’.

**const initialGameBoard = [
  [null, null, null],
  [null, null, null],
  [null, null, null],
];
**
export default function GameBoard({
  playerTurnHandler,
  onTurn,
  turnLogger,
  participant,
}) {
  **const [gameBoardState, setGameBoardState] = useState(initialGameBoard);**
  const [winner, setWinner] = useState('');
  const [counter, setCounter] = useState(0);
.
.
.
}

When the game is over there’s a ‘rematch’ button that set the gameBoardState back to the initial state – which is all null.

Inside the onClick listener function, I copied the old value of the variable ‘initialGameBoard’ into a new const variable and then use this variable as the parameter of setGameBoardState(param). It didn’t work 🙁

I also tried setGameBoardState(initialGameBoard). It didn’t work too.

But when I initialized a new const variable inside the onClick function and directly use this variable inside setGameBoardState it did work!

Can someone explain to me why did it happen?

Thanks!

This is my complete code:

import { useState, useSyncExternalStore } from 'react';
import { WINNING_COMBINATIONS } from '../winning-combinations';
import GameOver from './GameOver';

const initialGameBoard = [
  [null, null, null],
  [null, null, null],
  [null, null, null],
];

export default function GameBoard({
  playerTurnHandler,
  onTurn,
  turnLogger,
  participant,
}) {
  const [gameBoardState, setGameBoardState] = useState(initialGameBoard);
  const [winner, setWinner] = useState('');
  const [counter, setCounter] = useState(0);

  function checkWinner(actualGameboardState) {
    const numberOfCombinations = WINNING_COMBINATIONS.length;
    for (let index = 0; index < numberOfCombinations; index++) {
      const firstBlock = WINNING_COMBINATIONS[index][0]; //example = {row: 0, column: 0}
      const secondBlock = WINNING_COMBINATIONS[index][1]; //example = {row: 0, column: 1}
      const thirdBlock = WINNING_COMBINATIONS[index][2]; //example = {row: 0, column: 2}

      if (
        actualGameboardState[firstBlock.row][firstBlock.column] === null ||
        actualGameboardState[secondBlock.row][secondBlock.column] === null ||
        actualGameboardState[thirdBlock.row][thirdBlock.column] === null
      ) {
        continue; //if null, directly check the next combination
      }

      if (
        actualGameboardState[firstBlock.row][firstBlock.column] === 'X' &&
        actualGameboardState[secondBlock.row][secondBlock.column] === 'X' &&
        actualGameboardState[thirdBlock.row][thirdBlock.column] === 'X'
      ) {
        //do something
        setWinner(participant[0].toUpperCase());
      }

      if (
        actualGameboardState[firstBlock.row][firstBlock.column] === 'O' &&
        actualGameboardState[secondBlock.row][secondBlock.column] === 'O' &&
        actualGameboardState[thirdBlock.row][thirdBlock.column] === 'O'
      ) {
        //do something
        setWinner(participant[1].toUpperCase());
      }
    }
  }

  function selectSquareHandler(row, col) {
    const newGbState = [...gameBoardState];
    newGbState[row][col] = onTurn;
    setGameBoardState(newGbState);
    playerTurnHandler();
    turnLogger(row, col, onTurn);
    checkWinner(gameBoardState);
    setCounter((prev) => prev + 1);
  }

  function rematch() {
    const initial = [...initialGameBoard];

    const initial2 = [
      [null, null, null],
      [null, null, null],
      [null, null, null],
    ];

    //setGameBoardState(initial); doesn't work! page isn't re-rendered
    //setGameBoardState(initialGameBoard) also doesn't work
    setGameBoardState(initial2);//works perfectly!
    setWinner('');
    setCounter(0);
    console.log(gameBoardState, winner, counter);
  }

  return (
    <>
      {(winner || counter === 9) && (
        <GameOver winner={winner} rematch={rematch} />
      )}
      <ol id="game-board">
        {gameBoardState.map((row, rowIndex) => (
          <li key={rowIndex}>
            <ol>
              {row.map((playerSymbol, colIndex) => (
                <li key={colIndex}>
                  <button
                    onClick={() => selectSquareHandler(rowIndex, colIndex)}
                    disabled={playerSymbol !== null ? true : false}
                  >
                    {playerSymbol}
                  </button>
                </li>
              ))}
            </ol>
          </li>
        ))}
      </ol>
    </>
  );
}

How to use Tailwind in a Chrome extensions?

As many of you know Chrome extensions are just regular javascript/css/html files.
Since there is no tailwind.min.css file and there is no npm in a Vanilla chrome extensions this leads me to the question:

How does one use Tailwind in an existing chrome extensions?

Please note that migrating the entire extension to some React template that finally builds into an extension is not a reasonable solution to just include tailwind styles.

Different ways of passing a variable by reference?

I want to pass a variable to a function and have the function change the value.

I know I can do this as an object but am wondering if there is some way to do this that I haven’t thought of.

This is what I want to do, but it doesn’t work the way I want of course:

function test1(vari) {
    vari = 2;
}
var myvar1 = 1;
test1(myvar1);
console.log(myvar1);

This works, but I don’t really want to make all the variables objects:

function test2(vari) {
    vari.val = 2;
}
var myvar2 = { val: 1 };
test2(myvar2);
console.log(myvar2.val);

This also works, but not an acceptable solution:

function test3(vari) {
    eval(vari + ' = 2;');
}
var myvar3 = 1;
test3('myvar3');
console.log(myvar3);

Is there a better option than these?

I cannot get my custom js module classes to export

Context:
Typescript,
custom module with target environment react

source code: https://github.com/bingomanatee/wonderlandlabs-monorepo/tree/main/packages/forestry

continually getting “exports is not defined”

tried setting moudle/target in TSconfig:

{
  "compilerOptions": {    "target": "ESNext",
    "module": "ESNext",    "declaration": true,    "outDir": "./lib",    "downlevelIteration": true,    "isolatedModules": false,    "strict": false,    "moduleResolution": "node",                "types": [
      "jest",
      "node",
      "@types/jest"
    ],     "esModuleInterop": true,    "resolveJsonModule": true,
    "skipLibCheck": true,  },
  "include": [
    "src",
  ],
  "exclude": [
    "node_modules",
    "__tests__
    "lib
    "lib
  ],
  "rules": {
    "@typescript-eslint/ban-ts-comment": false
  }
}

what am I missing?

How do I properly download files and save to a zip in javascript from presigned urls coming from AWS S3?

I have an AWS S3 bucket with open permissions that look like this:

**[
{
    "AllowedHeaders": [
        "*"
    ],
    "AllowedMethods": [
        "GET",
        "PUT",
        "POST",
        "DELETE",
        "HEAD"
    ],
    "AllowedOrigins": [
        "*"
    ],
    "ExposeHeaders": [
        "ETag"
    ],
    "MaxAgeSeconds": 3000
}**

I also have a IAM user/policy that looks like this:

**{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AllowAllOrigins",
        "Action": [
            "s3:*"
        ],
        "Effect": "Allow",
        "Resource": [
            "arn:aws:s3:::my-bucket/*",
        ]
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:ListBucket",
            "s3:GetObject",
            "s3:PutObject",
            "s3:DeleteObject"
        ],
        "Resource": [
            "arn:aws:s3:::my-bucket/*",
        ]
    }
]

}**

I am struggline with an error related to CORS: http://localhost:3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I upload my files via a pre-signed url, and also get my files with a pre-signed url. The issue is when I try and download them I get a CORS error most of the time. Rarely it will go through and let me download my files.

Here is the code that I am using to download the files:

    const handleDownload = async () => {
        const zip = new JSZip();

    // Fetch each file and add it to the zip
    for (const item of selectedItems) {
        // item is the index and fileItems[item] is the pre-signed url
        const response = await fetch(fileItems[item].url);
        const blob = await response.blob();
        const splitUrl = fileItems[item].url.split('?');
        const fileNameFromUrl = splitUrl[0].split('/');
        const filename = fileNameFromUrl[7];
        zip.file(filename, blob);
    }

    // Generate the zip file and trigger download
    zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, 'selected-files.zip');
    });
};

I’ve tried pretty much everything to get the files to download without issue, every time.
Anyone know how I can remove this CORS roadblock?

Get 422 error when trying to connect frontend to server

I am using fastapi-users library for authentication and authorization. Everything worked properly in swagger but when I am trying to connect backend and frontend i get such an error and such data:
[HTTP/1.1 422 Unprocessable Entity 8ms]

request: {"username":"[email protected]","password":"me"}
response: {"detail":[{"type":"missing","loc":["body","username"],"msg":"Field required","input":null},{"type":"missing","loc":["body","password"],"msg":"Field required","input":null}]}

I added CORS and MiddleWare, so it should be ok there.

origins = [
        f"http://{FRONT_HOST}:{FRONT_PORT}",
    ]
app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

Here is my Login code:

import React, { useState } from 'react';

const Login = () => {
  const [formData, setFormData] = useState({
        username: '',
        password: '',
    });


  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value,
        });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
        const response = await fetch('http://localhost:8000/auth/jwt/login', {
            method: "POST",
            headers: {
                'accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify({
                username: formData.username,
                password: formData.password})
        });

        if (!response.ok) {
            throw new Error('Error during registration');
        }

        const data = await response.json();
        setSuccess('Login successful!');
        return <Redirect to='/account' />;
        // Возможно, вам нужно будет перенаправить пользователя или обновить состояние приложения


    } catch (err) {
        setError(err.message);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ maxWidth: '400px', margin: 'auto' }}>
      <h2>Login</h2>
        <div>
          <label>Email:</label>
          <input
            type="email"
            name="username"
            value={formData.username}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label>Password:</label>
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
          />
        </div>
        <button type="submit">Enter</button>
    </form>
  );
}

export default Login;

I read the github code of OAuth2PasswordRequestForm but still cannot understand what is the root of this problem.

I’ve tried different variations of:

  • body parameter in fetch (JSON.stringify, and just formData)
  • tried to add other optional parameters (grant_type, scope, client_id, client_secret)
  • tried to use both “application/x-www-form-urlencoded” and “application/json” content types

Maybe I do not understand how forms and JSON are sent.
I think there is a problem in sending data.
I would be glad to find out how it should actually work because I am new to making fullstack.

Unexpected domcontentloaded and load event firing playwright [closed]

page.waitForLoadState: Timeout 30000ms exceeded. =========================== logs =========================== "domcontentloaded" event fired "load" event fired ==============================

Keep getting above error while running test cases even though i don’t have any explicit waitForLoadstate for domcontentloaded or load.

Please help me find the better solution

Need a smooth navigation

How to reliably record input texts on each keystroke?

Here is a simple web page which stores unique input texts as Map keys. This is triggered the keyup event on the text input field. In case a particular text already exists in the Map, a message “repeat” is displayed in the label with id = ‘old’. This works as expected when I type slowly but it usually displays “repeat” when I type quickly, even for first time texts. How can I fix this?

class KeyupClass {
  newlabel = document.getElementById('new');

  textmap = new Map();

  oldlabel = document.getElementById('old');

  update = (event) => {
    this.newlabel.innerHTML = `new text ${event.target.value}`;
    if (this.textmap.has(event.target.value)) this.oldlabel.innerHTML = 'repeat';
    else {
      this.textmap.set(event.target.value, this.oldlabel.innerHTML);
      this.oldlabel.innerHTML = `previous text ${event.target.value}`;
    }
  };

  constructor() {
    document.getElementById('textinput').addEventListener('keyup', this.update);
  }
}
new KeyupClass();
<!doctype html>
<html lang="en-US">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>keyup event test</title>
</head>

<body>
  <div style="display: grid">
    <label>editing input updates old and new labels on each keystroke</label>
    <input type="text" id="textinput" placeholder="add text here" />
    <label id="old">old text</label>
    <label id="new">new text</label>
  </div>
</body>

</html>