Code Monkey home page Code Monkey logo

js-sdk's Introduction

Lit Protocol Javascript/Typescript SDK V5.0.0




The Lit JavaScript SDK provides developers with a framework for implementing Lit functionality into their own applications. Find installation instructions in the docs to get started with the Lit SDK based on your use case:

https://developer.litprotocol.com/SDK/Explanation/installation



This new V3 SDK is written in Typescript and is a complete rewrite of the old SDK. It is much more modular and easier to use, and has a much smaller bundle size.

ChangeLog: All notable changes to this project will be documented in this file.

Quick Start

NodeJS Exclusive

Removed browser-specific methods, e.g., checkAndSignAuthSig

yarn add @lit-protocol/lit-node-client-nodejs

or..

Isomorphic Implementation

Operable in both Node.js and the browser

yarn add @lit-protocol/lit-node-client

Packages

📝 If you're looking to use the Lit SDK, you're probably all set with just the lit-node-client .
Get started with interacting with Lit network!

Package Category Download
@lit-protocol/lit-node-client-nodejs lit-node-client-nodejs
@lit-protocol/lit-node-client lit-node-client

If you're a tech-savvy user and wish to utilize only specific submodules that our main module relies upon, you can find individual packages listed below. This way, you can import only the necessary packages that cater to your specific use case::

Package Category Download
@lit-protocol/access-control-conditions access-control-conditions
@lit-protocol/auth-helpers auth-helpers
@lit-protocol/bls-sdk bls-sdk
@lit-protocol/constants constants
@lit-protocol/contracts-sdk contracts-sdk
@lit-protocol/core core
@lit-protocol/crypto crypto
@lit-protocol/ecdsa-sdk ecdsa-sdk
@lit-protocol/encryption encryption
@lit-protocol/logger logger
@lit-protocol/misc misc
@lit-protocol/nacl nacl
@lit-protocol/pkp-base pkp-base
@lit-protocol/pkp-client pkp-client
@lit-protocol/pkp-cosmos pkp-cosmos
@lit-protocol/pkp-ethers pkp-ethers
@lit-protocol/pkp-sui pkp-sui
@lit-protocol/pkp-walletconnect pkp-walletconnect
@lit-protocol/sev-snp-utils-sdk sev-snp-utils-sdk
@lit-protocol/types types
@lit-protocol/uint8arrays uint8arrays
@lit-protocol/auth-browser auth-browser
@lit-protocol/misc-browser misc-browser

API Doc

Old APIs Doc(s)

Contributing and developing to this SDK

Prerequisite

  • node (v18.0.0)

Recommended

Quick Start

The following commands will help you start developing with this repository.

First, install the dependencies via yarn:

yarn

Building

You can build the project with the following commands:

// for local development - It stripped away operations that don't matter for local dev
yarn build:dev

// you should never need to use yarn build unless you want to test or publish it
yarn build

Running Test Apps

The test apps are configured to automatically import all modules and expose all module functions. For browsers, you can access these functions using window.LitJsSdk_<package_name>.<function_name>

// Running apps...
// react: http://localhost:4003
// nodejs: in the terminal
yarn apps

or running individually

// react
yarn nx run react:serve

// nodejs
yarn nx run nodejs:serve

Run unit tests

yarn test:unit

Run E2E tests


// -- web
yarn test:e2e:web

// -- node
yarn test:e2e:node

Advanced

Creating a new library

By default, NX provides a command to generate a library nx generate @nx/js:library. However, it doesn't have an esbuild built-in so that we've created a custom tool that modify the build commands.

yarn gen:lib <package-name> <tag>

Create a new react demo app using the Lit JS SDK

yarn tools --create --react contracts-sdk --demo

Deleting a package or app

// delete an app from ./app/<app-name>
yarn delete:app <app-name>

// delete a package from ./packages/<package-name>
yarn delete:package <package-name>

Building

yarn build

Building target package

yarn nx run <project-name>:build

Building Local Changes

During development you may wish to build your code changes in packages/ in a client application to test the correctness of the functionality.

If you would like to establish a dependency between packages within this monorepo and an external client application that consumes these packages:

  1. Run npm link at the root of the specific package you are making code changes in.
