Hardhat contract not showing

I’m trying to build an NFT site… following a video on Youtube I got to the part where I need to deploy my contract.

When I try to run npx hardhat run scripts/deploy.js --network goerli this message comes normally:

Lock with 0.001ETH and unlock timestamp 1682374138 deployed to 0x0284782356e7886a9Be78b57DA90e69167cB6CE2″

But when I try to see the contract in https://goerli.etherscan.io/address/0x0284782356e7886a9Be78b57DA90e69167cB6CE2 it shows that I do not have any contract.

The only thing I did differently from the youtube video adds the gasPrice on hardhat.config.js, cause without that I got another error saying that I don’t have founds (I have 0.0858 goerli eth). Can someone help me?

Deploy.js:

const hre = require("hardhat");

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contracts with the account:", deployer.address);
  console.log("Account balance:", (await deployer.getBalance()).toString());
  const currentTimestampInSeconds = Math.round(Date.now() / 1000);
  const unlockTime = currentTimestampInSeconds + 60;

  const lockedAmount = hre.ethers.utils.parseEther("0.001");
  const ethAmount = ethers.utils.parseEther('0.01');

  const Lock = await hre.ethers.getContractFactory("Lock");
  const lock = await Lock.deploy();

  console.log(
    `Lock with ${ethers.utils.formatEther(lockedAmount)}ETH and unlock timestamp ${unlockTime} deployed to ${lock.address}`
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

hardhat.config.js:

require("@nomicfoundation/hardhat-toolbox");
const dotenv = require("dotenv");
require('dotenv').config();

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.18",
  networks: {
    goerli: {
      url: process.env.REACT_APP_GOERLI_RPC_URL, 
      accounts: [process.env.REACT_APP_PRIVATE_KEY],
      gasPrice: 500000
    },
  },
  etherscan:{
    apiKey: process.env.REACT_APP_ETHERSCAN_KEY
  }
};

.env:

REACT_APP_GOERLI_RPC_URL='' //my url to infura api key
REACT_APP_ETHERSCAN_KEY='' //my etherscan key
REACT_APP_PRIVATE_KEY='' //my private key

Lock.sol (contract):

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

contract Lock is ERC721, Ownable{
    uint256 public mintPrice;
    uint256 public totalSupply;
    uint256 public maxSupply;
    uint256 public maxPerWallet;
    bool public isPublicMintEnabled;
    string internal baseTokenUri;
    address payable public withdrawWallet;

    mapping(address => uint256) public walletMints;

    constructor() payable ERC721('Lock', 'GB'){
        mintPrice = 0.00000001 ether;
        totalSupply = 0;
        maxSupply = 1000;
        maxPerWallet = 3;
    }

    function setIsPublicMintEnabled(bool isPublicMintEnabled_) external onlyOwner{
        isPublicMintEnabled = isPublicMintEnabled_;
    }

    function setBaseTokenUri(string calldata baseTokenUri_) external onlyOwner {
        baseTokenUri = baseTokenUri_;
    }

    function tokenURI(uint256 tokenId_) public view override returns (string memory){
        require(_exists(tokenId_),'Token does not exists');
        return string(abi.encodePacked(baseTokenUri, Strings.toString(tokenId_),".json"));
    }

    function withdraw() external onlyOwner {
        (bool success, ) = withdrawWallet.call{value: address(this).balance}('');
        require(success, 'withdraw failed');
    }

    function mint(uint256 quantity_) public payable {
        require(isPublicMintEnabled, 'minting not enabled');
        require(msg.value == quantity_ * mintPrice, 'wrong mint value');
        require(totalSupply + quantity_ <= maxSupply, 'sold out');
        require(walletMints[msg.sender] + quantity_ <= maxPerWallet, 'exceed max wallet');

        for(uint256 i=0; i<quantity_; i++){
            uint256 newTokenId = totalSupply + 1;
            totalSupply ++;
            _safeMint(msg.sender, newTokenId);
        }
    }
}

Handling Nested Promise Function Calls

If I have a function that gets an api response and awaits it, like this:

async function getResponse(repo) {
  const apiResponse = await axios.get(...); // uses repo
  return apiResponse;
}

and I have a function that applies this function to many repos:

