nft.storage icon indicating copy to clipboard operation
nft.storage copied to clipboard

client.store() failed with 'TypeError [ERR_INVALID_THIS]: Value of "this" must be of type URLSearchParams'

Open ronmegini opened this issue 1 year ago • 5 comments

I am using nft.storage module for javascript version 7.0.3 and trying to upload ERC1155 metadata to ipfs.

Full code snippet:

const { NFTStorage, Blob } = require('nft.storage')
require("dotenv").config();

// Fetch image from URL
async function getImage(imageURL) {
  console.log("start to pull image")
  const r = await fetch(imageURL)
  if (!r.ok) {
    throw new Error(`error fetching image: [${r.statusCode}]: ${r.status}`)
  }
  console.log("Finish pull image")
  const arrayBuffer = await r.arrayBuffer();
  const blob = new Blob([arrayBuffer]);
  return blob;
}

// Format json and upload to nftStorage via API
async function deployMetadata(contractName, description, imageURL) {
  const API_KEY = process.env.NFT_STORAGE_API_KEY
  const imageBlob = await getImage(imageURL)
  const nft = {
    image: imageBlob, // use image Blob as `image` field
    name: contractName,
    description: description
  }
  const client = new NFTStorage({ token: API_KEY })
  const metadata = await client.store(nft)
  console.log('NFT data stored!')
  return metadata.url
}

module.exports = deployMetadata;

The problem occur when I'm calling client.store(nft) function and gets this exception: "TypeError [ERR_INVALID_THIS]: Value of "this" must be of type URLSearchParams".

nft variable contains:

{
  image: Blob { size: 13432, type: '' },
  name: 'test3',
  description: 'test the api'
}

client object:

NFTStorage {
  token: '********',
  endpoint: URL {
    href: 'https://api.nft.storage/',
    origin: 'https://api.nft.storage',
    protocol: 'https:',
    username: '',
    password: '',
    host: 'api.nft.storage',
    hostname: 'api.nft.storage',
    port: '',
    pathname: '/',
    search: '',
    searchParams: URLSearchParams {},
    hash: ''
  },
  rateLimiter: [Function (anonymous)],
  did: undefined
}

ronmegini avatar May 22 '23 16:05 ronmegini

I believe this is a bug because even when I'm using the exact script described in this blog, I get the same exception.

Code:

import { NFTStorage } from 'nft.storage'
import * as dotenv from 'dotenv'

// Load .env file varibles to the environment
dotenv.config()

// read the API key from an environment variable. You'll need to set this before running the example!
const API_KEY = process.env.NFT_STORAGE_API_KEY

// For example's sake, we'll fetch an image from an HTTP URL.
// In most cases, you'll want to use files provided by a user instead.
async function getExampleImage() {
  const imageOriginUrl = "https://user-images.githubusercontent.com/87873179/144324736-3f09a98e-f5aa-4199-a874-13583bf31951.jpg"
  const r = await fetch(imageOriginUrl)
  if (!r.ok) {
    throw new Error(`error fetching image: [${r.statusCode}]: ${r.status}`)
  }
  return r.blob()
}

async function storeExampleNFT() {
  const image = await getExampleImage()
  const nft = {
    image, // use image Blob as `image` field
    name: "Storing the World's Most Valuable Virtual Assets with NFT.Storage",
    description: "The metaverse is here. Where is it all being stored?",
    properties: {
      type: "blog-post",
      origins: {
        http: "https://blog.nft.storage/posts/2021-11-30-hello-world-nft-storage/",
        ipfs: "ipfs://bafybeieh4gpvatp32iqaacs6xqxqitla4drrkyyzq6dshqqsilkk3fqmti/blog/post/2021-11-30-hello-world-nft-storage/"
      },
      authors: [{ name: "David Choi" }],
      content: {
        "text/markdown": "The last year has witnessed the explosion of NFTs onto the world’s mainstage. From fine art to collectibles to music and media, NFTs are quickly demonstrating just how quickly grassroots Web3 communities can grow, and perhaps how much closer we are to mass adoption than we may have previously thought. <... remaining content omitted ...>"
      }
    }
  }

  const client = new NFTStorage({ token: API_KEY })
  const metadata = await client.store(nft)

  console.log('NFT data stored!')
  console.log('Metadata URI: ', metadata.url)
}

storeExampleNFT()

Exception:

node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_INVALID_THIS]: Value of "this" must be of type URLSearchParams
    at new NodeError (node:internal/errors:399:5)
    at Proxy.has (node:internal/url:501:13)
    at Proxy.<anonymous> (file:///private/tmp/debug-metadata-creation/node_modules/@web-std/fetch/src/headers.js:140:44)
    at new Request (file:///private/tmp/debug-metadata-creation/node_modules/@web-std/fetch/src/request.js:105:38)
    at file:///private/tmp/debug-metadata-creation/node_modules/@web-std/fetch/src/index.js:40:19
    at new Promise (<anonymous>)
    at fetch (file:///private/tmp/debug-metadata-creation/node_modules/@web-std/fetch/src/index.js:38:9)
    at pRetry.retries (file:///private/tmp/debug-metadata-creation/node_modules/nft.storage/src/lib.js:196:32)
    at async RetryOperation._fn (/private/tmp/debug-metadata-creation/node_modules/p-retry/index.js:50:12) {
  code: 'ERR_INVALID_THIS'
}

Node.js v20.0.0

ronmegini avatar May 23 '23 09:05 ronmegini

Update: Same problem occur with the new 7.1.0 version

ronmegini avatar May 23 '23 10:05 ronmegini

I just ran into this when trying to upgrade to node v20. It happens with node 20 and not with node 18 or below. But NFT.STORAGE should fix this issue for Node v20.

moazzamgodil avatar Jun 02 '23 00:06 moazzamgodil

Fixed by downgrade node to version 18.

nft.storage package should support node 20. From my investigation I found out that the bug occur when nft.storage tries to use @web-std/fetch function which creates a Request and expect to get URLSearchParams as an input.

It also happens for other modules which use @web-std/fetch such as "web3.storage": "^4.5.4".

ronmegini avatar Jun 03 '23 12:06 ronmegini

Not having this problem on my devops pc for Linux v18 node, having it on windows v18 node with same working codebase in Linux.

Hiturunk avatar Jun 27 '23 04:06 Hiturunk

If you still need support, please re-open this issue and provide more detail. Thanks!

elizabeth-griffiths avatar Apr 25 '24 12:04 elizabeth-griffiths