cd ./packages/*/<package-name>
npm link
  1. Build the packages with or without dependencies
yarn build
# or
yarn nx run lit-node-client-nodejs:build --with-deps=false
  1. In the client application, run npm link <package> --save to ensure that the package.json of the client application is updated with a file: link to the dependency. This effectively creates a symlink in the node_modules of the client application to the local dependency in this repository.
cd path/to/client-application
npm link <package> --save

Having done this setup, this is what the development cycle looks like moving forward:

  1. Make code change
  2. Rebuild specific package
  3. Rebuild client application.

Publishing

You must have at least nodejs v18 to do this.

  1. Install the latest packages with yarn install

  2. Run yarn bump to bump the version

  3. Build all the packages with yarn build

  4. Run the unit tests with yarn test:unit & e2e node tests yarn test:e2e:nodejs locally & ensure that they pass

  5. Update the docs with yarn gen:docs --push

  6. Finally, publish with the @cayenne tag: yarn publish:cayenne

  7. Commit these changes "Published version X.X.X"

Publishing to Serrano / Jalapno

git checkout serrano
yarn bump
yarn build
yarn node ./tools/scripts/pub.mjs --tag serrano-jalapeno

Testing

Quick Start on E2E Testing

The following will serve the react testing app and launch the cypress e2e testing after

yarn test:e2e:web
or
yarn test:e2e:node

Environments

There are currently three environments can be tested on, each of which can be generated from a custom command, which would automatically import all the libraries in ./packages/*. The UI of HTML & React are visually identical but they are using different libraries.

Environment Generate Command Test Location
React yarn gen:react http://localhost:4003
NodeJs yarn gen:nodejs yarn nx run nodejs:serve

Unit Tests

yarn test:unit

E2E Testing with Metamask using Cypress (for Browser)

React

// E2E React
yarn tools --test --e2e react

Testing with a Local Lit Node

First, deploy your Lit Node Contracts, since the correct addresses will be pulled from the ../lit-assets/blockchain/contracts/deployed-lit-node-contracts-temp.json file.

Set these two env vars:

export LIT_JS_SDK_LOCAL_NODE_DEV="true"
export LIT_JS_SDK_FUNDED_WALLET_PRIVATE_KEY="putAFundedPrivateKeyOnChronicleHere"

Run:

yarn update:contracts-sdk --fetch
yarn update:contracts-sdk --gen
yarn build:packages

To run manual tests:

 yarn nx run nodejs:serve

ENV Vars

  • LIT_JS_SDK_GITHUB_ACCESS_TOKEN - a github access token to get the contract ABIs from a private repo
  • LIT_JS_SDK_LOCAL_NODE_DEV - set to true to use a local node
  • LIT_JS_SDK_FUNDED_WALLET_PRIVATE_KEY - set to a funded wallet on Chronicle Testnet

Dockerfile

...coming soon

Other Commands

Interactive graph dependencies using NX

yarn graph

FAQs & Common Errors

(React) Failed to parse source map from

In your React package.json, add GENERATE_SOURCEMAP=false to your start script

eg.

  "scripts": {
    "start": "GENERATE_SOURCEMAP=false react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
Web bundling using esbuild

It’s currently using a custom plugin @websaam/nx-esbuild which is a fork from @wanews/nx-esbuild

"_buildWeb": {
    "executor": "@websaam/nx-esbuild:package",
    "options": {
      "banner": {
        "js": "import { createRequire } from 'module';const require = createRequire(import.meta.url);"
      },
      "globalName": "LitJsSdk_CoreBrowser",
      "outfile":"dist/packages/core-browser-vanilla/core-browser.js",
      "entryPoints": ["./packages/core-browser/src/index.ts"],
      "define": { "global": "window" },
      "plugins":[
        {
          "package": "esbuild-node-builtins",
          "function": "nodeBuiltIns"
        }
      ]
    }
  }
Reference Error: crypto is not defined
import crypto, { createHash } from 'crypto';
Object.defineProperty(globalThis, 'crypto', {
  value: {
    getRandomValues: (arr: any) => crypto.randomBytes(arr.length),
    subtle: {
      digest: (algorithm: string, data: Uint8Array) => {
        return new Promise((resolve, reject) =>
          resolve(
            createHash(algorithm.toLowerCase().replace('-', ''))
              .update(data)
              .digest()
          )
        );
      },
    },
  },
});
error Command failed with exit code 13.

Make sure your node version is above v18.0.0

js-sdk's People

Contributors

a1ttech avatar aaryan-r-s avatar ansonhkg avatar bntzio avatar cairomassimo avatar dashkash54 avatar eengineer1 avatar federicoamura avatar furkanakal avatar garandor avatar gilbert avatar glitch003 avatar gtc6244 avatar hwrdtm avatar joshlong145 avatar maximushaximus avatar rahul-ramesh avatar saike avatar sarahzdev avatar uji avatar vacekj avatar yhl125 avatar ylmin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

js-sdk's Issues

Module not found error in browser

I have followed the installation guide after installing the package and running the app I faced these errors in the browser:

Module not found: Can't resolve 'net'
   6 | const http = require('http');
   7 | const https = require('https');
>  8 | const net = require('net');
     |             ^^^^^^^^^^^^^^
   9 | const tls = require('tls');
  10 | const { createHash } = require('crypto');
  11 |

https://nextjs.org/docs/messages/module-not-found
console.error @ client.js:1
push.[project]/node_modules/next/dist/client/setup-hydration-warning.js [client] (ecmascript).window.console.error @ setup-hydration-warning.js:18
handleErrors @ hot-dev-client.js:141
processMessage @ hot-dev-client.js:219
(anonymous) @ hot-dev-client.js:55
handleMessage @ websocket.js:56
Show 6 more frames
Show less
client.js:1 ./node_modules/ws/lib/websocket-server.js:9:12
Module not found: Can't resolve 'tls'
   7 | const https = require('https');
   8 | const net = require('net');
>  9 | const tls = require('tls');
     |             ^^^^^^^^^^^^^^
  10 | const { createHash } = require('crypto');
  11 |
  12 | const extension = require('./extension');

To Reproduce
Steps to reproduce the behavior:

  1. yarn add @lit-protocol/lit-node-client
  2. import * as LitJsSdk from "@lit-protocol/lit-node-client";
  3. inside the useEffect :
const client = new LitJsSdk.LitNodeClient({
  litNetwork: 'cayenne',
});

await client.connect();

Some tests failed

  1. yarn build failed
$ yarn build
yarn run v1.22.19
$ yarn build:packages
$ yarn tools check --no-empty-directories=true && yarn tools fixTsConfig && yarn reset && yarn tools --build --packages && yarn tools --postBuild && yarn tools --setup-local-dev && yarn postBuild:mapDepsToDist && yarn gen:readme && yarn build:verify
$ yarn node ./tools/scripts/tools.mjs check --no-empty-directories=true
$ yarn node ./tools/scripts/tools.mjs fixTsConfig
error Command failed.
Exit code: 13
Command: /Users/???/.nvm/versions/node/v16.10.0/bin/node
Arguments: ./tools/scripts/tools.mjs fixTsConfig
Directory: /Users/???/code/js-sdk
Output:

info Visit https://yarnpkg.com/en/docs/cli/node for documentation about this command.
error Command failed with exit code 13.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 13.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 13.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

  1. lit-build.config.json file is missing for yarn tools --build --packages --async, may I have the file in order to build the project?

  1. some tests failed with yarn run test:unit, mostly due to timeout.

NX Ran target test for 21 projects (10m)

✔    15/21 succeeded [0 read from cache]

✖    6/21 targets failed, including the following:
     - nx run auth-browser:test
     - nx run crypto:test
     - nx run lit-auth-client:test
     - nx run contracts-sdk:test
     - nx run pkp-ethers:test
     ...and 1 more...

No known conditions for "./cid" specifier in "multiformats" package

Is there an existing issue for this?

  • I have searched the existing issues

SDK version

5.0.0

Lit Network

All

Description of the bug/issue

I'm trying to use the SDK in a project with Remix + Vite. I get the error:

✘ [ERROR] No known conditions for "./cid" specifier in "multiformats" package [plugin vite:dep-pre-bundle]

The plugin "vite:dep-pre-bundle" was triggered by this import

    ../node_modules/@lit-protocol/contracts-sdk/src/lib/contracts-sdk.js:34:18:
      34 │     CID = require('multiformats/cid');

The error is triggered by this line in the contracts SDK package.

I'm not sure why this is the only dependancy imported with require(). I use the CID package in my project as well, where it is imported with:

import { CID } from 'multiformats/cid'

This error has only appeared after migrating Remix from their built-in bundler to Vite. However, while using this package before the migration the console was constantly spammed with "CID not found", so it looks like the import wasn't working in the first place.

Severity of the bug

Blocking

Steps To Reproduce

  1. Create a Remix + Vite project (you may also be able to reproduce this on any framework using Vite, but I haven't tried)
  2. Import the SDK and build
  3. Error triggered

Link to code

No response

Anything else?

No response

Error with humanizeAccessControlConditions() when using ERC20 tokens

**Before reporting, I have already ***

Describe the bug
When calling humanizeAccessControlConditions() with an ERC20 token, an exception is thrown.

To Reproduce
Code sample:

import { humanizeAccessControlConditions } from '@lit-protocol/lit-node-client';

function Component () {
  useEffect((async () => {
    const result = await humanizeAccessControlConditions({
      chains: ['goerli'],
      permanent: true,
      authSigTypes: ['ethereum'],
      unifiedAccessControlConditions: [
        {
          chain: 'goerli',
          method: 'balanceOf',
          parameters: [':userAddress'],
          conditionType: 'evmBasic',
          contractAddress: '0x5b8B8C9aD976aFCAd24fd6CF424294d372c190Ac',
          returnValueTest: {
            value: '100000000000000000000',
            comparator: '>='
          },
          standardContractType: 'ERC20'
        }
      ]
    });
  })();
  , []);
}

Expected behavior
Should return a human-friendly sentence of ERC20

Environment:

  • Lit SDK version: 2.2.47 (latest)

Additional info
This is the line that blows up: https://github.com/LIT-Protocol/js-sdk/blob/master/packages/misc/src/lib/misc.ts#L479

This is the error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')
    at new Interface (interface.js:57:23)
    at getInterface (index.js:625:1)
    at new BaseContract (index.js:481:52)
    at new Contract (index.js:899:8)
    at decimalPlaces (misc.js:348:1)
    at eval (humanizer.js:182:1)
    at Array.map (<anonymous>)
    at humanizeEvmBasicAccessControlConditions (humanizer.js:98:1)
    at eval (humanizer.js:399:1)
    at Array.map (<anonymous>)
    at humanizeUnifiedAccessControlConditions (humanizer.js:380:1)
    at humanizeAccessControlConditions (humanizer.js:469:1)
    at eval (TokenGateOption.tsx:47:36)

I believe the issue is that the ABI's are imported with import which is async, and when I log the value, it is a promise, not the resolved JSON data:

const ABI_ERC20 = import('./lib/abis/ERC20.json');

process not defined in node_modules/util/util.js

**Before reporting, I have already ***

Describe the bug
I am getting this error- util.js:109 Uncaught (in promise) ReferenceError: process is not defined
at node_modules/util/util.js (util.js:109:1)
at __require2 (chunk-XBCBYTQI.js?v=4f83186a:19:50)
at bls-sdk.ts:248:11

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • Lit SDK version (including the network (ie, "serrano") if different, and type - browser or backend)
  • Node version
  • Framework (React, Vue, Angular, Svelte - just Plain HTML!, etc)
  • Specific tooling (Webpack, Vite, browserify, etc)

Additional info
Add any other context about the problem here.

File uses global instead of globalThis

Is there an existing issue for this?

  • I have searched the existing issues

SDK version

3.0.32, but issue exists on master

Lit Network

N/A, trying to bundle package for browser

Description of the bug/issue

Can't find variable: global
../../node_modules/@lit-protocol/auth-browser/src/lib/chains/eth.js

which points to this line

Severity of the bug

Can't bundle for browser in a create-react-app

Steps To Reproduce

Using globalThis instead of global fixes the problem. The rest of the file also uses globalThis, so this would maintain consistency.

Link to code

No response

Anything else?

No response

Errors with the React sample app

I've followed the README.me

yarn
yarn build
yarn nx run react:serve

Notes: node version is v18.19.0, as v18.0.0 didn't work for one of the dependencies

And I got the following errors in the log

Nans-MacBook-Pro-14:js-sdk nanjiang$ yarn nx run react:serve
yarn run v1.22.19
$ 'Lit Protocol/js-sdk/node_modules/.bin/nx' run react:serve

> nx run react:serve

<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:4003/, http://[::1]:4003/
<i> [webpack-dev-server] 404s will fallback to '/index.html'

>  NX  Web Development Server is listening at http://localhost:4003/

Entrypoint main = runtime.js vendor.js main.js 3 auxiliary assets
Entrypoint polyfills = runtime.js polyfills.js 2 auxiliary assets
Entrypoint styles = runtime.js styles.css styles.js 2 auxiliary assets
chunk (runtime: runtime) main.js (main) 2.89 MiB [initial] [rendered]
chunk (runtime: runtime) node_modules_lit-protocol_accs-schemas_esm_schemas_LPACC_ATOM_json.js 693 bytes [rendered]
chunk (runtime: runtime) node_modules_lit-protocol_accs-schemas_esm_schemas_LPACC_EVM_BASIC_json.js 1.05 KiB [rendered]
chunk (runtime: runtime) node_modules_lit-protocol_accs-schemas_esm_schemas_LPACC_EVM_CONTRACT_json.js 1.57 KiB [rendered]
chunk (runtime: runtime) node_modules_lit-protocol_accs-schemas_esm_schemas_LPACC_SOL_json.js 924 bytes [rendered]
chunk (runtime: runtime) node_modules_nanoid_index_browser_js.js 1.14 KiB [rendered]
chunk (runtime: runtime) polyfills.js (polyfills) 508 KiB [initial] [rendered]
chunk (runtime: runtime) runtime.js (runtime) 35.8 KiB [entry] [rendered]
chunk (runtime: runtime) styles.css, styles.js (styles) 188 KiB (javascript) 3.17 KiB (css/mini-extract) [initial] [rendered]
chunk (runtime: runtime) vendor.js (vendor) (id hint: vendor) 11.2 MiB [initial] [rendered] split chunk (cache group: vendor) (name: vendor)
chunk (runtime: runtime) vendors-node_modules_multiformats_src_cid_js.js (id hint: vendors) 37.2 KiB [rendered] reused as split chunk (cache group: defaultVendors)
chunk (runtime: runtime) vendors-node_modules_simplewebauthn_browser_dist_bundle_index_js.js (id hint: vendors) 12.9 KiB [rendered] reused as split chunk (cache group: defaultVendors)
chunk (runtime: runtime) vendors-node_modules_walletconnect_modal-ui_dist_index_js.js (id hint: vendors) 345 KiB [rendered] reused as split chunk (cache group: defaultVendors)
chunk (runtime: runtime) vendors-node_modules_walletconnect_modal_dist_index_js.js (id hint: vendors) 21.4 KiB [rendered] reused as split chunk (cache group: defaultVendors)

WARNING in ../../packages/pkp-ethers/src/index.ts 8:0-315
export 'SupportedETHSigningMethods' (reexported as 'SupportedETHSigningMethods') was not found in './lib/pkp-ethers-types' (module has no exports)

ERROR in ../../dist/packages/contracts-sdk/src/lib/contracts-sdk.js 446:72-99
Module not found: Error: Package path ./cid is not exported from package Lit Protocol/js-sdk/node_modules/multiformats (see exports field in Lit Protocol/js-sdk/node_modules/multiformats/package.json)

webpack compiled with 1 error and 1 warning (dbf6066eeb0d9897)
No errors found.

And got the page like this

Screenshot 2024-02-19 at 20 20 01

Docker image

Please provide a Docker image, where you can interact with the SDK. Dependency issues make installation difficult.

[Closing soon] encrypt-decrypt-react-demo failing.

Hi there,

First of all, thanks for maintaining such a great project 🚀
I'm trying to take my first steps, and wanted to try out the encrypt-decrypt-react-demo as a starting point.

I actually tried this example project first https://github.com/debbly/IPFS-lit, but that failed due to some outdated dependencies.

Before reporting, I have already

Describe the bug

I'm running the "encrypt-decrypt-react"-demo, from here.
After installing and running the demo, i'm hitting this error when clicking the "Encrypt & Decrypt String"-Button:

caught (in promise) TypeError: this.signer.request is not a function
    at m.request (tslib.es6.js:218:1)
    at Web3Provider.jsonRpcFetchFunc (web3-provider.ts:96:1)
    at Web3Provider.send (web3-provider.ts:167:1)
    at Web3Provider.listAccounts (json-rpc-provider.ts:497:1)
    at connectWeb3 (eth.ts:381:1)
    at async checkAndSignEVMAuthMessage (eth.ts:456:1)
    at async App.js:122:1
    at async benchmark (utils.js:3:1)
    at async go (App.js:121:1)

To Reproduce
Steps to reproduce the behavior:

  1. Clone this repo
  2. cd to /apps/demo-encrypt-decrypt-react
  3. npm i
  4. npm start
  5. Click "Encypt & Decrypt String"
  6. Error appears in browser console.

Expected behavior
I was expecting some soft of Wallet-Login to pop up.
Judging by the logs, the app connects to the lit-network just fine, and fails afterwards.

The signature problem on Integrating with Ceramic

Description

I'm trying to approve for Lit Protocol and Ceramic with just one signature. I've managed to do so, but there might be some issues with my solution. I'll describe my problems here and discuss if there's a better approach, or whether it's possible to optimize the code of Lit or Ceramic to better address these issues.

Technical Information

My approach is as follows: first, I call Ceramic's authorization, with the code as below:

const accountId = await getAccountId(ethProvider, address)
      
const authMethod = await getAuthMethod(ethProvider, accountId)
console.log("[AuthCeramic] Authorize", authMethod)

session = await DIDSession.authorize(authMethod, {resources: ["ceramic://*"]})

After the user signs, they get a session as a login credential.
In Lit Protocol, similar to session, there's a data structure called AuthSig as a login credential. The structure of AuthSig is as follows:

interface AuthSig {
    sig: any; // Data after signing
    derivedVia: string; // Generally "web3.eth.personal.sign"
    signedMessage: string; // Data before signing
    address: string; // Signing address
}

Actually, session and AuthSig are somewhat interchangeable to a certain extent. Below is my conversion code:

async function getAuthSig(session, chainId = TargetChainId) {
  const {p, s} = session.cacao;
  const address = p.iss.split(":").pop();

  const message = new SiweMessage({
    domain: p.domain, address, 
    statement: p.statement,
    uri: p.aud,
    version: p.version,
    nonce: p.nonce,
    issuedAt: p.iat,
    expirationTime: p.exp,
    chainId: chainId.toString(),
    resources: p.resources,
  })

  return {
    address, derivedVia: "web3.eth.personal.sign",
    sig: s.s, signedMessage: message.toMessage(),
  } as AuthSig
}

Therefore, we can convert the session obtained after authorizing Ceramic into AuthSig and set it in LocalStorage, to authorize Lit:

const LitAuthSigKey = "lit-auth-signature"
const LitProviderKey = "lit-web3-provider"
const LitDefaultProvider = "metamask"

if (authSig) { // Set the default authSig in advance to avoid reconnecting and re-signing
  setLocalStorage(LitProviderKey, LitDefaultProvider)
  setLocalStorage(LitAuthSigKey, authSig)
}
authSig = await LitJsSdk.checkAndSignAuthMessage({
  chain: Chain
});

// Do some encryption/decryptions ....
const res = await LitJsSdk.decryptToString({
  authSig, chain: Chain, ...
}, lit)

This is my approach.

Solution Problem

There's a problem with the above solution, which is the issue of case sensitivity in the address in the signature information.

In the signature information of Ceramic, the address is converted to lowercase, here's an example:

localhost wants you to sign in with your Ethereum account:
0x66d369e52b1a7ee16.......f84025

Give this application access to some of your data on Ceramic

URI: did:key:z6Mkofcp......pnsDJ26j
Version: 1
Chain ID: 1
Nonce: 1CjSZZjMv2
Issued At: 2023-11-15T08:13:19.690Z
Expiration Time: 2023-11-22T08:13:19.690Z
Resources:
- ceramic://*

However, when we convert this signature into AuthSig and authenticate it in Lit, it says that the address does not conform to the EIP-55 format:
a1fbbbbb99c57d8ab7f2f9a94c12187
And this is the request data:
image

Therefore, I have to insert the following statement in the first section of the code to ensure that the address in the signature information is in EIP-55 format:

const accountId = await getAccountId(ethProvider, address)
accountId.address = address // Prevent the lowercase address

Only then can I successfully authorize Lit.
But after converting to EIP-55, the generated PKH-DID looks like this: did:pkh:eip155:1:0x66d369E52b1A7ee16D65e6a052745561C1f84025, which contains case sensitivity, and that's the problem:

  • If I keep the address lowercase, the generated DID is normal and conforms to the rules, but Lit cannot be successfully authorized.
  • If I retain the case sensitivity, I can successfully authorize Lit, but the generated DID will also retain the case sensitivity, but it seems to be able to be used normally in Ceramic.

Therefore, I wonder if there is a better solution, or whether it's possible to make some modifications to Ceramic or Lit to solve this problem?

I have also opened the same issue in Ceramic: ceramicnetwork/js-did#173

[Closing soon] Lit SDK is unable to regenerate the signature when the stored signature is expired

Describe the bug
Lit SDK cannot regenerate the signature when the stored signature is expired.
When the user contains an expired signature in local storage and calls LitJsSdk.checkAndSignAuthMessage, it is unable to regenerate a new signature and the following actions will be failed.

To Reproduce
Steps to reproduce the behavior:

  1. Calls LitJsSdk.checkAndSignAuthMessage with or without an expiration time (the expiration time is not working)
  2. Wait until the signature expired
  3. Calls LitJsSdk.checkAndSignAuthMessage again
  4. Errors occur

Expected behavior
The user should be prompted to sign again after the signature is expired.

Screenshots
Screenshot 2023-04-28 at 4 19 16 PM

Environment:

Additional info
In the function LitJsSdk.checkAndSignAuthMessage, the parameter expiration is ignored.

custom evm smart contract condition

**Before reporting, I have already ***

Describe the bug
I have deployed my smart contract on Goerli test network and have tested it to be sure of its functionality. Then i pass the evmContractCondition like below:

[ { "chain": "goerli", "contractAddress": "0x30E85Ee09Dbbf42A3FD91969e61d22c5e80F73dD", "functionName": "canDecrypt", "functionParams": [ "0x61727469636c65", "0x6b6a7a6c36637765316a773134617035766764377931326536686962616b7376", "0x6a6d757273716e726666386d646b74646a33757467696d743473627a696f67" ], "functionAbi": { "inputs": [ { "internalType": "bytes32", "name": "type_", "type": "bytes32" }, { "internalType": "bytes32", "name": "relation1_", "type": "bytes32" }, { "internalType": "bytes32", "name": "relation2_", "type": "bytes32" } ], "name": "canDecrypt", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, "returnValueTest": { "key": "", "comparator": "=", "value": "true" } } ]

But the problem is LIT cannot call the function to decrypt and gives me this error:

access_control_conditions_check_failed, Failed to get result from check_access_control_conditions

To Reproduce
Steps to reproduce the behavior:

  1. Encrypt your content with mentioned condition.
  2. Try to decrypt it.

Expected behavior
Be able to decrypt based on evm condition on Goerli test network.

Error executing ERC721 token operation with invalid token ID in LitJsSdk

The error message indicates that the code is encountering an execution revert when attempting to execute an ERC721 token operation with an invalid token ID.

From the code provided, it seems that it is using the LitJsSdk to connect to a Lit node and execute a script that attempts to sign an ECDSA signature using the Lit.Actions.signEcdsa() method. The parameters passed to this method include the toSign, publicKey, and sigName values, which are passed in from the jsParams object in the litNodeClient.executeJs() method.

To reproduce the issue, create a Next.js app with npx create-next-app@latest debug && cd debug utility, then install the lit-js-sdk package with npm install lit-js-sdk then add the code provided attached to a button.

  • @lit-protocol/lit-node-client version: "^2.0.40"
  • Network: "serrano"
  • Node version: v19.1.0
  • Framework: NextJS
  • Build tool: Webpack

Also note I have to use ts-ignore as typescript throws error that checkAndSignAuthMessage and LitNodeClient do not exist on LitJsSdk.

Executed:

import LitJsSdk from "lit-js-sdk";

async function execute() {
    // @ts-ignore
    const authSig = await LitJsSdk.checkAndSignAuthMessage({ chain: "ethereum" });
    // @ts-ignore
    const litNodeClient = new LitJsSdk.LitNodeClient({ litNetwork: "serrano" });
    await litNodeClient.connect();
    const litActionCode = `
    const go = async () => {  
      // this requests a signature share from the Lit Node
      // the signature share will be automatically returned in the HTTP response from the node
      // all the params (toSign, publicKey, sigName) are passed in from the LitJsSdk.executeJs() function
      const sigShare = await Lit.Actions.signEcdsa({ toSign, publicKey , sigName });
    };
    go();
    `;
    const signatures = await litNodeClient.executeJs({
      code: litActionCode,
      authSig,
      // all jsParams can be used anywhere in your litActionCode
      jsParams: {
        // this is the string "Hello World" for testing
        toSign: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100],
        publicKey:
            "0x02e5896d70c1bc4b4844458748fe0f936c7919d7968341e391fb6d82c258192e64",
        sigName: "sig1",
      },
    });
    console.log("signatures: ", signatures);
}

Error:

{
"message":"Error executing JS: Error: (code: 3, message: execution reverted: ERC721: invalid token ID, 
data: Some(String(\"0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000
00000000000000000000000000000000000000000000000000000184552433732313a20696e76616c696420746f6b656e204944
0000000000000000\")))\n    at async go (<user_provided_script>:6:24)",
"errorCode":"js_execution_error"
}

Screenshots
Screen Shot 2023-01-14 at 8 51 00 PM
Screen Shot 2023-01-14 at 8 51 19 PM
Screen Shot 2023-01-14 at 8 51 38 PM

Cayenne is evaluating Sepolia access conditions based on data from the Ethereum mainnet.

**Before reporting, I have already ***

Describe the bug
I am using the encryptString and decryptToString functions with unified access conditions for handling token-gated access to information. I did my testing on the Sepolia Testnet (chain ID: 11155111). However, I keep receiving errors indicating

"Invalid name: please ensure the contract and method you're calling exist! failed to decode empty bytes. if you're using jsonrpc this is likely due to jsonrpc returning 0x in case contract or method don't exist"

I tried switching my testing to the contracts deployed on Ethereum mainnet, and the error disappeared. I went further to run the test on the same Ethereum contract "0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401", while specifying the chain as Sepolia, and surprisingly the condition evaluation is working. Please see the unified access condition I used for verifying the Ethereum contract's condition on Sepolia network.

{ conditionType: "evmContract", contractAddress: '0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401', functionName: "balanceOf", functionParams: [':userAddress', '1234'], functionAbi: { type: "function", stateMutability: "view", outputs: [ { type: "uint256", name: "", internalType: "uint256", }, ], name: "balanceOf", inputs: [ { type: "address", name: "account", internalType: "address", }, { type: "uint256", name: "id", internalType: "uint256", }, ], }, chain: 'sepolia', returnValueTest: { key: "", comparator: '>', value: '0', }, }

This indicates that the Sepolia chain access conditions are evaluated based on the data from the Ethereum mainnet. I went down to the SDK code and the error seems to be coming from the Node instead of the client code.

To Reproduce
Steps to reproduce the behavior:
Please use the above unified access condition for encrypting and decrypting strings. Note that the contractAddress points to a contract on Ethereum.

Expected behavior
The above condition should evaluated to some meaningful result, while any contracts deployed on Sepolia should throw errors.

Environment:

  • Lit SDK version 3.2.2 for nodejs, on the "cayenne" network
  • Node version 18

The import @lit-protocol/lit-node-client doesn't work in Sveltekit. If you try to import this library in a Sveltekit project, the app throws a 500 error with ReferenceError: global/process is not defined

https://github.com/ChristianOConnor/lit-v2-svelte-integrate this is a demo app that demonstrates my problem.

I explained the problem in the readme:
Click "Lit Test" in the header and you will be directed to "Lit" where you'll get a 500 error. If you open the browser console (in either Firefox or Google Chrome), you will see "ReferenceError: global is not defined" as well as "Uncaught (in promise) ReferenceError: process is not defined."

Request for SPA-Friendly OAuth Redirection Mechanism in lit-auth-client

Issue Description:

I am currently using @lit-protocol/lit-auth-client@cayenne in a Single Page Application (SPA) built with React and React Router. I've noticed that the OAuth flow, particularly when using the GoogleProvider, causes a full page refresh during the redirection process. This behavior leads to the loss of in-memory state in my React application, which is not ideal for SPA architecture.

Technical Details:

The issue specifically arises in the signIn method within GoogleProvider.js, where window.location.assign is used for redirecting to the Google login page. Additionally, the authenticate method uses window.location.href.startsWith(this.redirectUri) to handle the callback from Google. These methods result in a full browser reload, which is contrary to the typical behavior in SPAs where navigation is handled by client-side routing without causing page reloads.

Suggested Enhancement:

I would like to request an enhancement in how the library handles OAuth redirects. Ideally, the redirection mechanism should be compatible with SPA norms, possibly by leveraging client-side routing methods that do not cause a full page reload. This change would significantly improve the user experience in SPAs and maintain the application state seamlessly through the authentication process.

Potential Solutions:

  1. Implement a redirection mechanism that integrates with client-side routing libraries like React Router.
  2. Provide a configuration option that allows developers to handle the redirection in a SPA-friendly manner.

Impact:

This enhancement would greatly benefit developers building SPAs with React (or similar frameworks) by aligning the OAuth flow with the core principles of SPAs. It would maintain the user experience continuity and state persistence across the authentication process.

Additional Context:

Here are some relevant snippets from the library where the full page refresh occurs:

  • GoogleProvider.js:
    • signIn method: window.location.assign(loginUrl);
    • authenticate method: window.location.href.startsWith(this.redirectUri);

Thank you for considering this request. I believe this enhancement will make the @lit-protocol/lit-auth-client library even more versatile and suitable for modern web application development.

Feature: Allow options for configuring pkp wallet singing implementation

Currently the implementation of https://github.com/LIT-Protocol/pkp-ethers does not allow for the lit action facilitating singing for the pkp wallet to be configured. Configuration of the options passed to executeJS should be possible to allow more sophisticated pkp relationships to be supported.

Create New Logging level uitlities

New Logging utilities within packages/misc will help create granular logging within sdk packages. the current log, logError, logWithRequestId and logErrorWithRequestId should be renamed to indicate it is logging under debug, changing the name to logDebug logDebugWithRequestId.

The following levels should be implemented.

  • Info
  • Trace
  • Warn

You can find current implementations of logging utilities below:
log
logWithRequestId

The above implementations use our logger package

see here for how we initialize a instance of our logging:

We should implement explicit logging utilities for the above categories supported in our logging package

  • logInfo
  • logInfoWithRequestId
  • logTrace
  • logTraceWithRequestId
  • logWarn
  • logWarnWithRequestId

[Closing soon] Webpack Issues

**Before reporting, I have already ***

Describe the bug

Using create-react-app and building with the js-sdk I'm running into some errors.

  1. Needing to add fallbacks for crypto and stream with crypto-browserify and stream-browserify
  2. Seeing a "Critical dependency: the request of a dependency is an expression" with the ecsda-sdk
To ignore, add // eslint-disable-next-line to the line before.

WARNING in ./node_modules/@lit-protocol/encryption/node_modules/@lit-protocol/crypto/node_modules/@lit-protocol/ecdsa-sdk/src/lib/ecdsa-sdk.js 312:16-55
Critical dependency: the request of a dependency is an expression

To Reproduce
Steps to reproduce the behavior:

  1. Create new React app with npx create-react-app my-app
  2. Update npm start to "GENERATE_SOURCEMAP=false react-scripts start" in package.json
  3. Add the following to node_modules/react-scripts/configs/webpack.config.js line 305
    resolve: {
      // This allows you to set a fallback for where webpack should look for modules.
      // We placed these paths second because we want `node_modules` to "win"
      // if there are any conflicts. This matches Node resolution mechanism.
      // https://github.com/facebook/create-react-app/issues/253
      modules: ['node_modules', paths.appNodeModules].concat(
        modules.additionalModulePaths || []
      ),
      fallback: {
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify")
      },
  1. Run npm install crypto-browserify stream-browserify
  2. See
WARNING in ./node_modules/@lit-protocol/encryption/node_modules/@lit-protocol/crypto/node_modules/@lit-protocol/ecdsa-sdk/src/lib/ecdsa-sdk.js 312:16-55
Critical dependency: the request of a dependency is an expression

Expected behavior
Hopefully no warnings 😅

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  "dependencies": {
    "@lit-protocol/lit-node-client": "^2.1.25",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "crypto-browserify": "^3.12.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "stream-browserify": "^3.0.0",
    "web-vitals": "^2.1.4"
},

Additional info
Add any other context about the problem here.

Yarn Upgrade Needed

Just a heads up, I required a yarn upgrade in order to install. I'm happy to put in a pull request if desired.

Getting the error message of "Invalid ipfsCid" when trying to decrypt the encrypted file uploaded to IPFS using the SDK

**Before reporting, I have already ***

Describe the bug
I am trying to create a really simple application that will simply encrypt and upload the file to IPFS then, download by decrypting it on the application.
As part of the encryption, I made it to specify which wallet address owner can access the file and I just use my own wallet address for that input, meaning, I should be able to decrypt it as well.

However, when I call the decrypt function after the encryption, I got the following error message in the console, and the decrypt didn't go through.

{
    "message": "Invalid ipfsCid",
    "errorCode": "InvalidArgumentException",
    "errorKind": "Validation"
}

To Reproduce
Steps to reproduce the behavior:

  1. Go to this github link
  2. Download the code and run npm install
  3. Copy and paste the contents of .env.example to .env.local
  4. Create a IPFS API key on Infura and obtain the required values INFURA_ID and INFURA_SECRET_KEY and assign them in .env.local
  5. Run the application by npm run dev and navigate to http://localhost:3000
  6. Simply copy paste your own metamask wallet address to the first input, upload a sample file, click on "Encrypt" button, click on "Decrypt" button.
  7. "Decrypt" should fail and you will be able to see the error messages in the console.

Expected behavior

Decryption should go through and the decrypted string should show up in the UI

Screenshots

Screenshot 2023-06-13 at 11 53 20 PM

Environment:

  • Lit SDK version (including the network (ie, "serrano") if different, and type - browser or backend) : 2.1.160
  • Node version: 18.0.0
  • Framework (React, Vue, Angular, Svelte - just Plain HTML!, etc): Next (13.4.5)
  • Specific tooling (Webpack, Vite, browserify, etc) : Nothing special

Additional info

Code snippet that I am facing issue with:

const FileEncryptDecryptForm = () => {
  const { encrypt, decrypt } = useLitFileProvider();

  const [authorizedWalletAddress, setAuthorizedWalletAddress] = useState<
    string | null
  >(null);
  const [file, setFile] = useState<File | null>(null);
  const [ipfsCid, setIpfsCid] = useState<string | null>(null);
  const [decryptedString, setDecryptedString] = useState<string | null>(null);

  const handleFileChange = async (file: File | null) => {
    setFile(file);
  };

  const handleEncryptClick = async () => {
    if (!authorizedWalletAddress) {
      alert('Please enter an authorized wallet address');
      return;
    }
    if (file && authorizedWalletAddress) {
      const ipfsCid = await encrypt(file, authorizedWalletAddress);
      console.log(ipfsCid);
      setIpfsCid(ipfsCid);
    }
  };

  const handleDecryptClick = async () => {
    if (ipfsCid) {
      // assume the ipfsCid from the encryption returned is assigned properly
      const decryptedString = await decrypt(ipfsCid);
      console.log(decryptedString);
      console.log(typeof decryptedString);
      setDecryptedString(
        typeof decryptedString === 'string'
          ? decryptedString
          : new TextDecoder().decode(decryptedString)
      );
    }
  };
};

Cannot find module './fetch.node'

Is there an existing issue for this?

  • I have searched the existing issues

SDK version

4.2.0

Lit Network

cayenne

Description of the bug/issue

Hi! Following the installation of the package (having attempted both the nodejs-exclusive and isomorphic versions), I attempted to initialize a lit node client, which resulted in the following error:

Import trace for requested module:
./node_modules/ipfs-utils/src/http/fetch.js
./node_modules/ipfs-utils/src/http.js
./node_modules/ipfs-http-client/cjs/src/files/rm.js
./node_modules/ipfs-http-client/cjs/src/files/index.js
./node_modules/ipfs-http-client/cjs/src/index.js
./node_modules/@lit-protocol/encryption/src/lib/encryption.js
./node_modules/@lit-protocol/encryption/src/index.js
./node_modules/@lit-protocol/lit-node-client-nodejs/src/index.js
./app/api/lit/route.ts
 ⨯ Error: Cannot find module './fetch.node'
    at webpackEmptyContext (/workspaces/Allegro/allegro/.next/server/app/api/lit/route.js:22:10)
    at eval (webpack-internal:///(rsc)/./node_modules/ipfs-utils/src/http/fetch.js:14:118)
    at (rsc)/./node_modules/ipfs-utils/src/http/fetch.js (/workspaces/Allegro/allegro/.next/server/vendor-chunks/ipfs-utils.js:70:1)
    at __webpack_require__ (/workspaces/Allegro/allegro/.next/server/webpack-runtime.js:33:43)
    at eval (webpack-internal:///(rsc)/./node_modules/ipfs-utils/src/http.js:2:37)
    at (rsc)/./node_modules/ipfs-utils/src/http.js (/workspaces/Allegro/allegro/.next/server/vendor-chunks/ipfs-utils.js:50:1)
    at __webpack_require__ (/workspaces/Allegro/allegro/.next/server/webpack-runtime.js:33:43)
    at eval (webpack-internal:///(rsc)/./node_modules/ipfs-http-client/cjs/src/lib/core.js:9:12)
    at (rsc)/./node_modules/ipfs-http-client/cjs/src/lib/core.js (/workspaces/Allegro/allegro/.next/server/vendor-chunks/ipfs-http-client.js:770:1)
    at __webpack_require__ (/workspaces/Allegro/allegro/.next/server/webpack-runtime.js:33:43)
    at eval (webpack-internal:///(rsc)/./node_modules/ipfs-http-client/cjs/src/lib/configure.js:5:12)
    at (rsc)/./node_modules/ipfs-http-client/cjs/src/lib/configure.js (/workspaces/Allegro/allegro/.next/server/vendor-chunks/ipfs-http-client.js:760:1)
    at __webpack_require__ (/workspaces/Allegro/allegro/.next/server/webpack-runtime.js:33:43)
    at eval (webpack-internal:///(rsc)/./node_modules/ipfs-http-client/cjs/src/bitswap/wantlist.js:6:17)
    at (rsc)/./node_modules/ipfs-http-client/cjs/src/bitswap/wantlist.js (/workspaces/Allegro/allegro/.next/server/vendor-chunks/ipfs-http-client.js:80:1) {
  code: 'MODULE_NOT_FOUND',
  page: '/api/lit'
}

I looked at /node_modules/ipfs-utils/src/http/fetch.js and found the following code:

let implName = './fetch.node'

if (typeof XMLHttpRequest === 'function') {
  // Electron has `XMLHttpRequest` and should get the browser implementation
  // instead of node.
  implName = './fetch.browser'
}

/** @type {fetchImpl} */
const fetch = require(implName)