async function getResponsesMany(repos) {
  const promises = [];
  repos.forEach(repo => promises.push(getResponse(repo));
  const responses = await Promise.all(promises);
  return responses;
}

I can get all my data like this:

const allData = await getResponsesMany(myRepos);

But this is weird to me, because getResponse is awaiting the axios.get call, but I feel like I don’t need to do that, since when I await Promise.all(promises) it will handle any nested promises. Am I supposed to therefore refactor getResponse to return the promise returned by axios.get instead? Is there a reason one should be faster than the other?

Add rows per page to custom pagination

I’m trying to add rows per page as a select option here. I’m able to get the total and current page but I would like to add the option to increase rows per page to 20 or 30. I tried to use MUI’s paginaton component but my project’s theme clashes with it so I guess I should build a custom pagination….?

enter image description here

I’m getting the data from Redux and mapping it out like this.

const { customers, isError, message, meta } = useSelector(
    (store) => store.customer
  );

  const pageNum = [];
  for (let i = 1; i <= meta.lastPage; i++) {
    pageNum.push(i)
  }
  const [page, setPage] = useState(1);

  const onChange = (e) => {setPage(e.target.value);};

<Table variant="simple" color={textColor}>
            <Thead>
              <Tr my=".8rem" pl="0px" color="gray.400">
                {captions.map((caption, idx) => {
                  return (
                    <Th color="black" key={idx} ps={idx === 0 ? "6px" : "24px"}>
                      {caption}
                    </Th>
                  );
                })}
              </Tr>
            </Thead>
            <Tbody>
              {customers
                .filter((customers) => {
                  return search.toLowerCase() === ""
                    ? customers
                    : customers.first_name.toLowerCase().includes(search) ||
                    customers.last_name.toLowerCase().includes(search);
                })
                .map((customers) => {
                  return (
                    <CustomersTable
                      key={customers.uid}
                      name={`${customers.first_name} ${customers.last_name}`}
                      logo={customers.logo}
                      id={customers.uid}
                      exchange={customers.exchange}
                      createdAt={moment(customers.createdAt).format("LLL")}
                    />
                  );
                })}
            </Tbody>
          </Table>
        </SkeletonText>
      </CardBody>
      <Flex justifyContent='space-between' alignItems='center' mt='20px'>
        <Text>Showing 1 to {meta.perPage} of {meta.total} Records</Text>
        <Text>page: {meta.currentPage}</Text>
        <Select w='70px' onChange={onChange} value={page} name='page'>
          {pageNum.map(a => <option>{a}</option>)}
        </Select>
      </Flex>
    </Card>

Dynamic import of JavaScript module without file path

Is it possible in the ECMAScript language, or other way, to import a module using some kind of object other than the real file path in local computer (whether relative or absolute, or with an “import map”)?

For example, as a use-case, there are some JavaScript packages (“memfs”) that mimic files and behave like virtual filesystems. Some of those files can of course contain JS code that can play the role of a JS Module, possibly wanted to be dynamically imported. They may have a “fake” virtual file path or file name, but how can the JS Runtime/Parser/Interpreter can process it?

Also, we can simply read a local file’s content (Via NodeJS for example), and it’s possible that we want to load its content as a module, when the original path is not available anymore, or for any other reason.

So, sometimes you have files, file contents, but without “file path”, how it’s possible to use that content for a module? (and not a regular inline scoped object.

How to get value from axios post response into UI text element

How should I get the value from axios post response (response.data.result) into UI text element.

setRecorderState((prevState) => {
      let url = window.URL.createObjectURL(blob);
      let formData = new FormData();
      formData.append("file_from_react", blob, "1.wav");
      console.log(formData)
      axios
        .post("http://192.168.0.112:5000/profile", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          console.log("response: " + response.data.result);
        })
        .catch((error) => {
          if (error.response) {
            console.log(error.response);
            console.log(error.response.status);
            console.log(error.response.headers);
          }
        });
       
      if (prevState.mediaRecorder)
        return {
          ...initialState,
          audio: url,
        };
      else return initialState;
    });

The response is in response.data.result. The question is: how can i render this response in the HTML page, this page being located in another js file?
This is the main code for the HTML page, and I want to render the variable mentioned above here:

 return (
    <View style={styles.container}>
      <div className="recorder-container">
        <RecorderControls recorderState={recorderState} handlers={handlers} />
        <RecordingsList audio={audio} />
      </div>
    </View>
  );

Firebase Storage Rules look right but still get “User does not have permission to access”

I’m experiencing firebase security rules errors and i can’t figure out what’s the problem.
The two conditions to write are that the user should be logged in and that the user requesting should have the same UserId of the folder/author

Here are my security rules:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /images/{userId}/{imageId} {
      allow read: if true;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
    match /videos/{userId}/{videoId} {
      allow read: if true;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
    match /profileImage/{userId}/{profileImage} {
      allow read: if true;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

All these rules cause an error when i’m trying to upload a profile image, an image or a video.
The error that i get is:

Firebase Storage: User does not have permission to access ‘images/LsF54H8lrFG5eKQPiEd8IUBx78c9/14211068-1225-4321-a5c0-0b55d0801d33-IMG-20200911-WA0032.jpg’. (storage/unauthorized)

The code to upload:

if (images.length > 0) {
    //Not sure how to address async state here.
    // setImageUploading(true);
    imageIsLoading();
    images.forEach((image) => {
      // console.log("Uploading State: " + imageUploading);
      imageID = `${uuidv4()}-${image.name}`;
      const uploadPromise = new Promise((resolve) => {
        const storageRef = ref(
          storage,
          // "images/" + user + "/" + uuidv4() + "-" + image.name
          "images/" + user + "/" + imageID
        );

        const uploadTask = uploadBytesResumable(storageRef, image);
        // console.log("Upload Status: " + imageUploading);

        uploadTask.on(
          "state_changed",
          (snapshot) => {
            // Observe state change events such as progress, pause, and resume
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log(
              image.name + ": Upload is " + Math.ceil(progress) + "% done"
            );
            switch (snapshot.state) {
              case "paused":
                console.log("Upload is paused");
                break;
              case "running":
                console.log("Upload is running");
                break;
              default:
            }
          },
          (error) => {
            // Handle unsuccessful uploads
            toast.error(error.message);
            console.log(error.message);
            // setImageUploading(false);
            imageNotLoading();
          },

Any assistance would be appreciated.

How to add object key after comparing two arrays of objects

I have two arrays of objects.
One array represents list of all countries:

const allCountries = [
  {
    name: 'Albania',
    code: 'AL',
    'alpha-3': 'ALB',
    numeric: '8',
  },
  {
    name: 'Algeria',
    code: 'DZ',
    'alpha-3': 'DZA',
    numeric: '12',
  },
  {
    name: 'Andorra',
    code: 'AD',
    'alpha-3': 'AND',
    numeric: '20',
  },
  {
    name: 'Angola',
    code: 'AO',
    'alpha-3': 'AGO',
    numeric: '24',
  },
  {
    name: 'Antigua and Barbuda',
    code: 'AG',
    'alpha-3': 'ATG',
    numeric: '28',
  },
  {
    name: 'Argentina',
    code: 'AR',
    'alpha-3': 'ARG',
    numeric: '32',
  },
];

The other array represents list of supported countries:

const supportedCountries = [
  {
    name: 'Algeria',
    code: 'DZ',
    'alpha-3': 'DZA',
    numeric: '12',
  },
  {
    name: 'Angola',
    code: 'AO',
    'alpha-3': 'AGO',
    numeric: '24',
  },
  {
    name: 'Argentina',
    code: 'AR',
    'alpha-3': 'ARG',
    numeric: '32',
  },
];

What I needed is to create another array of countries with isSupported: true or isSupported: false added to allCountries array to be:

[
  {
    name: "Albania",
    code: "AL",
    "alpha-3": "ALB",
    numeric: "8",
    isSupported: false
  },
  {
    name: "Algeria",
    code: "DZ",
    "alpha-3": "DZA",
    numeric: "12",
    isSupported: true
  },
  ... 
];

My solution is, and it works fine:

const newSet = [];

allCountries.forEach((country) => {
  supportedCountries.forEach((b4b) => {
    if (country.code === b4b.code) {
      newSet.push({ ...country, isSupported: true });
    }
  });
  newSet.push({ ...country, isSupported: false });
});

const uniqueCountries = newSet.reduce((accumulator, current) => {
  if (!accumulator.find((item) => item.code === current.code)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

My question is, what would be the better/cleaner/neater solution for this?

How does a CORS unblocker work from client side?

As far as I know, websites that don’t have Access-Control-Allow-Origin cannot be fetched using XMLHTTPRequest from client side so this problem can be solved only from server side by adding * to Access-Control-Allow-Origin in the header section.

let url = 'https://tv.jordkris.com';
fetch(url).then(res => res.text())
.then((text) => {
  var parser = new DOMParser();
  var html = parser.parseFromString(text, "text/html");
  var target = document.getElementById('target');
  target.innerHTML = text;
})
.catch(err => console.error(err.message));
<div id="target"></div>

However, recently I came across a website that can perform CORS unblocking of a URL.

let url = 'https://corsproxy.io/?' + encodeURIComponent('https://tv.jordkris.com');
fetch(url).then(res => res.text())
.then((text) => {
  var parser = new DOMParser();
  var html = parser.parseFromString(text, "text/html");
  var target = document.getElementById('target');
  target.innerHTML = text;
})
.catch(err => console.error(err.message));
<div id="target"></div>

How does the website work so that it can unblock CORS from the client side?

(items.map is not a function) how can i solve this , someone please help me

import React, { useEffect, useState } from "react";
const Api = () => {
  const [items, setItems] = useState([]);
  const apiGet = () => {
    fetch("https:dummyjson.com/posts#")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);
        setItems(json);
      });
  };

  useEffect(() => {
    apiGet();
  }, []);
  return (
    <div>
      {" "}
      <ul>
        {" "}
        {items.posts.map((item) => (
          <li>{item.title} </li>
        ))}{" "}
      </ul>{" "}
    </div>
  );
};

export default Api;

I tried to target the property which contain the array but Still im getting this error , i don’t know how to fix it

My page works fine on VScode’s Live Server but not on local

When I previewing my pages with a Visual Studio Live Server everything works cool. But when I tried to open my index file from local, it didn’t show CSS or JSON.

When I open the local file I want the page to run fine and pull the required data from the JSON file. I tried change /questions.json to ./questions.json in code but doesn’t work.

React js -compiled with errors

Suddenly i got a compilation error after moving js files but i undo it it still
Here is my index.html code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>React App</title>
  </head>
  <body>
    <div id="roOt"></div>
  </body>
</html>

And Here is my Index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from "./componment/App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

and here is the fail img
Fail capture
i would be thankfull if you give me a hint .

hint or sloution of react

Grouping types based on mime type property inside object: Javascript

I am having the following object that is being sent as an object to a function,

const mimeTypes = {
  image: [".svg", ".png", ".gif", ".jpeg", ".jpg"],
  application: [".pdf", ".zip"],
  text: [".txt", ".csv"]
};

I need to transform the above object into another object, based on mime type,
The result should look like


const result = {
  "image/*": [".svg", ".png", ".gif", ".jpeg", ".jpg"],
  "application/zip": [".zip"],
  "application/pdf": [".pdf"],
  "text/*": [".txt", ".csv"]
};

Here application level types are handled with their mime types, rest of the types are generic ones and follow image/* or text/*

How do I transform this? I am a beginner to this

function transform(obj){
   let res = {};
   for (const key in obj) {
    if (obj.key === 'image') {
      res["image/*"] = obj.image;
    }
    if (obj.key === 'text') {
      res["text/*"] = obj.text;
    }
   }
   return res;
}

When just const input = { text: [".txt", ".csv"]} is passed, the resultant object should only have text related object. In this case the result should have text related object like
const result = { "image/*":text: [".txt", ".csv"] };

Is there a more simpler and compact version of this?

How to center SVG in nextJs with viewbox

I am building a preloader using nextjs, it’s a timed benzene animation that plays out entirely before the homepage appears. The issue that I am dealing with comes from both ways that I try to implement this preloader. First, when I set the viewbox attributes in the component as shown below, I receive an error.

"use client";
import React, { useEffect, useState } from 'react';
import './Preloader.module.css';


const Preloader = () => {
  
  const viewBox = `${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`;

  return (
    <div className='preloader-div'>
      <svg viewBox={viewBox} width="100%" height="100%">
        ...
      </svg>
    </div>
  );
};

export default Preloader;

This is the error I receive…

error - ReferenceError: window is not defined
    at Preloader (./src/app/preloader/preloader.tsx:13:21)
   6 | const Preloader = () => {
   7 |   
>  8 |   const viewBox = `${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`;

So I did some research, and there are a few ways that I would be able to fix this, and the one that worked the best was to use useEffect. It does remove the error but the issue now comes from my svg starting in the top left of the browser for about the first second of the page loading, but then when useEffect runs, it gets moved to the center.

"use client";
import React, { useEffect, useState } from 'react';
import './Preloader.module.css';


const Preloader = () => {
  
  const [viewBox, setViewBox] = useState('');

  useEffect(() => {
    setViewBox(`${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`);
  }, []);


  return (
    <div className='preloader-div'>
      <svg viewBox={viewBox} width="100%" height="100%">
        ...
      </svg>
    </div>
  );
};

export default Preloader;

How would I remove this error but also have my svg centered from the initial loading of the page?