module.exports = fetch

I understand the issue stems from ipfs-utils, but is there a workaround for this?

Severity of the bug

High, since I cannot even initialize the lit node client

Steps To Reproduce

  1. Create [email protected] app
  2. Install @lit-protocol/lit-node-client-nodejs
  3. Create a folder (ex. lit) under app/api directory and route.ts file
  4. Initialize lit node client as such:
export async function GET() {
  const litNodeClient = new LitJsSdk.LitNodeClientNodeJs({
    litNetwork: "cayenne",
  });
}
  1. Call GET /api/lit from page.tsx

Link to code

No response

Anything else?

No response

Missing `saveSigningCondition` function?

**Before reporting, I have already ***

Describe the bug

Currently I'm working with lit-js-sdk which I gather is v1 and wanted to check out v2 since the v1 will be deprecated sooner than later. In doing so, I can't seem to find the saveSigningCondition which is required for the JWT auth path.

1. Why do I need to call saveSigningCondition() before getSignedToken()? Shouldn’t the former just return a JWT?

The reason behind this separation is that saveSigningCondition() is a function that an admin/developer of a website will most likely call only once to set up the token-gating mechanism. The function getSignedToken() can then be called for every website visitor. You can view this as a 1-to-many relationship.

I do see a commit c262f04 adding it but I can't seem to find it now? (I'm still a newb at github it seems) but I'm pretty sure it's because packages/utils/src/lib/litNodeClient.ts doesn't exist on master anymore?

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
packages/utils/src/lib/litNodeClient.ts might need to be added back to master?

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • Lit SDK version (including the network (ie, "serrano") if different, and type - browser or backend)
  • Node version
  • Framework (React, Vue, Angular, Svelte - just Plain HTML!, etc)
  • Specific tooling (Webpack, Vite, browserify, etc)

Additional info
Add any other context about the problem here.

EIP-1271 Authsig failed 401 but the contract return 0x1626ba7e

I am encountering an access control error with the following details:

{
  "message": "Access control failed for Smart contract",
  "errorCode": "NodeContractAuthsigUnauthorized",
  "errorKind": "Validation",
  "status": 401,
  "details": [
    "validation error: Authsig failed for contract 0xd68fa46952bC848f8675a89383c5B074e1E22E40: EIP1271 Authsig failed"
  ]
}

However, when I call the isValidSignature function of the contract, it returns true.

To Reproduce
replit

Expected behavior
Since the contract returns 0x1626ba7e which means the signature is valid, it should work

Environment:

  • @lit-protocol/lit-node-client: "^2.2.61"
  • litNetwork: "serrano"
  • Node: v20.3.1

Breaks at decrypt - parsing SIWE message

It breaks here at decrypt:
try { decryptedString = await LitJsSdk.decryptToString( { authSig, accessControlConditions, ciphertext, dataToEncryptHash, chain: "ethereum", }, litNodeClient, ); } catch (e) { console.log(e); }

With error:

[Lit-JS-SDK v3.0.27] [ERROR] [core] [id: 168cd37033d2a] Something went wrong, internal id for request: lit_168cd37033d2a. Please provide this identifier with any support requests. Error is Error parsing SIWE message - validation error: SIWE validation failed: parser error: Session key expiration time is not set,Session key expiration time is not set

[Lit-JS-SDK v3.0.27] [ERROR] [core] [id: 168cd37033d2a] most common error: {"errorKind":"Parser","errorCode":"NodeSIWEMessageError","status":400,"message":"Error parsing SIWE message","correlationId":"lit_168cd37033d2a","details":["validation error: SIWE validation failed: parser error: Session key expiration time is not set","Session key expiration time is not set"]}

Wrong version of `multiformats` package breaking `@lit-protocol/contracts-sdk`

Describe the bug

Lit's build system is breaking bundling with vite/rollup. Specifically:

  • contract-sdk's multiformats version is set to ^9.7.1, but only in peerDependencies.
  • Other packages, such as core, have multiformats version set to ^12.1.3, likely coming from the root package.json (not familiar with how Nx works)
  • This causes, during vite bundling, the contracts-sdk code to attempt a require on multiformats v12.x, which is problematically an esm module, breaking the build with this error:
No known conditions for "./cid" specifier in "multiformats" package [plugin vite:dep-pre-bundle]

node_modules/@lit-protocol/contracts-sdk/src/lib/contracts-sdk.js:33:18:
      33 │     CID = require('multiformats/cid');

To Reproduce

See this minimal example repo.

Suggested Fix

Either update contracts-sdk to dynamic import the existing multiformats esm version (I can provide a pr), or move the older multiformats dependency from peerDependencies to dependencies.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.