From 98e838ba4095e98068a71f9929eac6586c889e61 Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:22:33 -0500 Subject: [PATCH 01/11] Summary - Renamed log and logWithRequestId - Reorganized log*/log*WithRequestId to be consistent - Added additional levels --- packages/misc/src/lib/misc.spec.ts | 14 +++ packages/misc/src/lib/misc.ts | 177 ++++++++++++++++++++++++++++- 2 files changed, 185 insertions(+), 6 deletions(-) diff --git a/packages/misc/src/lib/misc.spec.ts b/packages/misc/src/lib/misc.spec.ts index 5a44032992..1d1ea122e7 100644 --- a/packages/misc/src/lib/misc.spec.ts +++ b/packages/misc/src/lib/misc.spec.ts @@ -6,6 +6,7 @@ global.TextDecoder = TextDecoder; import { LitErrorKind, LIT_ERROR } from '@lit-protocol/constants'; import * as utilsModule from './misc'; +import exp from 'constants'; describe('utils', () => { /** @@ -29,6 +30,19 @@ describe('utils', () => { expect((console.log as any).mock.calls[2][0]).toBe('Error Message'); }); + it.only('should have debug, info, trace, warn, and error functions', () => { + expect(utilsModule.logDebug).toBeDefined(); + expect(utilsModule.logDebugWithRequestId).toBeDefined(); + expect(utilsModule.logInfo).toBeDefined(); + expect(utilsModule.logInfoWithRequestId).toBeDefined(); + expect(utilsModule.logTrace).toBeDefined(); + expect(utilsModule.logTraceWithRequestId).toBeDefined(); + expect(utilsModule.logWarn).toBeDefined(); + expect(utilsModule.logWarnWithRequestId).toBeDefined(); + expect(utilsModule.logError).toBeDefined(); + expect(utilsModule.logErrorWithRequestId).toBeDefined(); + }); + it('should get the most common string in an array', () => { const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8]; diff --git a/packages/misc/src/lib/misc.ts b/packages/misc/src/lib/misc.ts index 8837e14752..6221d77a74 100644 --- a/packages/misc/src/lib/misc.ts +++ b/packages/misc/src/lib/misc.ts @@ -228,7 +228,7 @@ export const getLoggerbyId = (id: string) => { * * @returns { void } */ -export const log = (...args: any): void => { +export const logDebug = (...args: any): void => { if (!globalThis) { // there is no globalThis, just print the log console.log(...args); @@ -256,7 +256,7 @@ export const log = (...args: any): void => { globalThis?.logger && globalThis?.logger.debug(...args); }; -export const logWithRequestId = (id: string, ...args: any) => { +export const logDebugWithRequestId = (id: string, ...args: any) => { if (!globalThis) { // there is no globalThis, just print the log console.log(...args); @@ -286,7 +286,35 @@ export const logWithRequestId = (id: string, ...args: any) => { globalThis.logManager.get(globalThis.logger.category, id).debug(...args); }; -export const logErrorWithRequestId = (id: string, ...args: any) => { +export const logInfo = (...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + + if (globalThis?.litConfig?.debug !== true) { + return; + } + // config is loaded, and debug is true + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && globalThis?.logger.info(...log); + } + + globalThis?.logger && globalThis?.logger.info(...args); +}; + +export const logInfoWithRequestId = (id: string, ...args: any) => { if (!globalThis) { // there is no globalThis, just print the log console.log(...args); @@ -309,11 +337,118 @@ export const logErrorWithRequestId = (id: string, ...args: any) => { while (logBuffer.length > 0) { const log = logBuffer.shift() ?? ''; globalThis?.logger && - globalThis.logManager.get(globalThis.logger.category, id).error(...log); + globalThis.logManager.get(globalThis.logger.category, id).info(...log); } globalThis?.logger && - globalThis.logManager.get(globalThis.logger.category, id).error(...args); + globalThis.logManager.get(globalThis.logger.category, id).info(...args); +}; + +export const logTrace = (...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + + if (globalThis?.litConfig?.debug !== true) { + return; + } + // config is loaded, and debug is true + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && globalThis?.logger.trace(...log); + } + + globalThis?.logger && globalThis?.logger.trace(...args); +}; + +export const logTraceWithRequestId = (id: string, ...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + + if (globalThis?.litConfig?.debug !== true) { + return; + } + // config is loaded, and debug is true + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).trace(...log); + } + + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).trace(...args); +}; + +export const logWarn = (...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && globalThis?.logger.warn(...log); + } + + globalThis?.logger && globalThis?.logger.warn(...args); +}; + +export const logWarnWithRequestId = (id: string, ...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + // config is loaded, and debug is true + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).warn(...log); + } + + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).warn(...args); }; export const logError = (...args: any) => { @@ -346,6 +481,36 @@ export const logError = (...args: any) => { globalThis.logManager.get(globalThis.logger.category).error(...args); }; +export const logErrorWithRequestId = (id: string, ...args: any) => { + if (!globalThis) { + // there is no globalThis, just print the log + console.log(...args); + return; + } + + // check if config is loaded yet + if (!globalThis?.litConfig) { + // config isn't loaded yet, push into buffer + logBuffer.push(args); + return; + } + + if (globalThis?.litConfig?.debug !== true) { + return; + } + // config is loaded, and debug is true + + // if there are there are logs in buffer, print them first and empty the buffer. + while (logBuffer.length > 0) { + const log = logBuffer.shift() ?? ''; + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).error(...log); + } + + globalThis?.logger && + globalThis.logManager.get(globalThis.logger.category, id).error(...args); +}; + /** * * Get the type of a variable, could be an object instance type. @@ -423,7 +588,7 @@ export const checkIfAuthSigRequiresChainParam = ( chain: string, functionName: string ): boolean => { - log('checkIfAuthSigRequiresChainParam'); + logDebug('checkIfAuthSigRequiresChainParam'); for (const key of LIT_AUTH_SIG_CHAIN_KEYS) { if (key in authSig) { return true; From 67551f703d52329bc846196210fe32bf7b352059 Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:24:41 -0500 Subject: [PATCH 02/11] global replace of log with logDebug --- .../src/lib/hashing.ts | 12 +-- .../src/lib/humanizer.ts | 28 ++--- .../auth-browser/src/lib/chains/cosmos.ts | 6 +- packages/auth-browser/src/lib/chains/eth.ts | 100 +++++++++--------- packages/auth-browser/src/lib/chains/sol.ts | 8 +- packages/bls-sdk/README.md | 2 +- packages/core/src/lib/lit-core.ts | 34 +++--- packages/crypto/src/lib/crypto.ts | 16 +-- packages/encryption/src/lib/encryption.ts | 16 +-- .../encryption/src/lib/params-validators.ts | 2 +- .../src/lib/lit-auth-client.ts | 10 +- .../src/lib/providers/EthWalletProvider.ts | 2 +- packages/lit-auth-client/src/lib/relay.ts | 14 +-- packages/lit-auth-client/src/lib/utils.ts | 2 +- packages/lit-node-client-nodejs/src/index.ts | 2 +- .../src/lib/lit-node-client-nodejs.ts | 74 ++++++------- packages/lit-node-client/src/index.ts | 2 +- .../src/lib/lit-node-client.ts | 2 +- packages/logger/src/lib/logger.ts | 2 +- packages/pkp-base/src/lib/pkp-base.ts | 2 +- packages/pkp-client/src/lib/pkp-client.ts | 2 +- packages/sev-snp-utils-sdk/README.md | 2 +- 22 files changed, 170 insertions(+), 170 deletions(-) diff --git a/packages/access-control-conditions/src/lib/hashing.ts b/packages/access-control-conditions/src/lib/hashing.ts index e3b3dbbeda..8c9e0d6198 100644 --- a/packages/access-control-conditions/src/lib/hashing.ts +++ b/packages/access-control-conditions/src/lib/hashing.ts @@ -29,14 +29,14 @@ import { uint8arrayToString } from '@lit-protocol/uint8arrays'; export const hashUnifiedAccessControlConditions = ( unifiedAccessControlConditions: UnifiedAccessControlConditions ): Promise => { - log('unifiedAccessControlConditions:', unifiedAccessControlConditions); + logDebug'unifiedAccessControlConditions:', unifiedAccessControlConditions); const conditions = unifiedAccessControlConditions.map( (condition: ConditionItem) => { return canonicalUnifiedAccessControlConditionFormatter(condition); } ); - log('conditions:', conditions); + logDebug'conditions:', conditions); // check if there's any undefined in the conditions const hasUndefined = conditions.some((c) => c === undefined); @@ -57,7 +57,7 @@ export const hashUnifiedAccessControlConditions = ( } const toHash = JSON.stringify(conditions); - log('Hashing unified access control conditions: ', toHash); + logDebug'Hashing unified access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -116,7 +116,7 @@ export const hashAccessControlConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing access control conditions: ', toHash); + logDebug'Hashing access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -140,7 +140,7 @@ export const hashEVMContractConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing evm contract conditions: ', toHash); + logDebug'Hashing evm contract conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); return crypto.subtle.digest('SHA-256', data); @@ -163,7 +163,7 @@ export const hashSolRpcConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing sol rpc conditions: ', toHash); + logDebug'Hashing sol rpc conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); diff --git a/packages/access-control-conditions/src/lib/humanizer.ts b/packages/access-control-conditions/src/lib/humanizer.ts index 363f4309e1..ea9281b0fa 100644 --- a/packages/access-control-conditions/src/lib/humanizer.ts +++ b/packages/access-control-conditions/src/lib/humanizer.ts @@ -60,7 +60,7 @@ export const humanizeComparator = (comparator: string): string | undefined => { let selected: string | undefined = list[comparator]; if (!selected) { - log(`Unregonized comparator ${comparator}`); + logDebug`Unregonized comparator ${comparator}`); return; } @@ -86,9 +86,9 @@ export const humanizeEvmBasicAccessControlConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing evm basic access control conditions'); - log('myWalletAddress', myWalletAddress); - log('accessControlConditions', accessControlConditions); + logDebug'humanizing evm basic access control conditions'); + logDebug'myWalletAddress', myWalletAddress); + logDebug'accessControlConditions', accessControlConditions); let fixedConditions: any = accessControlConditions; @@ -235,7 +235,7 @@ export const humanizeEvmBasicAccessControlConditions = async ({ console.log(`Failed to get decimals for ${acc.contractAddress}`); } } - log('decimals', decimals); + logDebug'decimals', decimals); return `Owns ${humanizeComparator( acc.returnValueTest.comparator )} ${formatUnits(acc.returnValueTest.value, decimals)} of ${ @@ -286,9 +286,9 @@ export const humanizeEvmContractConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing evm contract conditions'); - log('myWalletAddress', myWalletAddress); - log('evmContractConditions', evmContractConditions); + logDebug'humanizing evm contract conditions'); + logDebug'myWalletAddress', myWalletAddress); + logDebug'evmContractConditions', evmContractConditions); const promises = await Promise.all( evmContractConditions.map(async (acc: any) => { @@ -347,9 +347,9 @@ export const humanizeSolRpcConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing sol rpc conditions'); - log('myWalletAddress', myWalletAddress); - log('solRpcConditions', solRpcConditions); + logDebug'humanizing sol rpc conditions'); + logDebug'myWalletAddress', myWalletAddress); + logDebug'solRpcConditions', solRpcConditions); const promises = await Promise.all( solRpcConditions.map(async (acc: any) => { @@ -421,9 +421,9 @@ export const humanizeCosmosConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing cosmos conditions'); - log('myWalletAddress', myWalletAddress); - log('cosmosConditions', cosmosConditions); + logDebug'humanizing cosmos conditions'); + logDebug'myWalletAddress', myWalletAddress); + logDebug'cosmosConditions', cosmosConditions); const promises = await Promise.all( cosmosConditions.map(async (acc: any) => { diff --git a/packages/auth-browser/src/lib/chains/cosmos.ts b/packages/auth-browser/src/lib/chains/cosmos.ts index 1378971a34..bbdfcffc95 100644 --- a/packages/auth-browser/src/lib/chains/cosmos.ts +++ b/packages/auth-browser/src/lib/chains/cosmos.ts @@ -142,7 +142,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- if not found in local storage if (!authSig) { - log('signing auth message because sig is not in local storage'); + logDebug'signing auth message because sig is not in local storage'); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -154,7 +154,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- validate if (connectedCosmosProvider.account != authSig.address) { - log( + logDebug 'signing auth message because account is not the same as the address in the auth sig' ); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -162,7 +162,7 @@ export const checkAndSignCosmosAuthMessage = async ({ authSig = JSON.parse(authSig); } - log('authSig', authSig); + logDebug'authSig', authSig); return authSig; }; diff --git a/packages/auth-browser/src/lib/chains/eth.ts b/packages/auth-browser/src/lib/chains/eth.ts index 3e6a95e50b..b21347e6e7 100644 --- a/packages/auth-browser/src/lib/chains/eth.ts +++ b/packages/auth-browser/src/lib/chains/eth.ts @@ -46,15 +46,15 @@ if (typeof global.Buffer === 'undefined') { global.Buffer = BufferPolyfill; } -// log("naclUtil:", naclUtil); -// log("nacl:", nacl); +// logDebug"naclUtil:", naclUtil); +// logDebug"nacl:", nacl); // -- fix import issues // let _nacl = nacl === undefined ? nacl['default'] : nacl; // let _naclUtil = naclUtil === undefined ? naclUtil['default'] : naclUtil; -// log("_nacl:", _nacl); -// log("_naclUtil:", _naclUtil); +// logDebug"_nacl:", _nacl); +// logDebug"_naclUtil:", _naclUtil); /** ---------- Local Interfaces ---------- */ interface ConnectWeb3 { @@ -203,7 +203,7 @@ export const getChainId = async ( resultOrError = ERight(resp.chainId); } catch (e) { // couldn't get chainId. throw the incorrect network error - log('getNetwork threw an exception', e); + logDebug'getNetwork threw an exception', e); resultOrError = ELeft({ message: `Incorrect network selected. Please switch to the ${chain} network in your wallet and try again.`, @@ -251,23 +251,23 @@ export const getMustResign = (authSig: AuthSig, resources: any): boolean => { try { const parsedSiwe = new SiweMessage(authSig.signedMessage); - log('parsedSiwe.resources', parsedSiwe.resources); + logDebug'parsedSiwe.resources', parsedSiwe.resources); if (JSON.stringify(parsedSiwe.resources) !== JSON.stringify(resources)) { - log( + logDebug 'signing auth message because resources differ from the resources in the auth sig' ); mustResign = true; } if (parsedSiwe.address !== getAddress(parsedSiwe.address)) { - log( + logDebug 'signing auth message because parsedSig.address is not equal to the same address but checksummed. This usually means the user had a non-checksummed address saved and so they need to re-sign.' ); mustResign = true; } } catch (e) { - log('error parsing siwe sig. making the user sign again: ', e); + logDebug'error parsing siwe sig. making the user sign again: ', e); mustResign = true; } @@ -354,7 +354,7 @@ export const connectWeb3 = async ({ }: ConnectWeb3): Promise => { // -- check if it's nodejs if (isNode()) { - log('connectWeb3 is not supported in nodejs.'); + logDebug'connectWeb3 is not supported in nodejs.'); return { web3: null, account: null }; } @@ -383,35 +383,35 @@ export const connectWeb3 = async ({ } } - log('getting provider via lit connect modal'); + logDebug'getting provider via lit connect modal'); const dialog = new LitConnectModal({ providerOptions }); const provider = await dialog.getWalletProvider(); - log('got provider'); + logDebug'got provider'); // @ts-ignore const web3 = new Web3Provider(provider); // trigger metamask popup try { - log( + logDebug '@deprecated soon to be removed. - trying to enable provider. this will trigger the metamask popup.' ); // @ts-ignore await provider.enable(); } catch (e) { - log( + logDebug "error enabling provider but swallowed it because it's not important. most wallets use a different function now to enable the wallet so you can ignore this error, because those other methods will be tried.", e ); } - log('listing accounts'); + logDebug'listing accounts'); const accounts = await web3.listAccounts(); - log('accounts', accounts); + logDebug'accounts', accounts); const account = accounts[0].toLowerCase(); return { web3, account }; @@ -427,7 +427,7 @@ export const connectWeb3 = async ({ */ export const disconnectWeb3 = (): void => { if (isNode()) { - log('disconnectWeb3 is not supported in nodejs.'); + logDebug'disconnectWeb3 is not supported in nodejs.'); return; } @@ -437,7 +437,7 @@ export const disconnectWeb3 = (): void => { // @ts-ignore globalThis.litWCProvider.disconnect(); } catch (err) { - log( + logDebug 'Attempted to disconnect global WalletConnectProvider for lit-connect-modal', err ); @@ -471,7 +471,7 @@ export const checkAndSignEVMAuthMessage = async ({ }: AuthCallbackParams): Promise => { // -- check if it's nodejs if (isNode()) { - log( + logDebug 'checkAndSignEVMAuthMessage is not supported in nodejs. You can create a SIWE on your own using the SIWE package.' ); return { @@ -504,7 +504,7 @@ export const checkAndSignEVMAuthMessage = async ({ walletConnectProjectId, }); - log(`got web3 and account: ${account}`); + logDebug`got web3 and account: ${account}`); // -- 2. prepare all required variables const currentChainIdOrError = await getChainId(chain, web3); @@ -512,18 +512,18 @@ export const checkAndSignEVMAuthMessage = async ({ const selectedChainIdHex: string = numberToHex(selectedChainId); const authSigOrError = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE); - log('currentChainIdOrError:', currentChainIdOrError); - log('selectedChainId:', selectedChainId); - log('selectedChainIdHex:', selectedChainIdHex); - log('authSigOrError:', authSigOrError); + logDebug'currentChainIdOrError:', currentChainIdOrError); + logDebug'selectedChainId:', selectedChainId); + logDebug'selectedChainIdHex:', selectedChainIdHex); + logDebug'authSigOrError:', authSigOrError); // -- 3. check all variables before executing business logic if (currentChainIdOrError.type === EITHER_TYPE.ERROR) { return throwError(currentChainIdOrError.result as any); } - log('chainId from web3', currentChainIdOrError); - log( + logDebug'chainId from web3', currentChainIdOrError); + logDebug `checkAndSignAuthMessage with chainId ${currentChainIdOrError} and chain set to ${chain} and selectedChain is `, selectedChain ); @@ -542,7 +542,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if able to switch chain id try { - log('trying to switch to chainId', selectedChainIdHex); + logDebug'trying to switch to chainId', selectedChainIdHex); await provider.request({ method: 'wallet_switchEthereumChain', @@ -551,7 +551,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if unable to switch chain } catch (switchError: any) { - log('error switching to chainId', switchError); + logDebug'error switching to chainId', switchError); // -- (error case) if ( @@ -589,10 +589,10 @@ export const checkAndSignEVMAuthMessage = async ({ } // -- 5. case: Lit auth signature is NOT in the local storage - log('checking if sig is in local storage'); + logDebug'checking if sig is in local storage'); if (authSigOrError.type === EITHER_TYPE.ERROR) { - log('signing auth message because sig is not in local storage'); + logDebug'signing auth message because sig is not in local storage'); try { // @ts-ignore @@ -606,7 +606,7 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } catch (e: any) { - log(e); + logDebuge); return throwError({ message: e.message, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -614,7 +614,7 @@ export const checkAndSignEVMAuthMessage = async ({ }); } authSigOrError.type = EITHER_TYPE.SUCCESS; - log('5. authSigOrError:', authSigOrError); + logDebug'5. authSigOrError:', authSigOrError); } // -- 6. case: Lit auth signature IS in the local storage @@ -623,11 +623,11 @@ export const checkAndSignEVMAuthMessage = async ({ if (typeof authSig === 'string') { authSig = JSON.parse(authSig); } - log('6. authSig:', authSig); + logDebug'6. authSig:', authSig); // -- 7. case: when we are NOT on the right wallet address if (account.toLowerCase() !== authSig.address.toLowerCase()) { - log( + logDebug 'signing auth message because account is not the same as the address in the auth sig' ); authSig = await _signAndGetAuth({ @@ -639,7 +639,7 @@ export const checkAndSignEVMAuthMessage = async ({ uri, nonce, }); - log('7. authSig:', authSig); + logDebug'7. authSig:', authSig); // -- 8. case: we are on the right wallet, but need to check the resources of the sig and re-sign if they don't match } else { @@ -656,13 +656,13 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } - log('8. mustResign:', mustResign); + logDebug'8. mustResign:', mustResign); } // -- 9. finally, if the authSig is expired, re-sign // if it's not expired, then we don't need to resign if (isSignedMessageExpired(authSig.signedMessage)) { - log('9. authSig expired!, resigning..'); + logDebug'9. authSig expired!, resigning..'); authSig = await _signAndGetAuth({ web3, @@ -738,7 +738,7 @@ export const signAndSaveAuthMessage = async ({ }: signAndSaveAuthParams): Promise => { // check if it's nodejs if (isNode()) { - log('checkAndSignEVMAuthMessage is not supported in nodejs.'); + logDebug'checkAndSignEVMAuthMessage is not supported in nodejs.'); return { sig: '', derivedVia: '', @@ -804,7 +804,7 @@ export const signAndSaveAuthMessage = async ({ ); } - log(`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); + logDebug`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); return authSig; }; @@ -823,7 +823,7 @@ export const signMessage = async ({ }: SignMessageParams): Promise => { // check if it's nodejs if (isNode()) { - log('signMessage is not supported in nodejs.'); + logDebug'signMessage is not supported in nodejs.'); return { signature: '', address: '', @@ -832,26 +832,26 @@ export const signMessage = async ({ // -- validate if (!web3 || !account) { - log(`web3: ${web3} OR ${account} not found. Connecting web3..`); + logDebug`web3: ${web3} OR ${account} not found. Connecting web3..`); let res = await connectWeb3({ chainId: 1 }); web3 = res.web3; account = res.account; } - log('pausing...'); + logDebug'pausing...'); await new Promise((resolve: any) => setTimeout(resolve, 500)); - log('signing with ', account); + logDebug'signing with ', account); const signature = await signMessageAsync(web3.getSigner(), account, body); const address = verifyMessage(body, signature).toLowerCase(); - log('Signature: ', signature); - log('recovered address: ', address); + logDebug'Signature: ', signature); + logDebug'recovered address: ', address); if (address.toLowerCase() !== account.toLowerCase()) { const msg = `ruh roh, the user signed with a different address (${address}) then they\'re using with web3 (${account}). this will lead to confusion.`; - log(msg); + logDebugmsg); alert( 'something seems to be wrong with your wallets message signing. maybe restart your browser or your wallet. your recovered sig address does not match your web3 account address' ); @@ -878,7 +878,7 @@ export const signMessageAsync = async ( ): Promise => { // check if it's nodejs if (isNode()) { - log('signMessageAsync is not supported in nodejs.'); + logDebug'signMessageAsync is not supported in nodejs.'); return null; } @@ -886,14 +886,14 @@ export const signMessageAsync = async ( if (signer instanceof JsonRpcSigner) { try { - log('Signing with personal_sign'); + logDebug'Signing with personal_sign'); const signature = await signer.provider.send('personal_sign', [ hexlify(messageBytes), address.toLowerCase(), ]); return signature; } catch (e: any) { - log( + logDebug 'Signing with personal_sign failed, trying signMessage as a fallback' ); if (e.message.includes('personal_sign')) { @@ -902,7 +902,7 @@ export const signMessageAsync = async ( throw e; } } else { - log('signing with signMessage'); + logDebug'signing with signMessage'); return await signer.signMessage(messageBytes); } }; diff --git a/packages/auth-browser/src/lib/chains/sol.ts b/packages/auth-browser/src/lib/chains/sol.ts index 16e54ba890..7df35a7d21 100644 --- a/packages/auth-browser/src/lib/chains/sol.ts +++ b/packages/auth-browser/src/lib/chains/sol.ts @@ -84,7 +84,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { const res = await connectSolProvider(); if (!res) { - log('Failed to connect sol provider'); + logDebug'Failed to connect sol provider'); } const provider = res?.provider; @@ -98,7 +98,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- case: if unable to get auth from local storage if (authSigOrError.type === EITHER_TYPE.ERROR) { - log('signing auth message because sig is not in local storage'); + logDebug'signing auth message because sig is not in local storage'); await signAndSaveAuthMessage({ provider }); @@ -122,7 +122,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- if the wallet address isn't the same as the address from local storage if (account !== authSig.address) { - log( + logDebug 'signing auth message because account is not the same as the address in the auth sig' ); @@ -135,7 +135,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { authSig = JSON.parse(authSigOrError.result); } - log('authSig', authSig); + logDebug'authSig', authSig); return authSig; }; diff --git a/packages/bls-sdk/README.md b/packages/bls-sdk/README.md index 2ca8c7d66e..3f751b9f47 100644 --- a/packages/bls-sdk/README.md +++ b/packages/bls-sdk/README.md @@ -17,7 +17,7 @@ import { initWasmBlsSdk } from '@lit-protocol/bls-sdk'; initWasmBlsSdk().then((exports) => { globalThis.wasmExports = exports; - log( + logDebug `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index 48e241d02a..56762f460c 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -139,7 +139,7 @@ export class LitCore { // If the user sets a new storage provider we respect it over our default storage // If the user sets a new file path, we respect it over the default path. if (this.config.storageProvider?.provider) { - log( + logDebug 'localstorage api not found, injecting persistance instance found in config' ); // using Object definProperty in order to set a property previously defined as readonly. @@ -152,7 +152,7 @@ export class LitCore { !globalThis.localStorage && !this.config.storageProvider?.provider ) { - log( + logDebug 'Looks like you are running in NodeJS and did not provide a storage provider, youre sessions will not be cached' ); } @@ -186,7 +186,7 @@ export class LitCore { const bootstrapUrls = await LitContracts.getValidators( this.config.litNetwork as LitNetwork ); - log('Bootstrap urls: ', bootstrapUrls); + logDebug'Bootstrap urls: ', bootstrapUrls); if (minNodeCount <= 0) { throwError({ message: `minNodeCount is ${minNodeCount}, which is invalid. Please check your network connection and try again.`, @@ -232,12 +232,12 @@ export class LitCore { const stakingContract = await LitContracts.getStakingContract( this.config.litNetwork as any ); - log( + logDebug 'listening for state change on staking contract: ', stakingContract.address ); stakingContract.on('StateChanged', async (state: StakingStates) => { - log(`New state detected: "${state}"`); + logDebug`New state detected: "${state}"`); if (state === StakingStates.NextValidatorSetLocked) { await this.setNewConfig(); } @@ -339,12 +339,12 @@ export class LitCore { }); } else { // actually verify the attestation by checking the signature against AMD certs - log('Checking attestation against amd certs...'); + logDebug'Checking attestation against amd certs...'); const attestation = resp.attestation; try { checkSevSnpAttestation(attestation, challenge, url).then(() => { - log(`Lit Node Attestation verified for ${url}`); + logDebug`Lit Node Attestation verified for ${url}`); // only set server keys if attestation is valid // so that we don't use this node if it's not valid @@ -368,7 +368,7 @@ export class LitCore { } }) .catch((e: any) => { - log('Error connecting to node ', url, e); + logDebug'Error connecting to node ', url, e); }); } @@ -424,10 +424,10 @@ export class LitCore { this.ready = true; - log( + logDebug `🔥 lit is ready. "litNodeClient" variable is ready to use globally.` ); - log('current network config', { + logDebug'current network config', { networkPubkey: this.networkPubKey, networkPubKeySet: this.networkPubKeySet, hdRootPubkeys: this.hdRootPubkeys, @@ -509,7 +509,7 @@ export class LitCore { // -- create url with path const urlWithPath = `${url}/web/handshake`; - log(`handshakeWithNode ${urlWithPath}`); + logDebug`handshakeWithNode ${urlWithPath}`); const data = { clientPublicKey: 'test', @@ -627,7 +627,7 @@ export class LitCore { errorCode: LIT_ERROR.INVALID_ARGUMENT_EXCEPTION.name, }); } else { - log(`authSig or sessionSigs not found. This may be using authMethod`); + logDebug`authSig or sessionSigs not found. This may be using authMethod`); } } @@ -763,7 +763,7 @@ export class LitCore { res.error.errorCode === 'not_authorized') && this.config.alertWhenUnauthorized ) { - log( + logDebug '[Alert originally] You are not authorized to access to this content' ); } @@ -814,7 +814,7 @@ export class LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - log( + logDebug 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -822,7 +822,7 @@ export class LitCore { formattedEVMContractConditions = evmContractConditions.map((c: any) => canonicalEVMContractConditionFormatter(c) ); - log( + logDebug 'formattedEVMContractConditions', JSON.stringify(formattedEVMContractConditions) ); @@ -830,7 +830,7 @@ export class LitCore { formattedSolRpcConditions = solRpcConditions.map((c: any) => canonicalSolRpcConditionFormatter(c) ); - log( + logDebug 'formattedSolRpcConditions', JSON.stringify(formattedSolRpcConditions) ); @@ -839,7 +839,7 @@ export class LitCore { unifiedAccessControlConditions.map((c: any) => canonicalUnifiedAccessControlConditionFormatter(c) ); - log( + logDebug 'formattedUnifiedAccessControlConditions', JSON.stringify(formattedUnifiedAccessControlConditions) ); diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index 8e8dc13d64..eeab382d04 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -26,7 +26,7 @@ if (!globalThis.wasmExports) { globalThis.wasmExports = exports; if (!globalThis.jestTesting) { - log( + logDebug `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` @@ -49,7 +49,7 @@ if (!globalThis.wasmECDSA) { globalThis.wasmECDSA = sdk; if (!globalThis.jestTesting) { - log( + logDebug `✅ [ECDSA SDK ${env}] wasmECDSA loaded. ${ Object.keys(wasmECDSA).length } functions available. Run 'wasmECDSA' in the console to see them.` @@ -63,7 +63,7 @@ if (!globalThis.wasmSevSnpUtils) { globalThis.wasmSevSnpUtils = exports; if (!globalThis.jestTesting) { - log( + logDebug `✅ [SEV SNP Utils SDK] wasmSevSnpUtils loaded. ${ Object.keys(exports).length } functions available. Run 'wasmSevSnpUtils' in the console to see them.` @@ -224,7 +224,7 @@ export const combineEcdsaShares = ( return acc; }, []); - log('Valid Shares:', validShares); + logDebug'Valid Shares:', validShares); // if there are no valid shares, throw an error if (validShares.length === 0) { @@ -267,7 +267,7 @@ export const combineEcdsaShares = ( break; case SIGTYPE.ECDSCAITSITHP256: res = ecdsaSdk.combine_signature(validShares, 3); - log('response from combine_signature', res); + logDebug'response from combine_signature', res); sig = JSON.parse(res); break; // if its another sig type, it shouldnt be resolving to this method @@ -277,10 +277,10 @@ export const combineEcdsaShares = ( ); } } catch (e) { - log('Failed to combine signatures:', e); + logDebug'Failed to combine signatures:', e); } - log('signature', sig); + logDebug'signature', sig); return sig; }; @@ -298,7 +298,7 @@ export const computeHDPubKey = ( defualt: throw new Error('Non supported signature type'); } } catch (e) { - log('Failed to derive public key', e); + logDebug'Failed to derive public key', e); } }; diff --git a/packages/encryption/src/lib/encryption.ts b/packages/encryption/src/lib/encryption.ts index 0da27ca35e..b18b128eef 100644 --- a/packages/encryption/src/lib/encryption.ts +++ b/packages/encryption/src/lib/encryption.ts @@ -377,7 +377,7 @@ export const zipAndEncryptFiles = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug"Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: "Failed to get 'encryptedAssets' from zip.folder() ", errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -561,7 +561,7 @@ export const encryptFileAndZipWithMetadata = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug"Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: `Failed to get 'encryptedAssets' from zip.folder()`, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -620,25 +620,25 @@ export const decryptZipFileWithMetadata = async ( ); if (!jsonFile) { - log(`Failed to read lit_protocol_metadata.json while zip.file()`); + logDebug`Failed to read lit_protocol_metadata.json while zip.file()`); return; } const metadata: MetadataForFile = JSON.parse(await jsonFile.async('string')); - log('zip metadata', metadata); + logDebug'zip metadata', metadata); const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug"Failed to get 'encryptedAssets' from zip.folder() "); return; } const _file: JSZip.JSZipObject | null = folder.file(metadata.name); if (!_file) { - log("Failed to get 'metadata.name' while zip.folder().file()"); + logDebug"Failed to get 'metadata.name' while zip.folder().file()"); return; } @@ -767,11 +767,11 @@ export const verifyJwt = ({ errorCode: LIT_ERROR.INVALID_PARAM_TYPE.name, }); - log('verifyJwt', jwt); + logDebug'verifyJwt', jwt); // verify that the wasm was loaded if (!globalThis.wasmExports) { - log('wasmExports is not loaded.'); + logDebug'wasmExports is not loaded.'); } const jwtParts = jwt.split('.'); diff --git a/packages/encryption/src/lib/params-validators.ts b/packages/encryption/src/lib/params-validators.ts index 08fd6813ca..54feed42ed 100644 --- a/packages/encryption/src/lib/params-validators.ts +++ b/packages/encryption/src/lib/params-validators.ts @@ -50,7 +50,7 @@ export const safeParams = ({ params: any[] | any; }): IEither => { if (!paramsValidators[functionName]) { - log(`This function ${functionName} is skipping params safe guarding.`); + logDebug`This function ${functionName} is skipping params safe guarding.`); return ERight(undefined); } diff --git a/packages/lit-auth-client/src/lib/lit-auth-client.ts b/packages/lit-auth-client/src/lib/lit-auth-client.ts index 35b7bb8116..8c6d60061a 100644 --- a/packages/lit-auth-client/src/lib/lit-auth-client.ts +++ b/packages/lit-auth-client/src/lib/lit-auth-client.ts @@ -88,9 +88,9 @@ export class LitAuthClient { // Set RPC URL this.rpcUrl = options?.rpcUrl || 'https://chain-rpc.litprotocol.com/http'; - log('rpc url: ', this.rpcUrl); - log('relay config: ', options.litRelayConfig); - log('relay instance: ', this.relay); + logDebug'rpc url: ', this.rpcUrl); + logDebug'relay config: ', options.litRelayConfig); + logDebug'relay instance: ', this.relay); } /** @@ -112,7 +112,7 @@ export class LitAuthClient { }; let provider: T; - log('resolving provider of type: ', type); + logDebug'resolving provider of type: ', type); switch (type) { case 'google': provider = new GoogleProvider({ @@ -232,7 +232,7 @@ export class LitAuthClient { authId = await StytchAuthFactorOtpProvider.authMethodId(authMethod); break; default: - log(`unsupported AuthMethodType: ${authMethod.authMethodType}`); + logDebug`unsupported AuthMethodType: ${authMethod.authMethodType}`); throw new Error( `Unsupported auth method type: ${authMethod.authMethodType}` ); diff --git a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts index c93000581c..aebb36ae9a 100644 --- a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts +++ b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts @@ -28,7 +28,7 @@ export default class EthWalletProvider extends BaseProvider { this.domain = options.domain || window.location.hostname; this.origin = options.origin || window.location.origin; } catch (e) { - log( + logDebug '⚠️ Error getting "domain" and "origin" from window object, defaulting to "localhost" and "http://localhost"' ); this.domain = options.domain || 'localhost'; diff --git a/packages/lit-auth-client/src/lib/relay.ts b/packages/lit-auth-client/src/lib/relay.ts index 762c208fe5..3fb566b299 100644 --- a/packages/lit-auth-client/src/lib/relay.ts +++ b/packages/lit-auth-client/src/lib/relay.ts @@ -39,7 +39,7 @@ export class LitRelay implements IRelay { this.relayUrl = config.relayUrl || 'https://relayer-server-staging-cayenne.getlit.dev'; this.relayApiKey = config.relayApiKey || ''; - log("Lit's relay server URL:", this.relayUrl); + logDebug"Lit's relay server URL:", this.relayUrl); } /** @@ -60,12 +60,12 @@ export class LitRelay implements IRelay { }); if (response.status < 200 || response.status >= 400) { - log('Something wrong with the API call', await response.json()); + logDebug'Something wrong with the API call', await response.json()); const err = new Error('Unable to mint PKP through relay server'); throw err; } else { const resBody = await response.json(); - log('Successfully initiated minting PKP with relayer'); + logDebug'Successfully initiated minting PKP with relayer'); return resBody; } } @@ -96,7 +96,7 @@ export class LitRelay implements IRelay { ); if (response.status < 200 || response.status >= 400) { - log('Something wrong with the API call', await response.json()); + logDebug'Something wrong with the API call', await response.json()); const err = new Error( `Unable to poll the status of this mint PKP transaction: ${requestId}` ); @@ -104,18 +104,18 @@ export class LitRelay implements IRelay { } const resBody = await response.json(); - log('Response OK', { body: resBody }); + logDebug'Response OK', { body: resBody }); if (resBody.error) { // exit loop since error - log('Something wrong with the API call', { + logDebug'Something wrong with the API call', { error: resBody.error, }); const err = new Error(resBody.error); throw err; } else if (resBody.status === 'Succeeded') { // exit loop since success - log('Successfully authed', { ...resBody }); + logDebug'Successfully authed', { ...resBody }); return resBody; } diff --git a/packages/lit-auth-client/src/lib/utils.ts b/packages/lit-auth-client/src/lib/utils.ts index 2bf6062b06..06f4c96426 100644 --- a/packages/lit-auth-client/src/lib/utils.ts +++ b/packages/lit-auth-client/src/lib/utils.ts @@ -309,7 +309,7 @@ export function unparse(buf: any) { ); } -export function log(...args: any) { +export function logDebug...args: any) { const logger = getLoggerbyId('auth-client'); logger.debug(...args); } diff --git a/packages/lit-node-client-nodejs/src/index.ts b/packages/lit-node-client-nodejs/src/index.ts index 9a9aa68354..a5e9d91e8a 100644 --- a/packages/lit-node-client-nodejs/src/index.ts +++ b/packages/lit-node-client-nodejs/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClientNodeJs from './lib/lit-node-client-nodejs'; // ==================== Environment ==================== if (isNode()) { - log('Oh hey you are running in Node.js!'); + logDebug'Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index fce4898729..7e53c0d477 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -215,7 +215,7 @@ export class LitNodeClientNodeJs extends LitCore { try { response = JSON.parse(responseString); } catch (e) { - log( + logDebug 'Error parsing response as json. Swallowing and returning as string.', responseString ); @@ -341,7 +341,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (TRY) to get it in the local storage // -- IF NOT: Generates one - log(`getWalletSig - flow starts + logDebug`getWalletSig - flow starts storageKey: ${storageKey} storedWalletSigOrError: ${JSON.stringify(storedWalletSigOrError)} `); @@ -351,12 +351,12 @@ export class LitNodeClientNodeJs extends LitCore { !storedWalletSigOrError.result || storedWalletSigOrError.result == '' ) { - log('getWalletSig - flow 1'); + logDebug'getWalletSig - flow 1'); console.warn( `Storage key "${storageKey}" is missing. Not a problem. Continue...` ); if (authNeededCallback) { - log('getWalletSig - flow 1.1'); + logDebug'getWalletSig - flow 1.1'); const body = { chain, statement: sessionCapabilityObject?.statement, @@ -369,13 +369,13 @@ export class LitNodeClientNodeJs extends LitCore { nonce, }; - log('callback body:', body); + logDebug'callback body:', body); walletSig = await authNeededCallback(body); } else { - log('getWalletSig - flow 1.2'); + logDebug'getWalletSig - flow 1.2'); if (!this.defaultAuthCallback) { - log('getWalletSig - flow 1.2.1'); + logDebug'getWalletSig - flow 1.2.1'); return throwError({ message: 'No default auth callback provided', errorKind: LIT_ERROR.PARAMS_MISSING_ERROR.kind, @@ -383,7 +383,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - log('getWalletSig - flow 1.2.2'); + logDebug'getWalletSig - flow 1.2.2'); walletSig = await this.defaultAuthCallback({ chain, statement: sessionCapabilityObject.statement, @@ -397,7 +397,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - log('getWalletSig - flow 1.3'); + logDebug'getWalletSig - flow 1.3'); // (TRY) to set walletSig to local storage const storeNewWalletSigOrError = setStorageItem( @@ -405,23 +405,23 @@ export class LitNodeClientNodeJs extends LitCore { JSON.stringify(walletSig) ); if (storeNewWalletSigOrError.type === 'ERROR') { - log('getWalletSig - flow 1.4'); + logDebug'getWalletSig - flow 1.4'); console.warn( `Unable to store walletSig in local storage. Not a problem. Continue...` ); } } else { - log('getWalletSig - flow 2'); + logDebug'getWalletSig - flow 2'); try { walletSig = JSON.parse(storedWalletSigOrError.result as string); - log('getWalletSig - flow 2.1'); + logDebug'getWalletSig - flow 2.1'); } catch (e) { console.warn('Error parsing walletSig', e); - log('getWalletSig - flow 2.2'); + logDebug'getWalletSig - flow 2.2'); } } - log('getWalletSig - flow 3'); + logDebug'getWalletSig - flow 3'); return walletSig!; }; @@ -648,7 +648,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSigningShareForDecryptionRequest, requestId: string ): Promise => { - log('getSigningShareForDecryption'); + logDebug'getSigningShareForDecryption'); const urlWithPath = `${url}/web/encryption/sign`; return await this.sendCommandToNode({ @@ -673,7 +673,7 @@ export class LitNodeClientNodeJs extends LitCore { params: SignConditionECDSA, requestId: string ): Promise => { - log('signConditionEcdsa'); + logDebug'signConditionEcdsa'); const urlWithPath = `${url}/web/signing/signConditionEcdsa`; const data = { @@ -784,7 +784,7 @@ export class LitNodeClientNodeJs extends LitCore { targetNodeRange, } = params; - log('running runOnTargetedNodes:', targetNodeRange); + logDebug'running runOnTargetedNodes:', targetNodeRange); if (!targetNodeRange) { return throwError({ @@ -852,7 +852,7 @@ export class LitNodeClientNodeJs extends LitCore { .mod(this.config.bootstrapUrls.length) .toNumber(); - log('nodeIndex:', nodeIndex); + logDebug'nodeIndex:', nodeIndex); // must be unique & less than bootstrapUrls.length if ( @@ -864,7 +864,7 @@ export class LitNodeClientNodeJs extends LitCore { nodeCounter++; } - log('Final Selected Indexes:', randomSelectedNodeIndexes); + logDebug'Final Selected Indexes:', randomSelectedNodeIndexes); const requestId = this.getRequestId(); const nodePromises = []; @@ -881,7 +881,7 @@ export class LitNodeClientNodeJs extends LitCore { // because the staking nodes can change, and the rust code will use the same list const url = this.config.bootstrapUrls[nodeIndex]; - log(`running on node ${nodeIndex} at ${url}`); + logDebug`running on node ${nodeIndex} at ${url}`); const reqBody: JsonExecutionRequest = this.getLitActionRequestBody(params); @@ -1011,20 +1011,20 @@ export class LitNodeClientNodeJs extends LitCore { // -- execute keys.forEach((key: any) => { - log('key:', key); + logDebug'key:', key); const shares = signedData.map((r: any) => r[key]); - log('shares:', shares); + logDebug'shares:', shares); shares.sort((a: any, b: any) => a.shareIndex - b.shareIndex); const sigShares: Array = shares.map((s: any, index: number) => { - log('Original Share Struct:', s); + logDebug'Original Share Struct:', s); const share = this._getFlattenShare(s); - log('share:', share); + logDebug'share:', share); if (!share) { throw new Error('share is null or undefined'); @@ -1039,8 +1039,8 @@ export class LitNodeClientNodeJs extends LitCore { const sanitisedBigR = sanitise(share.bigr); const sanitisedSigShare = sanitise(share.publicKey); - log('sanitisedBigR:', sanitisedBigR); - log('sanitisedSigShare:', sanitisedSigShare); + logDebug'sanitisedBigR:', sanitisedBigR); + logDebug'sanitisedSigShare:', sanitisedSigShare); return { sigType: share.sigType, @@ -1053,7 +1053,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - log('getSessionSignatures - sigShares', sigShares); + logDebug'getSessionSignatures - sigShares', sigShares); const sigType = mostCommonString(sigShares.map((s: any) => s.sigType)); @@ -1502,7 +1502,7 @@ export class LitNodeClientNodeJs extends LitCore { logs: mostCommonLogs, }; - log('returnVal:', returnVal); + logDebug'returnVal:', returnVal); // -- case: debug mode if (debug) { @@ -1746,7 +1746,7 @@ export class LitNodeClientNodeJs extends LitCore { res as SuccessNodePromises ).values; - log('signatureShares', signatureShares); + logDebug'signatureShares', signatureShares); // ========== Result ========== const finalJwt: string = this.combineSharesAndGetJWT( @@ -2072,7 +2072,7 @@ export class LitNodeClientNodeJs extends LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - log( + logDebug 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -2105,7 +2105,7 @@ export class LitNodeClientNodeJs extends LitCore { return signature; } catch (e) { - log('Error - signed_ecdsa_messages - ', e); + logDebug'Error - signed_ecdsa_messages - ', e); const signed_ecdsa_message = nodePromises[0]; return signed_ecdsa_message; } @@ -2199,7 +2199,7 @@ export class LitNodeClientNodeJs extends LitCore { let res; try { res = await this.handleNodePromises(nodePromises, requestId); - log('signSessionKey node promises:', res); + logDebug'signSessionKey node promises:', res); } catch (e) { throw new Error(`Error when handling node promises: ${e}`); } @@ -2246,7 +2246,7 @@ export class LitNodeClientNodeJs extends LitCore { // check if all required fields are present for (const field of requiredFields) { if (!sessionSig[field] || sessionSig[field] === '') { - log( + logDebug `Invalid signed data. ${field} is missing. Not a problem, we only need ${this.config.minNodeCount} nodes to sign the session key.` ); return null; @@ -2298,7 +2298,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSignSessionKeySharesProp, requestId: string ) => { - log('getSignSessionKeyShares'); + logDebug'getSignSessionKeyShares'); const urlWithPath = `${url}/web/sign_session_key`; return await this.sendCommandToNode({ url: urlWithPath, @@ -2387,7 +2387,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (CHECK) if we need to resign the session key if (needToResignSessionKey) { - log('need to re-sign session key. Signing...'); + logDebug'need to re-sign session key. Signing...'); authSig = await this.#authCallbackAndUpdateStorageItem({ authCallback: params.authNeededCallback, authCallbackParams: { @@ -2448,7 +2448,7 @@ export class LitNodeClientNodeJs extends LitCore { const uint8arrayMessage = uint8arrayFromString(signedMessage, 'utf8'); let signature = nacl.sign.detached(uint8arrayMessage, uint8arrayKey); - // log("signature", signature); + // logDebug"signature", signature); signatures[nodeAddress] = { sig: uint8arrayToString(signature, 'base16'), derivedVia: 'litSessionSignViaNacl', @@ -2458,7 +2458,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - log('signatures:', signatures); + logDebug'signatures:', signatures); return signatures; }; diff --git a/packages/lit-node-client/src/index.ts b/packages/lit-node-client/src/index.ts index 91c73a1761..0137f2a10c 100644 --- a/packages/lit-node-client/src/index.ts +++ b/packages/lit-node-client/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClient from './lib/lit-node-client'; // ==================== Environment ==================== if (isNode()) { - log('Oh hey you are running in Node.js!'); + logDebug'Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client/src/lib/lit-node-client.ts b/packages/lit-node-client/src/lib/lit-node-client.ts index 603a451e1a..fa6cb1b7d1 100644 --- a/packages/lit-node-client/src/lib/lit-node-client.ts +++ b/packages/lit-node-client/src/lib/lit-node-client.ts @@ -31,7 +31,7 @@ export class LitNodeClient extends LitNodeClientNodeJs { // -- validate if (storageConfigOrError.type === EITHER_TYPE.ERROR) { - log(`Storage key "${storageKey}" is missing. `); + logDebug`Storage key "${storageKey}" is missing. `); return; } diff --git a/packages/logger/src/lib/logger.ts b/packages/logger/src/lib/logger.ts index 0ed28c4b6a..c292830548 100644 --- a/packages/logger/src/lib/logger.ts +++ b/packages/logger/src/lib/logger.ts @@ -290,7 +290,7 @@ export class Logger { } private _log(level: LogLevel, message: string = '', ...args: any[]): void { - const log = new Log( + const log = new logDebug new Date().toISOString(), message, args, diff --git a/packages/pkp-base/src/lib/pkp-base.ts b/packages/pkp-base/src/lib/pkp-base.ts index 4b7a90e740..1ec90d0054 100644 --- a/packages/pkp-base/src/lib/pkp-base.ts +++ b/packages/pkp-base/src/lib/pkp-base.ts @@ -398,7 +398,7 @@ export class PKPBase { * @returns {void} - This function does not return a value. */ - log(...args: any[]): void { + logDebug...args: any[]): void { if (this.debug) { console.log(this.orange + this.PREFIX + this.reset, ...args); } diff --git a/packages/pkp-client/src/lib/pkp-client.ts b/packages/pkp-client/src/lib/pkp-client.ts index 44a58e4e84..11fea9b67c 100644 --- a/packages/pkp-client/src/lib/pkp-client.ts +++ b/packages/pkp-client/src/lib/pkp-client.ts @@ -115,7 +115,7 @@ export class PKPClient { ).length; if (successfulInits !== this._wallets.size) { - log( + logDebug `Not all wallets initialized successfully. Details: ${JSON.stringify( walletStatus, null, diff --git a/packages/sev-snp-utils-sdk/README.md b/packages/sev-snp-utils-sdk/README.md index 4fff08a3b8..240718373c 100644 --- a/packages/sev-snp-utils-sdk/README.md +++ b/packages/sev-snp-utils-sdk/README.md @@ -17,7 +17,7 @@ import { initSevSnpUtilsSdk } from '@lit-protocol/sev-snp-utils-sdk'; initSevSnpUtilsSdk().then((exports) => { globalThis.wasmExports = exports; - log( + logDebug `✅ [SEV SNP Utils SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` From 24b9fefdc30d4f7f0d1f2bf0f32bd5d2c3a779be Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:26:34 -0500 Subject: [PATCH 03/11] global replace of logWithRequestId with logDebugWithRequestId --- packages/core/src/lib/lit-core.ts | 2 +- .../src/lib/lit-node-client-nodejs.ts | 58 +++++++++---------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index 56762f460c..9668817360 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -538,7 +538,7 @@ export class LitCore { data, requestId, }: SendNodeCommand): Promise => { - logWithRequestId( + logDebugWithRequestId( requestId, `sendCommandToNode with url ${url} and data`, data diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index 7e53c0d477..e7e14ab27e 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -555,7 +555,7 @@ export class LitNodeClientNodeJs extends LitCore { ): Promise => { const { code, ipfsId, authSig, jsParams, authMethods } = params; - logWithRequestId(requestId, 'getJsExecutionShares'); + logDebugWithRequestId(requestId, 'getJsExecutionShares'); // -- execute const urlWithPath = `${url}/web/execute`; @@ -579,7 +579,7 @@ export class LitNodeClientNodeJs extends LitCore { params: any, requestId: string ) => { - logWithRequestId(requestId, 'getPkpSigningShares'); + logDebugWithRequestId(requestId, 'getPkpSigningShares'); const urlWithPath = `${url}/web/pkp/sign`; if (!params.authSig) { throw new Error('authSig is required'); @@ -597,7 +597,7 @@ export class LitNodeClientNodeJs extends LitCore { params: any, requestId: string ) => { - logWithRequestId(requestId, 'getPkpSigningShares'); + logDebugWithRequestId(requestId, 'getPkpSigningShares'); const urlWithPath = `${url}/web/pkp/claim`; if (!params.authMethod) { throw new Error('authMethod is required'); @@ -624,7 +624,7 @@ export class LitNodeClientNodeJs extends LitCore { params: SigningAccessControlConditionRequest, requestId: string ): Promise => { - logWithRequestId(requestId, 'getSigningShareForToken'); + logDebugWithRequestId(requestId, 'getSigningShareForToken'); const urlWithPath = `${url}/web/signing/access_control_condition`; return this.sendCommandToNode({ @@ -727,7 +727,7 @@ export class LitNodeClientNodeJs extends LitCore { signatureShares.map((s) => s.signatureShare) ); - logWithRequestId(requestId, 'signature is', signature); + logDebugWithRequestId(requestId, 'signature is', signature); const unsignedJwt = mostCommonString( signatureShares.map((s: any) => s.unsignedJwt) @@ -1126,7 +1126,7 @@ export class LitNodeClientNodeJs extends LitCore { for (const field of requiredFields) { if (!signatureResponse[sigName][field]) { - logWithRequestId( + logDebugWithRequestId( requestId, `invalid field ${field} in signature share: ${sigName}, continuing with share processing` ); @@ -1183,22 +1183,22 @@ export class LitNodeClientNodeJs extends LitCore { shares.sort((a: any, b: any) => a.shareIndex - b.shareIndex); let sigName = shares[0].sigName; - logWithRequestId( + logDebugWithRequestId( requestId, `starting signature combine for sig name: ${sigName}`, shares ); - logWithRequestId( + logDebugWithRequestId( requestId, `number of shares for ${sigName}:`, signedData.length ); - logWithRequestId( + logDebugWithRequestId( requestId, `validated length for signature: ${sigName}`, shares.length ); - logWithRequestId( + logDebugWithRequestId( requestId, 'minimum required shares for threshold:', this.config.minNodeCount @@ -1284,7 +1284,7 @@ export class LitNodeClientNodeJs extends LitCore { await wasmECDSA.initWasmEcdsaSdk(); // init WASM const signature = wasmECDSA.combine_signature(R_x, R_y, shares); - logWithRequestId(requestId, 'raw ecdsa sig', signature); + logDebugWithRequestId(requestId, 'raw ecdsa sig', signature); return signature; }; @@ -1400,7 +1400,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- case: promises success (TODO: check the keys of "values") const responseData = (res as SuccessNodePromises).values; - logWithRequestId( + logDebugWithRequestId( requestId, 'executeJs responseData', JSON.stringify(responseData, null, 2) @@ -1449,7 +1449,7 @@ export class LitNodeClientNodeJs extends LitCore { return signedData; }); - logWithRequestId(requestId, 'signedDataList:', signedDataList); + logDebugWithRequestId(requestId, 'signedDataList:', signedDataList); const signatures = this.getSignatures(signedDataList, requestId); // -- 2. combine responses as a string, and get parse it as JSON @@ -1485,7 +1485,7 @@ export class LitNodeClientNodeJs extends LitCore { }) .filter((item) => item !== null); - logWithRequestId(requestId, 'claimList:', claimsList); + logDebugWithRequestId(requestId, 'claimList:', claimsList); let claims = undefined; @@ -1564,7 +1564,7 @@ export class LitNodeClientNodeJs extends LitCore { mustHave: false, }); - logWithRequestId(requestId, 'sigToPassToNode:', sigToPassToNode); + logDebugWithRequestId(requestId, 'sigToPassToNode:', sigToPassToNode); const reqBody = { toSign, @@ -1574,7 +1574,7 @@ export class LitNodeClientNodeJs extends LitCore { authMethods, }; - logWithRequestId(requestId, 'reqBody:', reqBody); + logDebugWithRequestId(requestId, 'reqBody:', reqBody); return this.getPkpSignExecutionShares(url, reqBody, requestId); }); @@ -1588,7 +1588,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- case: promises success (TODO: check the keys of "values") const responseData = (res as SuccessNodePromises).values; - logWithRequestId( + logDebugWithRequestId( requestId, 'responseData', JSON.stringify(responseData, null, 2) @@ -1636,7 +1636,7 @@ export class LitNodeClientNodeJs extends LitCore { }); const signatures = this.getSignatures(signedDataList, requestId); - logWithRequestId(requestId, `signature combination`, signatures); + logDebugWithRequestId(requestId, `signature combination`, signatures); return signatures.signature; // only a single signature is ever present, so we just return it. }; @@ -1930,7 +1930,7 @@ export class LitNodeClientNodeJs extends LitCore { dataToEncryptHash ); - logWithRequestId(requestId, 'identityParam', identityParam); + logDebugWithRequestId(requestId, 'identityParam', identityParam); // ========== Get Network Signature ========== const nodePromises = this.getNodePromises((url: string) => { @@ -1965,7 +1965,7 @@ export class LitNodeClientNodeJs extends LitCore { res as SuccessNodePromises ).values; - logWithRequestId(requestId, 'signatureShares', signatureShares); + logDebugWithRequestId(requestId, 'signatureShares', signatureShares); // ========== Result ========== const decryptedData = this.#decryptWithSignatureShares( @@ -2183,7 +2183,7 @@ export class LitNodeClientNodeJs extends LitCore { siweMessage: siweMessageStr, }; - logWithRequestId(requestId, 'signSessionKey body', body); + logDebugWithRequestId(requestId, 'signSessionKey body', body); const nodePromises = this.getNodePromises((url: string) => { return this.getSignSessionKeyShares( @@ -2204,7 +2204,7 @@ export class LitNodeClientNodeJs extends LitCore { throw new Error(`Error when handling node promises: ${e}`); } - logWithRequestId(requestId, 'handleNodePromises res:', res); + logDebugWithRequestId(requestId, 'handleNodePromises res:', res); // -- case: promises rejected if (!this.#isSuccessNodePromises(res)) { @@ -2213,7 +2213,7 @@ export class LitNodeClientNodeJs extends LitCore { } const responseData = res.values; - logWithRequestId( + logDebugWithRequestId( requestId, 'responseData', JSON.stringify(responseData, null, 2) @@ -2225,7 +2225,7 @@ export class LitNodeClientNodeJs extends LitCore { (r: any) => (r as SignedData).signedData ); - logWithRequestId(requestId, 'signedDataList', signedDataList); + logDebugWithRequestId(requestId, 'signedDataList', signedDataList); // -- checking if we have enough shares const validatedSignedDataList = signedDataList @@ -2257,13 +2257,13 @@ export class LitNodeClientNodeJs extends LitCore { }) .filter((item) => item !== null); - logWithRequestId(requestId, 'requested length:', signedDataList.length); - logWithRequestId( + logDebugWithRequestId(requestId, 'requested length:', signedDataList.length); + logDebugWithRequestId( requestId, 'validated length:', validatedSignedDataList.length ); - logWithRequestId( + logDebugWithRequestId( requestId, 'minimum required length:', this.config.minNodeCount @@ -2528,7 +2528,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - logWithRequestId( + logDebugWithRequestId( requestId, `responseData: ${JSON.stringify(responseData, null, 2)}` ); @@ -2537,7 +2537,7 @@ export class LitNodeClientNodeJs extends LitCore { .derivedKeyId; const pubkey: string = this.computeHDPubKey(derivedKeyId); - logWithRequestId( + logDebugWithRequestId( requestId, `pubkey ${pubkey} derived from key id ${derivedKeyId}` ); From 0714e8c08361107aade4d31095b57c1577c74bd1 Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:26:58 -0500 Subject: [PATCH 04/11] removed .only from test --- packages/misc/src/lib/misc.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/misc/src/lib/misc.spec.ts b/packages/misc/src/lib/misc.spec.ts index 1d1ea122e7..91a26023ec 100644 --- a/packages/misc/src/lib/misc.spec.ts +++ b/packages/misc/src/lib/misc.spec.ts @@ -30,7 +30,7 @@ describe('utils', () => { expect((console.log as any).mock.calls[2][0]).toBe('Error Message'); }); - it.only('should have debug, info, trace, warn, and error functions', () => { + it('should have debug, info, trace, warn, and error functions', () => { expect(utilsModule.logDebug).toBeDefined(); expect(utilsModule.logDebugWithRequestId).toBeDefined(); expect(utilsModule.logInfo).toBeDefined(); From 7928432fe0ed0115e9192dcd2af72fa9c783ee39 Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:33:38 -0500 Subject: [PATCH 05/11] Revert "global replace of log with logDebug" This reverts commit 67551f703d52329bc846196210fe32bf7b352059. Bad Global Replace --- .../src/lib/hashing.ts | 12 +-- .../src/lib/humanizer.ts | 28 ++--- .../auth-browser/src/lib/chains/cosmos.ts | 6 +- packages/auth-browser/src/lib/chains/eth.ts | 100 +++++++++--------- packages/auth-browser/src/lib/chains/sol.ts | 8 +- packages/bls-sdk/README.md | 2 +- packages/core/src/lib/lit-core.ts | 34 +++--- packages/crypto/src/lib/crypto.ts | 16 +-- packages/encryption/src/lib/encryption.ts | 16 +-- .../encryption/src/lib/params-validators.ts | 2 +- .../src/lib/lit-auth-client.ts | 10 +- .../src/lib/providers/EthWalletProvider.ts | 2 +- packages/lit-auth-client/src/lib/relay.ts | 14 +-- packages/lit-auth-client/src/lib/utils.ts | 2 +- packages/lit-node-client-nodejs/src/index.ts | 2 +- .../src/lib/lit-node-client-nodejs.ts | 74 ++++++------- packages/lit-node-client/src/index.ts | 2 +- .../src/lib/lit-node-client.ts | 2 +- packages/logger/src/lib/logger.ts | 2 +- packages/pkp-base/src/lib/pkp-base.ts | 2 +- packages/pkp-client/src/lib/pkp-client.ts | 2 +- packages/sev-snp-utils-sdk/README.md | 2 +- 22 files changed, 170 insertions(+), 170 deletions(-) diff --git a/packages/access-control-conditions/src/lib/hashing.ts b/packages/access-control-conditions/src/lib/hashing.ts index 8c9e0d6198..e3b3dbbeda 100644 --- a/packages/access-control-conditions/src/lib/hashing.ts +++ b/packages/access-control-conditions/src/lib/hashing.ts @@ -29,14 +29,14 @@ import { uint8arrayToString } from '@lit-protocol/uint8arrays'; export const hashUnifiedAccessControlConditions = ( unifiedAccessControlConditions: UnifiedAccessControlConditions ): Promise => { - logDebug'unifiedAccessControlConditions:', unifiedAccessControlConditions); + log('unifiedAccessControlConditions:', unifiedAccessControlConditions); const conditions = unifiedAccessControlConditions.map( (condition: ConditionItem) => { return canonicalUnifiedAccessControlConditionFormatter(condition); } ); - logDebug'conditions:', conditions); + log('conditions:', conditions); // check if there's any undefined in the conditions const hasUndefined = conditions.some((c) => c === undefined); @@ -57,7 +57,7 @@ export const hashUnifiedAccessControlConditions = ( } const toHash = JSON.stringify(conditions); - logDebug'Hashing unified access control conditions: ', toHash); + log('Hashing unified access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -116,7 +116,7 @@ export const hashAccessControlConditions = ( ); const toHash = JSON.stringify(conds); - logDebug'Hashing access control conditions: ', toHash); + log('Hashing access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -140,7 +140,7 @@ export const hashEVMContractConditions = ( ); const toHash = JSON.stringify(conds); - logDebug'Hashing evm contract conditions: ', toHash); + log('Hashing evm contract conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); return crypto.subtle.digest('SHA-256', data); @@ -163,7 +163,7 @@ export const hashSolRpcConditions = ( ); const toHash = JSON.stringify(conds); - logDebug'Hashing sol rpc conditions: ', toHash); + log('Hashing sol rpc conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); diff --git a/packages/access-control-conditions/src/lib/humanizer.ts b/packages/access-control-conditions/src/lib/humanizer.ts index ea9281b0fa..363f4309e1 100644 --- a/packages/access-control-conditions/src/lib/humanizer.ts +++ b/packages/access-control-conditions/src/lib/humanizer.ts @@ -60,7 +60,7 @@ export const humanizeComparator = (comparator: string): string | undefined => { let selected: string | undefined = list[comparator]; if (!selected) { - logDebug`Unregonized comparator ${comparator}`); + log(`Unregonized comparator ${comparator}`); return; } @@ -86,9 +86,9 @@ export const humanizeEvmBasicAccessControlConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - logDebug'humanizing evm basic access control conditions'); - logDebug'myWalletAddress', myWalletAddress); - logDebug'accessControlConditions', accessControlConditions); + log('humanizing evm basic access control conditions'); + log('myWalletAddress', myWalletAddress); + log('accessControlConditions', accessControlConditions); let fixedConditions: any = accessControlConditions; @@ -235,7 +235,7 @@ export const humanizeEvmBasicAccessControlConditions = async ({ console.log(`Failed to get decimals for ${acc.contractAddress}`); } } - logDebug'decimals', decimals); + log('decimals', decimals); return `Owns ${humanizeComparator( acc.returnValueTest.comparator )} ${formatUnits(acc.returnValueTest.value, decimals)} of ${ @@ -286,9 +286,9 @@ export const humanizeEvmContractConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - logDebug'humanizing evm contract conditions'); - logDebug'myWalletAddress', myWalletAddress); - logDebug'evmContractConditions', evmContractConditions); + log('humanizing evm contract conditions'); + log('myWalletAddress', myWalletAddress); + log('evmContractConditions', evmContractConditions); const promises = await Promise.all( evmContractConditions.map(async (acc: any) => { @@ -347,9 +347,9 @@ export const humanizeSolRpcConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - logDebug'humanizing sol rpc conditions'); - logDebug'myWalletAddress', myWalletAddress); - logDebug'solRpcConditions', solRpcConditions); + log('humanizing sol rpc conditions'); + log('myWalletAddress', myWalletAddress); + log('solRpcConditions', solRpcConditions); const promises = await Promise.all( solRpcConditions.map(async (acc: any) => { @@ -421,9 +421,9 @@ export const humanizeCosmosConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - logDebug'humanizing cosmos conditions'); - logDebug'myWalletAddress', myWalletAddress); - logDebug'cosmosConditions', cosmosConditions); + log('humanizing cosmos conditions'); + log('myWalletAddress', myWalletAddress); + log('cosmosConditions', cosmosConditions); const promises = await Promise.all( cosmosConditions.map(async (acc: any) => { diff --git a/packages/auth-browser/src/lib/chains/cosmos.ts b/packages/auth-browser/src/lib/chains/cosmos.ts index bbdfcffc95..1378971a34 100644 --- a/packages/auth-browser/src/lib/chains/cosmos.ts +++ b/packages/auth-browser/src/lib/chains/cosmos.ts @@ -142,7 +142,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- if not found in local storage if (!authSig) { - logDebug'signing auth message because sig is not in local storage'); + log('signing auth message because sig is not in local storage'); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -154,7 +154,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- validate if (connectedCosmosProvider.account != authSig.address) { - logDebug + log( 'signing auth message because account is not the same as the address in the auth sig' ); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -162,7 +162,7 @@ export const checkAndSignCosmosAuthMessage = async ({ authSig = JSON.parse(authSig); } - logDebug'authSig', authSig); + log('authSig', authSig); return authSig; }; diff --git a/packages/auth-browser/src/lib/chains/eth.ts b/packages/auth-browser/src/lib/chains/eth.ts index b21347e6e7..3e6a95e50b 100644 --- a/packages/auth-browser/src/lib/chains/eth.ts +++ b/packages/auth-browser/src/lib/chains/eth.ts @@ -46,15 +46,15 @@ if (typeof global.Buffer === 'undefined') { global.Buffer = BufferPolyfill; } -// logDebug"naclUtil:", naclUtil); -// logDebug"nacl:", nacl); +// log("naclUtil:", naclUtil); +// log("nacl:", nacl); // -- fix import issues // let _nacl = nacl === undefined ? nacl['default'] : nacl; // let _naclUtil = naclUtil === undefined ? naclUtil['default'] : naclUtil; -// logDebug"_nacl:", _nacl); -// logDebug"_naclUtil:", _naclUtil); +// log("_nacl:", _nacl); +// log("_naclUtil:", _naclUtil); /** ---------- Local Interfaces ---------- */ interface ConnectWeb3 { @@ -203,7 +203,7 @@ export const getChainId = async ( resultOrError = ERight(resp.chainId); } catch (e) { // couldn't get chainId. throw the incorrect network error - logDebug'getNetwork threw an exception', e); + log('getNetwork threw an exception', e); resultOrError = ELeft({ message: `Incorrect network selected. Please switch to the ${chain} network in your wallet and try again.`, @@ -251,23 +251,23 @@ export const getMustResign = (authSig: AuthSig, resources: any): boolean => { try { const parsedSiwe = new SiweMessage(authSig.signedMessage); - logDebug'parsedSiwe.resources', parsedSiwe.resources); + log('parsedSiwe.resources', parsedSiwe.resources); if (JSON.stringify(parsedSiwe.resources) !== JSON.stringify(resources)) { - logDebug + log( 'signing auth message because resources differ from the resources in the auth sig' ); mustResign = true; } if (parsedSiwe.address !== getAddress(parsedSiwe.address)) { - logDebug + log( 'signing auth message because parsedSig.address is not equal to the same address but checksummed. This usually means the user had a non-checksummed address saved and so they need to re-sign.' ); mustResign = true; } } catch (e) { - logDebug'error parsing siwe sig. making the user sign again: ', e); + log('error parsing siwe sig. making the user sign again: ', e); mustResign = true; } @@ -354,7 +354,7 @@ export const connectWeb3 = async ({ }: ConnectWeb3): Promise => { // -- check if it's nodejs if (isNode()) { - logDebug'connectWeb3 is not supported in nodejs.'); + log('connectWeb3 is not supported in nodejs.'); return { web3: null, account: null }; } @@ -383,35 +383,35 @@ export const connectWeb3 = async ({ } } - logDebug'getting provider via lit connect modal'); + log('getting provider via lit connect modal'); const dialog = new LitConnectModal({ providerOptions }); const provider = await dialog.getWalletProvider(); - logDebug'got provider'); + log('got provider'); // @ts-ignore const web3 = new Web3Provider(provider); // trigger metamask popup try { - logDebug + log( '@deprecated soon to be removed. - trying to enable provider. this will trigger the metamask popup.' ); // @ts-ignore await provider.enable(); } catch (e) { - logDebug + log( "error enabling provider but swallowed it because it's not important. most wallets use a different function now to enable the wallet so you can ignore this error, because those other methods will be tried.", e ); } - logDebug'listing accounts'); + log('listing accounts'); const accounts = await web3.listAccounts(); - logDebug'accounts', accounts); + log('accounts', accounts); const account = accounts[0].toLowerCase(); return { web3, account }; @@ -427,7 +427,7 @@ export const connectWeb3 = async ({ */ export const disconnectWeb3 = (): void => { if (isNode()) { - logDebug'disconnectWeb3 is not supported in nodejs.'); + log('disconnectWeb3 is not supported in nodejs.'); return; } @@ -437,7 +437,7 @@ export const disconnectWeb3 = (): void => { // @ts-ignore globalThis.litWCProvider.disconnect(); } catch (err) { - logDebug + log( 'Attempted to disconnect global WalletConnectProvider for lit-connect-modal', err ); @@ -471,7 +471,7 @@ export const checkAndSignEVMAuthMessage = async ({ }: AuthCallbackParams): Promise => { // -- check if it's nodejs if (isNode()) { - logDebug + log( 'checkAndSignEVMAuthMessage is not supported in nodejs. You can create a SIWE on your own using the SIWE package.' ); return { @@ -504,7 +504,7 @@ export const checkAndSignEVMAuthMessage = async ({ walletConnectProjectId, }); - logDebug`got web3 and account: ${account}`); + log(`got web3 and account: ${account}`); // -- 2. prepare all required variables const currentChainIdOrError = await getChainId(chain, web3); @@ -512,18 +512,18 @@ export const checkAndSignEVMAuthMessage = async ({ const selectedChainIdHex: string = numberToHex(selectedChainId); const authSigOrError = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE); - logDebug'currentChainIdOrError:', currentChainIdOrError); - logDebug'selectedChainId:', selectedChainId); - logDebug'selectedChainIdHex:', selectedChainIdHex); - logDebug'authSigOrError:', authSigOrError); + log('currentChainIdOrError:', currentChainIdOrError); + log('selectedChainId:', selectedChainId); + log('selectedChainIdHex:', selectedChainIdHex); + log('authSigOrError:', authSigOrError); // -- 3. check all variables before executing business logic if (currentChainIdOrError.type === EITHER_TYPE.ERROR) { return throwError(currentChainIdOrError.result as any); } - logDebug'chainId from web3', currentChainIdOrError); - logDebug + log('chainId from web3', currentChainIdOrError); + log( `checkAndSignAuthMessage with chainId ${currentChainIdOrError} and chain set to ${chain} and selectedChain is `, selectedChain ); @@ -542,7 +542,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if able to switch chain id try { - logDebug'trying to switch to chainId', selectedChainIdHex); + log('trying to switch to chainId', selectedChainIdHex); await provider.request({ method: 'wallet_switchEthereumChain', @@ -551,7 +551,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if unable to switch chain } catch (switchError: any) { - logDebug'error switching to chainId', switchError); + log('error switching to chainId', switchError); // -- (error case) if ( @@ -589,10 +589,10 @@ export const checkAndSignEVMAuthMessage = async ({ } // -- 5. case: Lit auth signature is NOT in the local storage - logDebug'checking if sig is in local storage'); + log('checking if sig is in local storage'); if (authSigOrError.type === EITHER_TYPE.ERROR) { - logDebug'signing auth message because sig is not in local storage'); + log('signing auth message because sig is not in local storage'); try { // @ts-ignore @@ -606,7 +606,7 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } catch (e: any) { - logDebuge); + log(e); return throwError({ message: e.message, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -614,7 +614,7 @@ export const checkAndSignEVMAuthMessage = async ({ }); } authSigOrError.type = EITHER_TYPE.SUCCESS; - logDebug'5. authSigOrError:', authSigOrError); + log('5. authSigOrError:', authSigOrError); } // -- 6. case: Lit auth signature IS in the local storage @@ -623,11 +623,11 @@ export const checkAndSignEVMAuthMessage = async ({ if (typeof authSig === 'string') { authSig = JSON.parse(authSig); } - logDebug'6. authSig:', authSig); + log('6. authSig:', authSig); // -- 7. case: when we are NOT on the right wallet address if (account.toLowerCase() !== authSig.address.toLowerCase()) { - logDebug + log( 'signing auth message because account is not the same as the address in the auth sig' ); authSig = await _signAndGetAuth({ @@ -639,7 +639,7 @@ export const checkAndSignEVMAuthMessage = async ({ uri, nonce, }); - logDebug'7. authSig:', authSig); + log('7. authSig:', authSig); // -- 8. case: we are on the right wallet, but need to check the resources of the sig and re-sign if they don't match } else { @@ -656,13 +656,13 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } - logDebug'8. mustResign:', mustResign); + log('8. mustResign:', mustResign); } // -- 9. finally, if the authSig is expired, re-sign // if it's not expired, then we don't need to resign if (isSignedMessageExpired(authSig.signedMessage)) { - logDebug'9. authSig expired!, resigning..'); + log('9. authSig expired!, resigning..'); authSig = await _signAndGetAuth({ web3, @@ -738,7 +738,7 @@ export const signAndSaveAuthMessage = async ({ }: signAndSaveAuthParams): Promise => { // check if it's nodejs if (isNode()) { - logDebug'checkAndSignEVMAuthMessage is not supported in nodejs.'); + log('checkAndSignEVMAuthMessage is not supported in nodejs.'); return { sig: '', derivedVia: '', @@ -804,7 +804,7 @@ export const signAndSaveAuthMessage = async ({ ); } - logDebug`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); + log(`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); return authSig; }; @@ -823,7 +823,7 @@ export const signMessage = async ({ }: SignMessageParams): Promise => { // check if it's nodejs if (isNode()) { - logDebug'signMessage is not supported in nodejs.'); + log('signMessage is not supported in nodejs.'); return { signature: '', address: '', @@ -832,26 +832,26 @@ export const signMessage = async ({ // -- validate if (!web3 || !account) { - logDebug`web3: ${web3} OR ${account} not found. Connecting web3..`); + log(`web3: ${web3} OR ${account} not found. Connecting web3..`); let res = await connectWeb3({ chainId: 1 }); web3 = res.web3; account = res.account; } - logDebug'pausing...'); + log('pausing...'); await new Promise((resolve: any) => setTimeout(resolve, 500)); - logDebug'signing with ', account); + log('signing with ', account); const signature = await signMessageAsync(web3.getSigner(), account, body); const address = verifyMessage(body, signature).toLowerCase(); - logDebug'Signature: ', signature); - logDebug'recovered address: ', address); + log('Signature: ', signature); + log('recovered address: ', address); if (address.toLowerCase() !== account.toLowerCase()) { const msg = `ruh roh, the user signed with a different address (${address}) then they\'re using with web3 (${account}). this will lead to confusion.`; - logDebugmsg); + log(msg); alert( 'something seems to be wrong with your wallets message signing. maybe restart your browser or your wallet. your recovered sig address does not match your web3 account address' ); @@ -878,7 +878,7 @@ export const signMessageAsync = async ( ): Promise => { // check if it's nodejs if (isNode()) { - logDebug'signMessageAsync is not supported in nodejs.'); + log('signMessageAsync is not supported in nodejs.'); return null; } @@ -886,14 +886,14 @@ export const signMessageAsync = async ( if (signer instanceof JsonRpcSigner) { try { - logDebug'Signing with personal_sign'); + log('Signing with personal_sign'); const signature = await signer.provider.send('personal_sign', [ hexlify(messageBytes), address.toLowerCase(), ]); return signature; } catch (e: any) { - logDebug + log( 'Signing with personal_sign failed, trying signMessage as a fallback' ); if (e.message.includes('personal_sign')) { @@ -902,7 +902,7 @@ export const signMessageAsync = async ( throw e; } } else { - logDebug'signing with signMessage'); + log('signing with signMessage'); return await signer.signMessage(messageBytes); } }; diff --git a/packages/auth-browser/src/lib/chains/sol.ts b/packages/auth-browser/src/lib/chains/sol.ts index 7df35a7d21..16e54ba890 100644 --- a/packages/auth-browser/src/lib/chains/sol.ts +++ b/packages/auth-browser/src/lib/chains/sol.ts @@ -84,7 +84,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { const res = await connectSolProvider(); if (!res) { - logDebug'Failed to connect sol provider'); + log('Failed to connect sol provider'); } const provider = res?.provider; @@ -98,7 +98,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- case: if unable to get auth from local storage if (authSigOrError.type === EITHER_TYPE.ERROR) { - logDebug'signing auth message because sig is not in local storage'); + log('signing auth message because sig is not in local storage'); await signAndSaveAuthMessage({ provider }); @@ -122,7 +122,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- if the wallet address isn't the same as the address from local storage if (account !== authSig.address) { - logDebug + log( 'signing auth message because account is not the same as the address in the auth sig' ); @@ -135,7 +135,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { authSig = JSON.parse(authSigOrError.result); } - logDebug'authSig', authSig); + log('authSig', authSig); return authSig; }; diff --git a/packages/bls-sdk/README.md b/packages/bls-sdk/README.md index 3f751b9f47..2ca8c7d66e 100644 --- a/packages/bls-sdk/README.md +++ b/packages/bls-sdk/README.md @@ -17,7 +17,7 @@ import { initWasmBlsSdk } from '@lit-protocol/bls-sdk'; initWasmBlsSdk().then((exports) => { globalThis.wasmExports = exports; - logDebug + log( `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index 9668817360..fe235e5514 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -139,7 +139,7 @@ export class LitCore { // If the user sets a new storage provider we respect it over our default storage // If the user sets a new file path, we respect it over the default path. if (this.config.storageProvider?.provider) { - logDebug + log( 'localstorage api not found, injecting persistance instance found in config' ); // using Object definProperty in order to set a property previously defined as readonly. @@ -152,7 +152,7 @@ export class LitCore { !globalThis.localStorage && !this.config.storageProvider?.provider ) { - logDebug + log( 'Looks like you are running in NodeJS and did not provide a storage provider, youre sessions will not be cached' ); } @@ -186,7 +186,7 @@ export class LitCore { const bootstrapUrls = await LitContracts.getValidators( this.config.litNetwork as LitNetwork ); - logDebug'Bootstrap urls: ', bootstrapUrls); + log('Bootstrap urls: ', bootstrapUrls); if (minNodeCount <= 0) { throwError({ message: `minNodeCount is ${minNodeCount}, which is invalid. Please check your network connection and try again.`, @@ -232,12 +232,12 @@ export class LitCore { const stakingContract = await LitContracts.getStakingContract( this.config.litNetwork as any ); - logDebug + log( 'listening for state change on staking contract: ', stakingContract.address ); stakingContract.on('StateChanged', async (state: StakingStates) => { - logDebug`New state detected: "${state}"`); + log(`New state detected: "${state}"`); if (state === StakingStates.NextValidatorSetLocked) { await this.setNewConfig(); } @@ -339,12 +339,12 @@ export class LitCore { }); } else { // actually verify the attestation by checking the signature against AMD certs - logDebug'Checking attestation against amd certs...'); + log('Checking attestation against amd certs...'); const attestation = resp.attestation; try { checkSevSnpAttestation(attestation, challenge, url).then(() => { - logDebug`Lit Node Attestation verified for ${url}`); + log(`Lit Node Attestation verified for ${url}`); // only set server keys if attestation is valid // so that we don't use this node if it's not valid @@ -368,7 +368,7 @@ export class LitCore { } }) .catch((e: any) => { - logDebug'Error connecting to node ', url, e); + log('Error connecting to node ', url, e); }); } @@ -424,10 +424,10 @@ export class LitCore { this.ready = true; - logDebug + log( `🔥 lit is ready. "litNodeClient" variable is ready to use globally.` ); - logDebug'current network config', { + log('current network config', { networkPubkey: this.networkPubKey, networkPubKeySet: this.networkPubKeySet, hdRootPubkeys: this.hdRootPubkeys, @@ -509,7 +509,7 @@ export class LitCore { // -- create url with path const urlWithPath = `${url}/web/handshake`; - logDebug`handshakeWithNode ${urlWithPath}`); + log(`handshakeWithNode ${urlWithPath}`); const data = { clientPublicKey: 'test', @@ -627,7 +627,7 @@ export class LitCore { errorCode: LIT_ERROR.INVALID_ARGUMENT_EXCEPTION.name, }); } else { - logDebug`authSig or sessionSigs not found. This may be using authMethod`); + log(`authSig or sessionSigs not found. This may be using authMethod`); } } @@ -763,7 +763,7 @@ export class LitCore { res.error.errorCode === 'not_authorized') && this.config.alertWhenUnauthorized ) { - logDebug + log( '[Alert originally] You are not authorized to access to this content' ); } @@ -814,7 +814,7 @@ export class LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - logDebug + log( 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -822,7 +822,7 @@ export class LitCore { formattedEVMContractConditions = evmContractConditions.map((c: any) => canonicalEVMContractConditionFormatter(c) ); - logDebug + log( 'formattedEVMContractConditions', JSON.stringify(formattedEVMContractConditions) ); @@ -830,7 +830,7 @@ export class LitCore { formattedSolRpcConditions = solRpcConditions.map((c: any) => canonicalSolRpcConditionFormatter(c) ); - logDebug + log( 'formattedSolRpcConditions', JSON.stringify(formattedSolRpcConditions) ); @@ -839,7 +839,7 @@ export class LitCore { unifiedAccessControlConditions.map((c: any) => canonicalUnifiedAccessControlConditionFormatter(c) ); - logDebug + log( 'formattedUnifiedAccessControlConditions', JSON.stringify(formattedUnifiedAccessControlConditions) ); diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index eeab382d04..8e8dc13d64 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -26,7 +26,7 @@ if (!globalThis.wasmExports) { globalThis.wasmExports = exports; if (!globalThis.jestTesting) { - logDebug + log( `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` @@ -49,7 +49,7 @@ if (!globalThis.wasmECDSA) { globalThis.wasmECDSA = sdk; if (!globalThis.jestTesting) { - logDebug + log( `✅ [ECDSA SDK ${env}] wasmECDSA loaded. ${ Object.keys(wasmECDSA).length } functions available. Run 'wasmECDSA' in the console to see them.` @@ -63,7 +63,7 @@ if (!globalThis.wasmSevSnpUtils) { globalThis.wasmSevSnpUtils = exports; if (!globalThis.jestTesting) { - logDebug + log( `✅ [SEV SNP Utils SDK] wasmSevSnpUtils loaded. ${ Object.keys(exports).length } functions available. Run 'wasmSevSnpUtils' in the console to see them.` @@ -224,7 +224,7 @@ export const combineEcdsaShares = ( return acc; }, []); - logDebug'Valid Shares:', validShares); + log('Valid Shares:', validShares); // if there are no valid shares, throw an error if (validShares.length === 0) { @@ -267,7 +267,7 @@ export const combineEcdsaShares = ( break; case SIGTYPE.ECDSCAITSITHP256: res = ecdsaSdk.combine_signature(validShares, 3); - logDebug'response from combine_signature', res); + log('response from combine_signature', res); sig = JSON.parse(res); break; // if its another sig type, it shouldnt be resolving to this method @@ -277,10 +277,10 @@ export const combineEcdsaShares = ( ); } } catch (e) { - logDebug'Failed to combine signatures:', e); + log('Failed to combine signatures:', e); } - logDebug'signature', sig); + log('signature', sig); return sig; }; @@ -298,7 +298,7 @@ export const computeHDPubKey = ( defualt: throw new Error('Non supported signature type'); } } catch (e) { - logDebug'Failed to derive public key', e); + log('Failed to derive public key', e); } }; diff --git a/packages/encryption/src/lib/encryption.ts b/packages/encryption/src/lib/encryption.ts index b18b128eef..0da27ca35e 100644 --- a/packages/encryption/src/lib/encryption.ts +++ b/packages/encryption/src/lib/encryption.ts @@ -377,7 +377,7 @@ export const zipAndEncryptFiles = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - logDebug"Failed to get 'encryptedAssets' from zip.folder() "); + log("Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: "Failed to get 'encryptedAssets' from zip.folder() ", errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -561,7 +561,7 @@ export const encryptFileAndZipWithMetadata = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - logDebug"Failed to get 'encryptedAssets' from zip.folder() "); + log("Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: `Failed to get 'encryptedAssets' from zip.folder()`, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -620,25 +620,25 @@ export const decryptZipFileWithMetadata = async ( ); if (!jsonFile) { - logDebug`Failed to read lit_protocol_metadata.json while zip.file()`); + log(`Failed to read lit_protocol_metadata.json while zip.file()`); return; } const metadata: MetadataForFile = JSON.parse(await jsonFile.async('string')); - logDebug'zip metadata', metadata); + log('zip metadata', metadata); const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - logDebug"Failed to get 'encryptedAssets' from zip.folder() "); + log("Failed to get 'encryptedAssets' from zip.folder() "); return; } const _file: JSZip.JSZipObject | null = folder.file(metadata.name); if (!_file) { - logDebug"Failed to get 'metadata.name' while zip.folder().file()"); + log("Failed to get 'metadata.name' while zip.folder().file()"); return; } @@ -767,11 +767,11 @@ export const verifyJwt = ({ errorCode: LIT_ERROR.INVALID_PARAM_TYPE.name, }); - logDebug'verifyJwt', jwt); + log('verifyJwt', jwt); // verify that the wasm was loaded if (!globalThis.wasmExports) { - logDebug'wasmExports is not loaded.'); + log('wasmExports is not loaded.'); } const jwtParts = jwt.split('.'); diff --git a/packages/encryption/src/lib/params-validators.ts b/packages/encryption/src/lib/params-validators.ts index 54feed42ed..08fd6813ca 100644 --- a/packages/encryption/src/lib/params-validators.ts +++ b/packages/encryption/src/lib/params-validators.ts @@ -50,7 +50,7 @@ export const safeParams = ({ params: any[] | any; }): IEither => { if (!paramsValidators[functionName]) { - logDebug`This function ${functionName} is skipping params safe guarding.`); + log(`This function ${functionName} is skipping params safe guarding.`); return ERight(undefined); } diff --git a/packages/lit-auth-client/src/lib/lit-auth-client.ts b/packages/lit-auth-client/src/lib/lit-auth-client.ts index 8c6d60061a..35b7bb8116 100644 --- a/packages/lit-auth-client/src/lib/lit-auth-client.ts +++ b/packages/lit-auth-client/src/lib/lit-auth-client.ts @@ -88,9 +88,9 @@ export class LitAuthClient { // Set RPC URL this.rpcUrl = options?.rpcUrl || 'https://chain-rpc.litprotocol.com/http'; - logDebug'rpc url: ', this.rpcUrl); - logDebug'relay config: ', options.litRelayConfig); - logDebug'relay instance: ', this.relay); + log('rpc url: ', this.rpcUrl); + log('relay config: ', options.litRelayConfig); + log('relay instance: ', this.relay); } /** @@ -112,7 +112,7 @@ export class LitAuthClient { }; let provider: T; - logDebug'resolving provider of type: ', type); + log('resolving provider of type: ', type); switch (type) { case 'google': provider = new GoogleProvider({ @@ -232,7 +232,7 @@ export class LitAuthClient { authId = await StytchAuthFactorOtpProvider.authMethodId(authMethod); break; default: - logDebug`unsupported AuthMethodType: ${authMethod.authMethodType}`); + log(`unsupported AuthMethodType: ${authMethod.authMethodType}`); throw new Error( `Unsupported auth method type: ${authMethod.authMethodType}` ); diff --git a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts index aebb36ae9a..c93000581c 100644 --- a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts +++ b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts @@ -28,7 +28,7 @@ export default class EthWalletProvider extends BaseProvider { this.domain = options.domain || window.location.hostname; this.origin = options.origin || window.location.origin; } catch (e) { - logDebug + log( '⚠️ Error getting "domain" and "origin" from window object, defaulting to "localhost" and "http://localhost"' ); this.domain = options.domain || 'localhost'; diff --git a/packages/lit-auth-client/src/lib/relay.ts b/packages/lit-auth-client/src/lib/relay.ts index 3fb566b299..762c208fe5 100644 --- a/packages/lit-auth-client/src/lib/relay.ts +++ b/packages/lit-auth-client/src/lib/relay.ts @@ -39,7 +39,7 @@ export class LitRelay implements IRelay { this.relayUrl = config.relayUrl || 'https://relayer-server-staging-cayenne.getlit.dev'; this.relayApiKey = config.relayApiKey || ''; - logDebug"Lit's relay server URL:", this.relayUrl); + log("Lit's relay server URL:", this.relayUrl); } /** @@ -60,12 +60,12 @@ export class LitRelay implements IRelay { }); if (response.status < 200 || response.status >= 400) { - logDebug'Something wrong with the API call', await response.json()); + log('Something wrong with the API call', await response.json()); const err = new Error('Unable to mint PKP through relay server'); throw err; } else { const resBody = await response.json(); - logDebug'Successfully initiated minting PKP with relayer'); + log('Successfully initiated minting PKP with relayer'); return resBody; } } @@ -96,7 +96,7 @@ export class LitRelay implements IRelay { ); if (response.status < 200 || response.status >= 400) { - logDebug'Something wrong with the API call', await response.json()); + log('Something wrong with the API call', await response.json()); const err = new Error( `Unable to poll the status of this mint PKP transaction: ${requestId}` ); @@ -104,18 +104,18 @@ export class LitRelay implements IRelay { } const resBody = await response.json(); - logDebug'Response OK', { body: resBody }); + log('Response OK', { body: resBody }); if (resBody.error) { // exit loop since error - logDebug'Something wrong with the API call', { + log('Something wrong with the API call', { error: resBody.error, }); const err = new Error(resBody.error); throw err; } else if (resBody.status === 'Succeeded') { // exit loop since success - logDebug'Successfully authed', { ...resBody }); + log('Successfully authed', { ...resBody }); return resBody; } diff --git a/packages/lit-auth-client/src/lib/utils.ts b/packages/lit-auth-client/src/lib/utils.ts index 06f4c96426..2bf6062b06 100644 --- a/packages/lit-auth-client/src/lib/utils.ts +++ b/packages/lit-auth-client/src/lib/utils.ts @@ -309,7 +309,7 @@ export function unparse(buf: any) { ); } -export function logDebug...args: any) { +export function log(...args: any) { const logger = getLoggerbyId('auth-client'); logger.debug(...args); } diff --git a/packages/lit-node-client-nodejs/src/index.ts b/packages/lit-node-client-nodejs/src/index.ts index a5e9d91e8a..9a9aa68354 100644 --- a/packages/lit-node-client-nodejs/src/index.ts +++ b/packages/lit-node-client-nodejs/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClientNodeJs from './lib/lit-node-client-nodejs'; // ==================== Environment ==================== if (isNode()) { - logDebug'Oh hey you are running in Node.js!'); + log('Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index e7e14ab27e..76bf0630ba 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -215,7 +215,7 @@ export class LitNodeClientNodeJs extends LitCore { try { response = JSON.parse(responseString); } catch (e) { - logDebug + log( 'Error parsing response as json. Swallowing and returning as string.', responseString ); @@ -341,7 +341,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (TRY) to get it in the local storage // -- IF NOT: Generates one - logDebug`getWalletSig - flow starts + log(`getWalletSig - flow starts storageKey: ${storageKey} storedWalletSigOrError: ${JSON.stringify(storedWalletSigOrError)} `); @@ -351,12 +351,12 @@ export class LitNodeClientNodeJs extends LitCore { !storedWalletSigOrError.result || storedWalletSigOrError.result == '' ) { - logDebug'getWalletSig - flow 1'); + log('getWalletSig - flow 1'); console.warn( `Storage key "${storageKey}" is missing. Not a problem. Continue...` ); if (authNeededCallback) { - logDebug'getWalletSig - flow 1.1'); + log('getWalletSig - flow 1.1'); const body = { chain, statement: sessionCapabilityObject?.statement, @@ -369,13 +369,13 @@ export class LitNodeClientNodeJs extends LitCore { nonce, }; - logDebug'callback body:', body); + log('callback body:', body); walletSig = await authNeededCallback(body); } else { - logDebug'getWalletSig - flow 1.2'); + log('getWalletSig - flow 1.2'); if (!this.defaultAuthCallback) { - logDebug'getWalletSig - flow 1.2.1'); + log('getWalletSig - flow 1.2.1'); return throwError({ message: 'No default auth callback provided', errorKind: LIT_ERROR.PARAMS_MISSING_ERROR.kind, @@ -383,7 +383,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - logDebug'getWalletSig - flow 1.2.2'); + log('getWalletSig - flow 1.2.2'); walletSig = await this.defaultAuthCallback({ chain, statement: sessionCapabilityObject.statement, @@ -397,7 +397,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - logDebug'getWalletSig - flow 1.3'); + log('getWalletSig - flow 1.3'); // (TRY) to set walletSig to local storage const storeNewWalletSigOrError = setStorageItem( @@ -405,23 +405,23 @@ export class LitNodeClientNodeJs extends LitCore { JSON.stringify(walletSig) ); if (storeNewWalletSigOrError.type === 'ERROR') { - logDebug'getWalletSig - flow 1.4'); + log('getWalletSig - flow 1.4'); console.warn( `Unable to store walletSig in local storage. Not a problem. Continue...` ); } } else { - logDebug'getWalletSig - flow 2'); + log('getWalletSig - flow 2'); try { walletSig = JSON.parse(storedWalletSigOrError.result as string); - logDebug'getWalletSig - flow 2.1'); + log('getWalletSig - flow 2.1'); } catch (e) { console.warn('Error parsing walletSig', e); - logDebug'getWalletSig - flow 2.2'); + log('getWalletSig - flow 2.2'); } } - logDebug'getWalletSig - flow 3'); + log('getWalletSig - flow 3'); return walletSig!; }; @@ -648,7 +648,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSigningShareForDecryptionRequest, requestId: string ): Promise => { - logDebug'getSigningShareForDecryption'); + log('getSigningShareForDecryption'); const urlWithPath = `${url}/web/encryption/sign`; return await this.sendCommandToNode({ @@ -673,7 +673,7 @@ export class LitNodeClientNodeJs extends LitCore { params: SignConditionECDSA, requestId: string ): Promise => { - logDebug'signConditionEcdsa'); + log('signConditionEcdsa'); const urlWithPath = `${url}/web/signing/signConditionEcdsa`; const data = { @@ -784,7 +784,7 @@ export class LitNodeClientNodeJs extends LitCore { targetNodeRange, } = params; - logDebug'running runOnTargetedNodes:', targetNodeRange); + log('running runOnTargetedNodes:', targetNodeRange); if (!targetNodeRange) { return throwError({ @@ -852,7 +852,7 @@ export class LitNodeClientNodeJs extends LitCore { .mod(this.config.bootstrapUrls.length) .toNumber(); - logDebug'nodeIndex:', nodeIndex); + log('nodeIndex:', nodeIndex); // must be unique & less than bootstrapUrls.length if ( @@ -864,7 +864,7 @@ export class LitNodeClientNodeJs extends LitCore { nodeCounter++; } - logDebug'Final Selected Indexes:', randomSelectedNodeIndexes); + log('Final Selected Indexes:', randomSelectedNodeIndexes); const requestId = this.getRequestId(); const nodePromises = []; @@ -881,7 +881,7 @@ export class LitNodeClientNodeJs extends LitCore { // because the staking nodes can change, and the rust code will use the same list const url = this.config.bootstrapUrls[nodeIndex]; - logDebug`running on node ${nodeIndex} at ${url}`); + log(`running on node ${nodeIndex} at ${url}`); const reqBody: JsonExecutionRequest = this.getLitActionRequestBody(params); @@ -1011,20 +1011,20 @@ export class LitNodeClientNodeJs extends LitCore { // -- execute keys.forEach((key: any) => { - logDebug'key:', key); + log('key:', key); const shares = signedData.map((r: any) => r[key]); - logDebug'shares:', shares); + log('shares:', shares); shares.sort((a: any, b: any) => a.shareIndex - b.shareIndex); const sigShares: Array = shares.map((s: any, index: number) => { - logDebug'Original Share Struct:', s); + log('Original Share Struct:', s); const share = this._getFlattenShare(s); - logDebug'share:', share); + log('share:', share); if (!share) { throw new Error('share is null or undefined'); @@ -1039,8 +1039,8 @@ export class LitNodeClientNodeJs extends LitCore { const sanitisedBigR = sanitise(share.bigr); const sanitisedSigShare = sanitise(share.publicKey); - logDebug'sanitisedBigR:', sanitisedBigR); - logDebug'sanitisedSigShare:', sanitisedSigShare); + log('sanitisedBigR:', sanitisedBigR); + log('sanitisedSigShare:', sanitisedSigShare); return { sigType: share.sigType, @@ -1053,7 +1053,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - logDebug'getSessionSignatures - sigShares', sigShares); + log('getSessionSignatures - sigShares', sigShares); const sigType = mostCommonString(sigShares.map((s: any) => s.sigType)); @@ -1502,7 +1502,7 @@ export class LitNodeClientNodeJs extends LitCore { logs: mostCommonLogs, }; - logDebug'returnVal:', returnVal); + log('returnVal:', returnVal); // -- case: debug mode if (debug) { @@ -1746,7 +1746,7 @@ export class LitNodeClientNodeJs extends LitCore { res as SuccessNodePromises ).values; - logDebug'signatureShares', signatureShares); + log('signatureShares', signatureShares); // ========== Result ========== const finalJwt: string = this.combineSharesAndGetJWT( @@ -2072,7 +2072,7 @@ export class LitNodeClientNodeJs extends LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - logDebug + log( 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -2105,7 +2105,7 @@ export class LitNodeClientNodeJs extends LitCore { return signature; } catch (e) { - logDebug'Error - signed_ecdsa_messages - ', e); + log('Error - signed_ecdsa_messages - ', e); const signed_ecdsa_message = nodePromises[0]; return signed_ecdsa_message; } @@ -2199,7 +2199,7 @@ export class LitNodeClientNodeJs extends LitCore { let res; try { res = await this.handleNodePromises(nodePromises, requestId); - logDebug'signSessionKey node promises:', res); + log('signSessionKey node promises:', res); } catch (e) { throw new Error(`Error when handling node promises: ${e}`); } @@ -2246,7 +2246,7 @@ export class LitNodeClientNodeJs extends LitCore { // check if all required fields are present for (const field of requiredFields) { if (!sessionSig[field] || sessionSig[field] === '') { - logDebug + log( `Invalid signed data. ${field} is missing. Not a problem, we only need ${this.config.minNodeCount} nodes to sign the session key.` ); return null; @@ -2298,7 +2298,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSignSessionKeySharesProp, requestId: string ) => { - logDebug'getSignSessionKeyShares'); + log('getSignSessionKeyShares'); const urlWithPath = `${url}/web/sign_session_key`; return await this.sendCommandToNode({ url: urlWithPath, @@ -2387,7 +2387,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (CHECK) if we need to resign the session key if (needToResignSessionKey) { - logDebug'need to re-sign session key. Signing...'); + log('need to re-sign session key. Signing...'); authSig = await this.#authCallbackAndUpdateStorageItem({ authCallback: params.authNeededCallback, authCallbackParams: { @@ -2448,7 +2448,7 @@ export class LitNodeClientNodeJs extends LitCore { const uint8arrayMessage = uint8arrayFromString(signedMessage, 'utf8'); let signature = nacl.sign.detached(uint8arrayMessage, uint8arrayKey); - // logDebug"signature", signature); + // log("signature", signature); signatures[nodeAddress] = { sig: uint8arrayToString(signature, 'base16'), derivedVia: 'litSessionSignViaNacl', @@ -2458,7 +2458,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - logDebug'signatures:', signatures); + log('signatures:', signatures); return signatures; }; diff --git a/packages/lit-node-client/src/index.ts b/packages/lit-node-client/src/index.ts index 0137f2a10c..91c73a1761 100644 --- a/packages/lit-node-client/src/index.ts +++ b/packages/lit-node-client/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClient from './lib/lit-node-client'; // ==================== Environment ==================== if (isNode()) { - logDebug'Oh hey you are running in Node.js!'); + log('Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client/src/lib/lit-node-client.ts b/packages/lit-node-client/src/lib/lit-node-client.ts index fa6cb1b7d1..603a451e1a 100644 --- a/packages/lit-node-client/src/lib/lit-node-client.ts +++ b/packages/lit-node-client/src/lib/lit-node-client.ts @@ -31,7 +31,7 @@ export class LitNodeClient extends LitNodeClientNodeJs { // -- validate if (storageConfigOrError.type === EITHER_TYPE.ERROR) { - logDebug`Storage key "${storageKey}" is missing. `); + log(`Storage key "${storageKey}" is missing. `); return; } diff --git a/packages/logger/src/lib/logger.ts b/packages/logger/src/lib/logger.ts index c292830548..0ed28c4b6a 100644 --- a/packages/logger/src/lib/logger.ts +++ b/packages/logger/src/lib/logger.ts @@ -290,7 +290,7 @@ export class Logger { } private _log(level: LogLevel, message: string = '', ...args: any[]): void { - const log = new logDebug + const log = new Log( new Date().toISOString(), message, args, diff --git a/packages/pkp-base/src/lib/pkp-base.ts b/packages/pkp-base/src/lib/pkp-base.ts index 1ec90d0054..4b7a90e740 100644 --- a/packages/pkp-base/src/lib/pkp-base.ts +++ b/packages/pkp-base/src/lib/pkp-base.ts @@ -398,7 +398,7 @@ export class PKPBase { * @returns {void} - This function does not return a value. */ - logDebug...args: any[]): void { + log(...args: any[]): void { if (this.debug) { console.log(this.orange + this.PREFIX + this.reset, ...args); } diff --git a/packages/pkp-client/src/lib/pkp-client.ts b/packages/pkp-client/src/lib/pkp-client.ts index 11fea9b67c..44a58e4e84 100644 --- a/packages/pkp-client/src/lib/pkp-client.ts +++ b/packages/pkp-client/src/lib/pkp-client.ts @@ -115,7 +115,7 @@ export class PKPClient { ).length; if (successfulInits !== this._wallets.size) { - logDebug + log( `Not all wallets initialized successfully. Details: ${JSON.stringify( walletStatus, null, diff --git a/packages/sev-snp-utils-sdk/README.md b/packages/sev-snp-utils-sdk/README.md index 240718373c..4fff08a3b8 100644 --- a/packages/sev-snp-utils-sdk/README.md +++ b/packages/sev-snp-utils-sdk/README.md @@ -17,7 +17,7 @@ import { initSevSnpUtilsSdk } from '@lit-protocol/sev-snp-utils-sdk'; initSevSnpUtilsSdk().then((exports) => { globalThis.wasmExports = exports; - logDebug + log( `✅ [SEV SNP Utils SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` From 759b820b40bfa7e298877e9cc0f14e4792fa0d0e Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:35:26 -0500 Subject: [PATCH 06/11] fixed bad replace of log with logDebug --- .../src/lib/hashing.ts | 12 +-- .../src/lib/humanizer.ts | 28 ++--- .../auth-browser/src/lib/chains/cosmos.ts | 6 +- packages/auth-browser/src/lib/chains/eth.ts | 100 +++++++++--------- packages/auth-browser/src/lib/chains/sol.ts | 8 +- packages/bls-sdk/README.md | 2 +- packages/core/src/lib/lit-core.ts | 36 ++++--- packages/crypto/src/lib/crypto.ts | 16 +-- packages/encryption/src/lib/encryption.ts | 16 +-- .../encryption/src/lib/params-validators.ts | 2 +- .../src/lib/lit-auth-client.ts | 10 +- .../src/lib/providers/EthWalletProvider.ts | 2 +- packages/lit-auth-client/src/lib/relay.ts | 14 +-- packages/lit-auth-client/src/lib/utils.ts | 2 +- packages/lit-node-client-nodejs/src/index.ts | 2 +- .../src/lib/lit-node-client-nodejs.ts | 80 +++++++------- packages/lit-node-client/src/index.ts | 2 +- .../src/lib/lit-node-client.ts | 2 +- packages/logger/src/lib/logger.ts | 2 +- packages/pkp-base/src/lib/pkp-base.ts | 2 +- packages/pkp-client/src/lib/pkp-client.ts | 2 +- packages/sev-snp-utils-sdk/README.md | 2 +- 22 files changed, 177 insertions(+), 171 deletions(-) diff --git a/packages/access-control-conditions/src/lib/hashing.ts b/packages/access-control-conditions/src/lib/hashing.ts index e3b3dbbeda..6fc2faabc3 100644 --- a/packages/access-control-conditions/src/lib/hashing.ts +++ b/packages/access-control-conditions/src/lib/hashing.ts @@ -29,14 +29,14 @@ import { uint8arrayToString } from '@lit-protocol/uint8arrays'; export const hashUnifiedAccessControlConditions = ( unifiedAccessControlConditions: UnifiedAccessControlConditions ): Promise => { - log('unifiedAccessControlConditions:', unifiedAccessControlConditions); + logDebug('unifiedAccessControlConditions:', unifiedAccessControlConditions); const conditions = unifiedAccessControlConditions.map( (condition: ConditionItem) => { return canonicalUnifiedAccessControlConditionFormatter(condition); } ); - log('conditions:', conditions); + logDebug('conditions:', conditions); // check if there's any undefined in the conditions const hasUndefined = conditions.some((c) => c === undefined); @@ -57,7 +57,7 @@ export const hashUnifiedAccessControlConditions = ( } const toHash = JSON.stringify(conditions); - log('Hashing unified access control conditions: ', toHash); + logDebug('Hashing unified access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -116,7 +116,7 @@ export const hashAccessControlConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing access control conditions: ', toHash); + logDebug('Hashing access control conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); @@ -140,7 +140,7 @@ export const hashEVMContractConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing evm contract conditions: ', toHash); + logDebug('Hashing evm contract conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); return crypto.subtle.digest('SHA-256', data); @@ -163,7 +163,7 @@ export const hashSolRpcConditions = ( ); const toHash = JSON.stringify(conds); - log('Hashing sol rpc conditions: ', toHash); + logDebug('Hashing sol rpc conditions: ', toHash); const encoder = new TextEncoder(); const data = encoder.encode(toHash); diff --git a/packages/access-control-conditions/src/lib/humanizer.ts b/packages/access-control-conditions/src/lib/humanizer.ts index 363f4309e1..64d79aa76e 100644 --- a/packages/access-control-conditions/src/lib/humanizer.ts +++ b/packages/access-control-conditions/src/lib/humanizer.ts @@ -60,7 +60,7 @@ export const humanizeComparator = (comparator: string): string | undefined => { let selected: string | undefined = list[comparator]; if (!selected) { - log(`Unregonized comparator ${comparator}`); + logDebug(`Unregonized comparator ${comparator}`); return; } @@ -86,9 +86,9 @@ export const humanizeEvmBasicAccessControlConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing evm basic access control conditions'); - log('myWalletAddress', myWalletAddress); - log('accessControlConditions', accessControlConditions); + logDebug('humanizing evm basic access control conditions'); + logDebug('myWalletAddress', myWalletAddress); + logDebug('accessControlConditions', accessControlConditions); let fixedConditions: any = accessControlConditions; @@ -235,7 +235,7 @@ export const humanizeEvmBasicAccessControlConditions = async ({ console.log(`Failed to get decimals for ${acc.contractAddress}`); } } - log('decimals', decimals); + logDebug('decimals', decimals); return `Owns ${humanizeComparator( acc.returnValueTest.comparator )} ${formatUnits(acc.returnValueTest.value, decimals)} of ${ @@ -286,9 +286,9 @@ export const humanizeEvmContractConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing evm contract conditions'); - log('myWalletAddress', myWalletAddress); - log('evmContractConditions', evmContractConditions); + logDebug('humanizing evm contract conditions'); + logDebug('myWalletAddress', myWalletAddress); + logDebug('evmContractConditions', evmContractConditions); const promises = await Promise.all( evmContractConditions.map(async (acc: any) => { @@ -347,9 +347,9 @@ export const humanizeSolRpcConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing sol rpc conditions'); - log('myWalletAddress', myWalletAddress); - log('solRpcConditions', solRpcConditions); + logDebug('humanizing sol rpc conditions'); + logDebug('myWalletAddress', myWalletAddress); + logDebug('solRpcConditions', solRpcConditions); const promises = await Promise.all( solRpcConditions.map(async (acc: any) => { @@ -421,9 +421,9 @@ export const humanizeCosmosConditions = async ({ tokenList?: Array; myWalletAddress?: string; }): Promise => { - log('humanizing cosmos conditions'); - log('myWalletAddress', myWalletAddress); - log('cosmosConditions', cosmosConditions); + logDebug('humanizing cosmos conditions'); + logDebug('myWalletAddress', myWalletAddress); + logDebug('cosmosConditions', cosmosConditions); const promises = await Promise.all( cosmosConditions.map(async (acc: any) => { diff --git a/packages/auth-browser/src/lib/chains/cosmos.ts b/packages/auth-browser/src/lib/chains/cosmos.ts index 1378971a34..e4786d01f6 100644 --- a/packages/auth-browser/src/lib/chains/cosmos.ts +++ b/packages/auth-browser/src/lib/chains/cosmos.ts @@ -142,7 +142,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- if not found in local storage if (!authSig) { - log('signing auth message because sig is not in local storage'); + logDebug('signing auth message because sig is not in local storage'); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -154,7 +154,7 @@ export const checkAndSignCosmosAuthMessage = async ({ // -- validate if (connectedCosmosProvider.account != authSig.address) { - log( + logDebug( 'signing auth message because account is not the same as the address in the auth sig' ); await signAndSaveAuthMessage(connectedCosmosProvider); @@ -162,7 +162,7 @@ export const checkAndSignCosmosAuthMessage = async ({ authSig = JSON.parse(authSig); } - log('authSig', authSig); + logDebug('authSig', authSig); return authSig; }; diff --git a/packages/auth-browser/src/lib/chains/eth.ts b/packages/auth-browser/src/lib/chains/eth.ts index 3e6a95e50b..36fcac0eb8 100644 --- a/packages/auth-browser/src/lib/chains/eth.ts +++ b/packages/auth-browser/src/lib/chains/eth.ts @@ -46,15 +46,15 @@ if (typeof global.Buffer === 'undefined') { global.Buffer = BufferPolyfill; } -// log("naclUtil:", naclUtil); -// log("nacl:", nacl); +// logDebug("naclUtil:", naclUtil); +// logDebug("nacl:", nacl); // -- fix import issues // let _nacl = nacl === undefined ? nacl['default'] : nacl; // let _naclUtil = naclUtil === undefined ? naclUtil['default'] : naclUtil; -// log("_nacl:", _nacl); -// log("_naclUtil:", _naclUtil); +// logDebug("_nacl:", _nacl); +// logDebug("_naclUtil:", _naclUtil); /** ---------- Local Interfaces ---------- */ interface ConnectWeb3 { @@ -203,7 +203,7 @@ export const getChainId = async ( resultOrError = ERight(resp.chainId); } catch (e) { // couldn't get chainId. throw the incorrect network error - log('getNetwork threw an exception', e); + logDebug('getNetwork threw an exception', e); resultOrError = ELeft({ message: `Incorrect network selected. Please switch to the ${chain} network in your wallet and try again.`, @@ -251,23 +251,23 @@ export const getMustResign = (authSig: AuthSig, resources: any): boolean => { try { const parsedSiwe = new SiweMessage(authSig.signedMessage); - log('parsedSiwe.resources', parsedSiwe.resources); + logDebug('parsedSiwe.resources', parsedSiwe.resources); if (JSON.stringify(parsedSiwe.resources) !== JSON.stringify(resources)) { - log( + logDebug( 'signing auth message because resources differ from the resources in the auth sig' ); mustResign = true; } if (parsedSiwe.address !== getAddress(parsedSiwe.address)) { - log( + logDebug( 'signing auth message because parsedSig.address is not equal to the same address but checksummed. This usually means the user had a non-checksummed address saved and so they need to re-sign.' ); mustResign = true; } } catch (e) { - log('error parsing siwe sig. making the user sign again: ', e); + logDebug('error parsing siwe sig. making the user sign again: ', e); mustResign = true; } @@ -354,7 +354,7 @@ export const connectWeb3 = async ({ }: ConnectWeb3): Promise => { // -- check if it's nodejs if (isNode()) { - log('connectWeb3 is not supported in nodejs.'); + logDebug('connectWeb3 is not supported in nodejs.'); return { web3: null, account: null }; } @@ -383,35 +383,35 @@ export const connectWeb3 = async ({ } } - log('getting provider via lit connect modal'); + logDebug('getting provider via lit connect modal'); const dialog = new LitConnectModal({ providerOptions }); const provider = await dialog.getWalletProvider(); - log('got provider'); + logDebug('got provider'); // @ts-ignore const web3 = new Web3Provider(provider); // trigger metamask popup try { - log( + logDebug( '@deprecated soon to be removed. - trying to enable provider. this will trigger the metamask popup.' ); // @ts-ignore await provider.enable(); } catch (e) { - log( + logDebug( "error enabling provider but swallowed it because it's not important. most wallets use a different function now to enable the wallet so you can ignore this error, because those other methods will be tried.", e ); } - log('listing accounts'); + logDebug('listing accounts'); const accounts = await web3.listAccounts(); - log('accounts', accounts); + logDebug('accounts', accounts); const account = accounts[0].toLowerCase(); return { web3, account }; @@ -427,7 +427,7 @@ export const connectWeb3 = async ({ */ export const disconnectWeb3 = (): void => { if (isNode()) { - log('disconnectWeb3 is not supported in nodejs.'); + logDebug('disconnectWeb3 is not supported in nodejs.'); return; } @@ -437,7 +437,7 @@ export const disconnectWeb3 = (): void => { // @ts-ignore globalThis.litWCProvider.disconnect(); } catch (err) { - log( + logDebug( 'Attempted to disconnect global WalletConnectProvider for lit-connect-modal', err ); @@ -471,7 +471,7 @@ export const checkAndSignEVMAuthMessage = async ({ }: AuthCallbackParams): Promise => { // -- check if it's nodejs if (isNode()) { - log( + logDebug( 'checkAndSignEVMAuthMessage is not supported in nodejs. You can create a SIWE on your own using the SIWE package.' ); return { @@ -504,7 +504,7 @@ export const checkAndSignEVMAuthMessage = async ({ walletConnectProjectId, }); - log(`got web3 and account: ${account}`); + logDebug(`got web3 and account: ${account}`); // -- 2. prepare all required variables const currentChainIdOrError = await getChainId(chain, web3); @@ -512,18 +512,18 @@ export const checkAndSignEVMAuthMessage = async ({ const selectedChainIdHex: string = numberToHex(selectedChainId); const authSigOrError = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE); - log('currentChainIdOrError:', currentChainIdOrError); - log('selectedChainId:', selectedChainId); - log('selectedChainIdHex:', selectedChainIdHex); - log('authSigOrError:', authSigOrError); + logDebug('currentChainIdOrError:', currentChainIdOrError); + logDebug('selectedChainId:', selectedChainId); + logDebug('selectedChainIdHex:', selectedChainIdHex); + logDebug('authSigOrError:', authSigOrError); // -- 3. check all variables before executing business logic if (currentChainIdOrError.type === EITHER_TYPE.ERROR) { return throwError(currentChainIdOrError.result as any); } - log('chainId from web3', currentChainIdOrError); - log( + logDebug('chainId from web3', currentChainIdOrError); + logDebug( `checkAndSignAuthMessage with chainId ${currentChainIdOrError} and chain set to ${chain} and selectedChain is `, selectedChain ); @@ -542,7 +542,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if able to switch chain id try { - log('trying to switch to chainId', selectedChainIdHex); + logDebug('trying to switch to chainId', selectedChainIdHex); await provider.request({ method: 'wallet_switchEthereumChain', @@ -551,7 +551,7 @@ export const checkAndSignEVMAuthMessage = async ({ // -- (case) if unable to switch chain } catch (switchError: any) { - log('error switching to chainId', switchError); + logDebug('error switching to chainId', switchError); // -- (error case) if ( @@ -589,10 +589,10 @@ export const checkAndSignEVMAuthMessage = async ({ } // -- 5. case: Lit auth signature is NOT in the local storage - log('checking if sig is in local storage'); + logDebug('checking if sig is in local storage'); if (authSigOrError.type === EITHER_TYPE.ERROR) { - log('signing auth message because sig is not in local storage'); + logDebug('signing auth message because sig is not in local storage'); try { // @ts-ignore @@ -606,7 +606,7 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } catch (e: any) { - log(e); + logDebug(e); return throwError({ message: e.message, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -614,7 +614,7 @@ export const checkAndSignEVMAuthMessage = async ({ }); } authSigOrError.type = EITHER_TYPE.SUCCESS; - log('5. authSigOrError:', authSigOrError); + logDebug('5. authSigOrError:', authSigOrError); } // -- 6. case: Lit auth signature IS in the local storage @@ -623,11 +623,11 @@ export const checkAndSignEVMAuthMessage = async ({ if (typeof authSig === 'string') { authSig = JSON.parse(authSig); } - log('6. authSig:', authSig); + logDebug('6. authSig:', authSig); // -- 7. case: when we are NOT on the right wallet address if (account.toLowerCase() !== authSig.address.toLowerCase()) { - log( + logDebug( 'signing auth message because account is not the same as the address in the auth sig' ); authSig = await _signAndGetAuth({ @@ -639,7 +639,7 @@ export const checkAndSignEVMAuthMessage = async ({ uri, nonce, }); - log('7. authSig:', authSig); + logDebug('7. authSig:', authSig); // -- 8. case: we are on the right wallet, but need to check the resources of the sig and re-sign if they don't match } else { @@ -656,13 +656,13 @@ export const checkAndSignEVMAuthMessage = async ({ nonce, }); } - log('8. mustResign:', mustResign); + logDebug('8. mustResign:', mustResign); } // -- 9. finally, if the authSig is expired, re-sign // if it's not expired, then we don't need to resign if (isSignedMessageExpired(authSig.signedMessage)) { - log('9. authSig expired!, resigning..'); + logDebug('9. authSig expired!, resigning..'); authSig = await _signAndGetAuth({ web3, @@ -738,7 +738,7 @@ export const signAndSaveAuthMessage = async ({ }: signAndSaveAuthParams): Promise => { // check if it's nodejs if (isNode()) { - log('checkAndSignEVMAuthMessage is not supported in nodejs.'); + logDebug('checkAndSignEVMAuthMessage is not supported in nodejs.'); return { sig: '', derivedVia: '', @@ -804,7 +804,7 @@ export const signAndSaveAuthMessage = async ({ ); } - log(`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); + logDebug(`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`); return authSig; }; @@ -823,7 +823,7 @@ export const signMessage = async ({ }: SignMessageParams): Promise => { // check if it's nodejs if (isNode()) { - log('signMessage is not supported in nodejs.'); + logDebug('signMessage is not supported in nodejs.'); return { signature: '', address: '', @@ -832,26 +832,26 @@ export const signMessage = async ({ // -- validate if (!web3 || !account) { - log(`web3: ${web3} OR ${account} not found. Connecting web3..`); + logDebug(`web3: ${web3} OR ${account} not found. Connecting web3..`); let res = await connectWeb3({ chainId: 1 }); web3 = res.web3; account = res.account; } - log('pausing...'); + logDebug('pausing...'); await new Promise((resolve: any) => setTimeout(resolve, 500)); - log('signing with ', account); + logDebug('signing with ', account); const signature = await signMessageAsync(web3.getSigner(), account, body); const address = verifyMessage(body, signature).toLowerCase(); - log('Signature: ', signature); - log('recovered address: ', address); + logDebug('Signature: ', signature); + logDebug('recovered address: ', address); if (address.toLowerCase() !== account.toLowerCase()) { const msg = `ruh roh, the user signed with a different address (${address}) then they\'re using with web3 (${account}). this will lead to confusion.`; - log(msg); + logDebug(msg); alert( 'something seems to be wrong with your wallets message signing. maybe restart your browser or your wallet. your recovered sig address does not match your web3 account address' ); @@ -878,7 +878,7 @@ export const signMessageAsync = async ( ): Promise => { // check if it's nodejs if (isNode()) { - log('signMessageAsync is not supported in nodejs.'); + logDebug('signMessageAsync is not supported in nodejs.'); return null; } @@ -886,14 +886,14 @@ export const signMessageAsync = async ( if (signer instanceof JsonRpcSigner) { try { - log('Signing with personal_sign'); + logDebug('Signing with personal_sign'); const signature = await signer.provider.send('personal_sign', [ hexlify(messageBytes), address.toLowerCase(), ]); return signature; } catch (e: any) { - log( + logDebug( 'Signing with personal_sign failed, trying signMessage as a fallback' ); if (e.message.includes('personal_sign')) { @@ -902,7 +902,7 @@ export const signMessageAsync = async ( throw e; } } else { - log('signing with signMessage'); + logDebug('signing with signMessage'); return await signer.signMessage(messageBytes); } }; diff --git a/packages/auth-browser/src/lib/chains/sol.ts b/packages/auth-browser/src/lib/chains/sol.ts index 16e54ba890..7a9717cc22 100644 --- a/packages/auth-browser/src/lib/chains/sol.ts +++ b/packages/auth-browser/src/lib/chains/sol.ts @@ -84,7 +84,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { const res = await connectSolProvider(); if (!res) { - log('Failed to connect sol provider'); + logDebug('Failed to connect sol provider'); } const provider = res?.provider; @@ -98,7 +98,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- case: if unable to get auth from local storage if (authSigOrError.type === EITHER_TYPE.ERROR) { - log('signing auth message because sig is not in local storage'); + logDebug('signing auth message because sig is not in local storage'); await signAndSaveAuthMessage({ provider }); @@ -122,7 +122,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { // -- if the wallet address isn't the same as the address from local storage if (account !== authSig.address) { - log( + logDebug( 'signing auth message because account is not the same as the address in the auth sig' ); @@ -135,7 +135,7 @@ export const checkAndSignSolAuthMessage = async (): Promise => { authSig = JSON.parse(authSigOrError.result); } - log('authSig', authSig); + logDebug('authSig', authSig); return authSig; }; diff --git a/packages/bls-sdk/README.md b/packages/bls-sdk/README.md index 2ca8c7d66e..5e38855b2a 100644 --- a/packages/bls-sdk/README.md +++ b/packages/bls-sdk/README.md @@ -17,7 +17,7 @@ import { initWasmBlsSdk } from '@lit-protocol/bls-sdk'; initWasmBlsSdk().then((exports) => { globalThis.wasmExports = exports; - log( + logDebug( `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index fe235e5514..c5aae39519 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -139,7 +139,7 @@ export class LitCore { // If the user sets a new storage provider we respect it over our default storage // If the user sets a new file path, we respect it over the default path. if (this.config.storageProvider?.provider) { - log( + logDebug( 'localstorage api not found, injecting persistance instance found in config' ); // using Object definProperty in order to set a property previously defined as readonly. @@ -152,7 +152,7 @@ export class LitCore { !globalThis.localStorage && !this.config.storageProvider?.provider ) { - log( + logDebug( 'Looks like you are running in NodeJS and did not provide a storage provider, youre sessions will not be cached' ); } @@ -186,7 +186,7 @@ export class LitCore { const bootstrapUrls = await LitContracts.getValidators( this.config.litNetwork as LitNetwork ); - log('Bootstrap urls: ', bootstrapUrls); + logDebug('Bootstrap urls: ', bootstrapUrls); if (minNodeCount <= 0) { throwError({ message: `minNodeCount is ${minNodeCount}, which is invalid. Please check your network connection and try again.`, @@ -232,12 +232,12 @@ export class LitCore { const stakingContract = await LitContracts.getStakingContract( this.config.litNetwork as any ); - log( + logDebug( 'listening for state change on staking contract: ', stakingContract.address ); stakingContract.on('StateChanged', async (state: StakingStates) => { - log(`New state detected: "${state}"`); + logDebug(`New state detected: "${state}"`); if (state === StakingStates.NextValidatorSetLocked) { await this.setNewConfig(); } @@ -339,12 +339,12 @@ export class LitCore { }); } else { // actually verify the attestation by checking the signature against AMD certs - log('Checking attestation against amd certs...'); + logDebug('Checking attestation against amd certs...'); const attestation = resp.attestation; try { checkSevSnpAttestation(attestation, challenge, url).then(() => { - log(`Lit Node Attestation verified for ${url}`); + logDebug(`Lit Node Attestation verified for ${url}`); // only set server keys if attestation is valid // so that we don't use this node if it's not valid @@ -368,7 +368,7 @@ export class LitCore { } }) .catch((e: any) => { - log('Error connecting to node ', url, e); + logDebug('Error connecting to node ', url, e); }); } @@ -424,10 +424,10 @@ export class LitCore { this.ready = true; - log( + logDebug( `🔥 lit is ready. "litNodeClient" variable is ready to use globally.` ); - log('current network config', { + logDebug('current network config', { networkPubkey: this.networkPubKey, networkPubKeySet: this.networkPubKeySet, hdRootPubkeys: this.hdRootPubkeys, @@ -509,7 +509,7 @@ export class LitCore { // -- create url with path const urlWithPath = `${url}/web/handshake`; - log(`handshakeWithNode ${urlWithPath}`); + logDebug(`handshakeWithNode ${urlWithPath}`); const data = { clientPublicKey: 'test', @@ -627,7 +627,9 @@ export class LitCore { errorCode: LIT_ERROR.INVALID_ARGUMENT_EXCEPTION.name, }); } else { - log(`authSig or sessionSigs not found. This may be using authMethod`); + logDebug( + `authSig or sessionSigs not found. This may be using authMethod` + ); } } @@ -763,7 +765,7 @@ export class LitCore { res.error.errorCode === 'not_authorized') && this.config.alertWhenUnauthorized ) { - log( + logDebug( '[Alert originally] You are not authorized to access to this content' ); } @@ -814,7 +816,7 @@ export class LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - log( + logDebug( 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -822,7 +824,7 @@ export class LitCore { formattedEVMContractConditions = evmContractConditions.map((c: any) => canonicalEVMContractConditionFormatter(c) ); - log( + logDebug( 'formattedEVMContractConditions', JSON.stringify(formattedEVMContractConditions) ); @@ -830,7 +832,7 @@ export class LitCore { formattedSolRpcConditions = solRpcConditions.map((c: any) => canonicalSolRpcConditionFormatter(c) ); - log( + logDebug( 'formattedSolRpcConditions', JSON.stringify(formattedSolRpcConditions) ); @@ -839,7 +841,7 @@ export class LitCore { unifiedAccessControlConditions.map((c: any) => canonicalUnifiedAccessControlConditionFormatter(c) ); - log( + logDebug( 'formattedUnifiedAccessControlConditions', JSON.stringify(formattedUnifiedAccessControlConditions) ); diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index 8e8dc13d64..fe50bd22e1 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -26,7 +26,7 @@ if (!globalThis.wasmExports) { globalThis.wasmExports = exports; if (!globalThis.jestTesting) { - log( + logDebug( `✅ [BLS SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` @@ -49,7 +49,7 @@ if (!globalThis.wasmECDSA) { globalThis.wasmECDSA = sdk; if (!globalThis.jestTesting) { - log( + logDebug( `✅ [ECDSA SDK ${env}] wasmECDSA loaded. ${ Object.keys(wasmECDSA).length } functions available. Run 'wasmECDSA' in the console to see them.` @@ -63,7 +63,7 @@ if (!globalThis.wasmSevSnpUtils) { globalThis.wasmSevSnpUtils = exports; if (!globalThis.jestTesting) { - log( + logDebug( `✅ [SEV SNP Utils SDK] wasmSevSnpUtils loaded. ${ Object.keys(exports).length } functions available. Run 'wasmSevSnpUtils' in the console to see them.` @@ -224,7 +224,7 @@ export const combineEcdsaShares = ( return acc; }, []); - log('Valid Shares:', validShares); + logDebug('Valid Shares:', validShares); // if there are no valid shares, throw an error if (validShares.length === 0) { @@ -267,7 +267,7 @@ export const combineEcdsaShares = ( break; case SIGTYPE.ECDSCAITSITHP256: res = ecdsaSdk.combine_signature(validShares, 3); - log('response from combine_signature', res); + logDebug('response from combine_signature', res); sig = JSON.parse(res); break; // if its another sig type, it shouldnt be resolving to this method @@ -277,10 +277,10 @@ export const combineEcdsaShares = ( ); } } catch (e) { - log('Failed to combine signatures:', e); + logDebug('Failed to combine signatures:', e); } - log('signature', sig); + logDebug('signature', sig); return sig; }; @@ -298,7 +298,7 @@ export const computeHDPubKey = ( defualt: throw new Error('Non supported signature type'); } } catch (e) { - log('Failed to derive public key', e); + logDebug('Failed to derive public key', e); } }; diff --git a/packages/encryption/src/lib/encryption.ts b/packages/encryption/src/lib/encryption.ts index 0da27ca35e..d8b06f26a2 100644 --- a/packages/encryption/src/lib/encryption.ts +++ b/packages/encryption/src/lib/encryption.ts @@ -377,7 +377,7 @@ export const zipAndEncryptFiles = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug("Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: "Failed to get 'encryptedAssets' from zip.folder() ", errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -561,7 +561,7 @@ export const encryptFileAndZipWithMetadata = async ( const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug("Failed to get 'encryptedAssets' from zip.folder() "); return throwError({ message: `Failed to get 'encryptedAssets' from zip.folder()`, errorKind: LIT_ERROR.UNKNOWN_ERROR.kind, @@ -620,25 +620,25 @@ export const decryptZipFileWithMetadata = async ( ); if (!jsonFile) { - log(`Failed to read lit_protocol_metadata.json while zip.file()`); + logDebug(`Failed to read lit_protocol_metadata.json while zip.file()`); return; } const metadata: MetadataForFile = JSON.parse(await jsonFile.async('string')); - log('zip metadata', metadata); + logDebug('zip metadata', metadata); const folder: JSZip | null = zip.folder('encryptedAssets'); if (!folder) { - log("Failed to get 'encryptedAssets' from zip.folder() "); + logDebug("Failed to get 'encryptedAssets' from zip.folder() "); return; } const _file: JSZip.JSZipObject | null = folder.file(metadata.name); if (!_file) { - log("Failed to get 'metadata.name' while zip.folder().file()"); + logDebug("Failed to get 'metadata.name' while zip.folder().file()"); return; } @@ -767,11 +767,11 @@ export const verifyJwt = ({ errorCode: LIT_ERROR.INVALID_PARAM_TYPE.name, }); - log('verifyJwt', jwt); + logDebug('verifyJwt', jwt); // verify that the wasm was loaded if (!globalThis.wasmExports) { - log('wasmExports is not loaded.'); + logDebug('wasmExports is not loaded.'); } const jwtParts = jwt.split('.'); diff --git a/packages/encryption/src/lib/params-validators.ts b/packages/encryption/src/lib/params-validators.ts index 08fd6813ca..a0ea98a5a7 100644 --- a/packages/encryption/src/lib/params-validators.ts +++ b/packages/encryption/src/lib/params-validators.ts @@ -50,7 +50,7 @@ export const safeParams = ({ params: any[] | any; }): IEither => { if (!paramsValidators[functionName]) { - log(`This function ${functionName} is skipping params safe guarding.`); + logDebug(`This function ${functionName} is skipping params safe guarding.`); return ERight(undefined); } diff --git a/packages/lit-auth-client/src/lib/lit-auth-client.ts b/packages/lit-auth-client/src/lib/lit-auth-client.ts index 35b7bb8116..9f67133a23 100644 --- a/packages/lit-auth-client/src/lib/lit-auth-client.ts +++ b/packages/lit-auth-client/src/lib/lit-auth-client.ts @@ -88,9 +88,9 @@ export class LitAuthClient { // Set RPC URL this.rpcUrl = options?.rpcUrl || 'https://chain-rpc.litprotocol.com/http'; - log('rpc url: ', this.rpcUrl); - log('relay config: ', options.litRelayConfig); - log('relay instance: ', this.relay); + logDebug('rpc url: ', this.rpcUrl); + logDebug('relay config: ', options.litRelayConfig); + logDebug('relay instance: ', this.relay); } /** @@ -112,7 +112,7 @@ export class LitAuthClient { }; let provider: T; - log('resolving provider of type: ', type); + logDebug('resolving provider of type: ', type); switch (type) { case 'google': provider = new GoogleProvider({ @@ -232,7 +232,7 @@ export class LitAuthClient { authId = await StytchAuthFactorOtpProvider.authMethodId(authMethod); break; default: - log(`unsupported AuthMethodType: ${authMethod.authMethodType}`); + logDebug(`unsupported AuthMethodType: ${authMethod.authMethodType}`); throw new Error( `Unsupported auth method type: ${authMethod.authMethodType}` ); diff --git a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts index c93000581c..8956a06b85 100644 --- a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts +++ b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts @@ -28,7 +28,7 @@ export default class EthWalletProvider extends BaseProvider { this.domain = options.domain || window.location.hostname; this.origin = options.origin || window.location.origin; } catch (e) { - log( + logDebug( '⚠️ Error getting "domain" and "origin" from window object, defaulting to "localhost" and "http://localhost"' ); this.domain = options.domain || 'localhost'; diff --git a/packages/lit-auth-client/src/lib/relay.ts b/packages/lit-auth-client/src/lib/relay.ts index 762c208fe5..7d9889a8dd 100644 --- a/packages/lit-auth-client/src/lib/relay.ts +++ b/packages/lit-auth-client/src/lib/relay.ts @@ -39,7 +39,7 @@ export class LitRelay implements IRelay { this.relayUrl = config.relayUrl || 'https://relayer-server-staging-cayenne.getlit.dev'; this.relayApiKey = config.relayApiKey || ''; - log("Lit's relay server URL:", this.relayUrl); + logDebug("Lit's relay server URL:", this.relayUrl); } /** @@ -60,12 +60,12 @@ export class LitRelay implements IRelay { }); if (response.status < 200 || response.status >= 400) { - log('Something wrong with the API call', await response.json()); + logDebug('Something wrong with the API call', await response.json()); const err = new Error('Unable to mint PKP through relay server'); throw err; } else { const resBody = await response.json(); - log('Successfully initiated minting PKP with relayer'); + logDebug('Successfully initiated minting PKP with relayer'); return resBody; } } @@ -96,7 +96,7 @@ export class LitRelay implements IRelay { ); if (response.status < 200 || response.status >= 400) { - log('Something wrong with the API call', await response.json()); + logDebug('Something wrong with the API call', await response.json()); const err = new Error( `Unable to poll the status of this mint PKP transaction: ${requestId}` ); @@ -104,18 +104,18 @@ export class LitRelay implements IRelay { } const resBody = await response.json(); - log('Response OK', { body: resBody }); + logDebug('Response OK', { body: resBody }); if (resBody.error) { // exit loop since error - log('Something wrong with the API call', { + logDebug('Something wrong with the API call', { error: resBody.error, }); const err = new Error(resBody.error); throw err; } else if (resBody.status === 'Succeeded') { // exit loop since success - log('Successfully authed', { ...resBody }); + logDebug('Successfully authed', { ...resBody }); return resBody; } diff --git a/packages/lit-auth-client/src/lib/utils.ts b/packages/lit-auth-client/src/lib/utils.ts index 2bf6062b06..11ed051cb6 100644 --- a/packages/lit-auth-client/src/lib/utils.ts +++ b/packages/lit-auth-client/src/lib/utils.ts @@ -309,7 +309,7 @@ export function unparse(buf: any) { ); } -export function log(...args: any) { +export function logDebug(...args: any) { const logger = getLoggerbyId('auth-client'); logger.debug(...args); } diff --git a/packages/lit-node-client-nodejs/src/index.ts b/packages/lit-node-client-nodejs/src/index.ts index 9a9aa68354..2ed6442937 100644 --- a/packages/lit-node-client-nodejs/src/index.ts +++ b/packages/lit-node-client-nodejs/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClientNodeJs from './lib/lit-node-client-nodejs'; // ==================== Environment ==================== if (isNode()) { - log('Oh hey you are running in Node.js!'); + logDebug('Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index 76bf0630ba..0c141802be 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -215,7 +215,7 @@ export class LitNodeClientNodeJs extends LitCore { try { response = JSON.parse(responseString); } catch (e) { - log( + logDebug( 'Error parsing response as json. Swallowing and returning as string.', responseString ); @@ -341,7 +341,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (TRY) to get it in the local storage // -- IF NOT: Generates one - log(`getWalletSig - flow starts + logDebug(`getWalletSig - flow starts storageKey: ${storageKey} storedWalletSigOrError: ${JSON.stringify(storedWalletSigOrError)} `); @@ -351,12 +351,12 @@ export class LitNodeClientNodeJs extends LitCore { !storedWalletSigOrError.result || storedWalletSigOrError.result == '' ) { - log('getWalletSig - flow 1'); + logDebug('getWalletSig - flow 1'); console.warn( `Storage key "${storageKey}" is missing. Not a problem. Continue...` ); if (authNeededCallback) { - log('getWalletSig - flow 1.1'); + logDebug('getWalletSig - flow 1.1'); const body = { chain, statement: sessionCapabilityObject?.statement, @@ -369,13 +369,13 @@ export class LitNodeClientNodeJs extends LitCore { nonce, }; - log('callback body:', body); + logDebug('callback body:', body); walletSig = await authNeededCallback(body); } else { - log('getWalletSig - flow 1.2'); + logDebug('getWalletSig - flow 1.2'); if (!this.defaultAuthCallback) { - log('getWalletSig - flow 1.2.1'); + logDebug('getWalletSig - flow 1.2.1'); return throwError({ message: 'No default auth callback provided', errorKind: LIT_ERROR.PARAMS_MISSING_ERROR.kind, @@ -383,7 +383,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - log('getWalletSig - flow 1.2.2'); + logDebug('getWalletSig - flow 1.2.2'); walletSig = await this.defaultAuthCallback({ chain, statement: sessionCapabilityObject.statement, @@ -397,7 +397,7 @@ export class LitNodeClientNodeJs extends LitCore { }); } - log('getWalletSig - flow 1.3'); + logDebug('getWalletSig - flow 1.3'); // (TRY) to set walletSig to local storage const storeNewWalletSigOrError = setStorageItem( @@ -405,23 +405,23 @@ export class LitNodeClientNodeJs extends LitCore { JSON.stringify(walletSig) ); if (storeNewWalletSigOrError.type === 'ERROR') { - log('getWalletSig - flow 1.4'); + logDebug('getWalletSig - flow 1.4'); console.warn( `Unable to store walletSig in local storage. Not a problem. Continue...` ); } } else { - log('getWalletSig - flow 2'); + logDebug('getWalletSig - flow 2'); try { walletSig = JSON.parse(storedWalletSigOrError.result as string); - log('getWalletSig - flow 2.1'); + logDebug('getWalletSig - flow 2.1'); } catch (e) { console.warn('Error parsing walletSig', e); - log('getWalletSig - flow 2.2'); + logDebug('getWalletSig - flow 2.2'); } } - log('getWalletSig - flow 3'); + logDebug('getWalletSig - flow 3'); return walletSig!; }; @@ -648,7 +648,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSigningShareForDecryptionRequest, requestId: string ): Promise => { - log('getSigningShareForDecryption'); + logDebug('getSigningShareForDecryption'); const urlWithPath = `${url}/web/encryption/sign`; return await this.sendCommandToNode({ @@ -673,7 +673,7 @@ export class LitNodeClientNodeJs extends LitCore { params: SignConditionECDSA, requestId: string ): Promise => { - log('signConditionEcdsa'); + logDebug('signConditionEcdsa'); const urlWithPath = `${url}/web/signing/signConditionEcdsa`; const data = { @@ -784,7 +784,7 @@ export class LitNodeClientNodeJs extends LitCore { targetNodeRange, } = params; - log('running runOnTargetedNodes:', targetNodeRange); + logDebug('running runOnTargetedNodes:', targetNodeRange); if (!targetNodeRange) { return throwError({ @@ -852,7 +852,7 @@ export class LitNodeClientNodeJs extends LitCore { .mod(this.config.bootstrapUrls.length) .toNumber(); - log('nodeIndex:', nodeIndex); + logDebug('nodeIndex:', nodeIndex); // must be unique & less than bootstrapUrls.length if ( @@ -864,7 +864,7 @@ export class LitNodeClientNodeJs extends LitCore { nodeCounter++; } - log('Final Selected Indexes:', randomSelectedNodeIndexes); + logDebug('Final Selected Indexes:', randomSelectedNodeIndexes); const requestId = this.getRequestId(); const nodePromises = []; @@ -881,7 +881,7 @@ export class LitNodeClientNodeJs extends LitCore { // because the staking nodes can change, and the rust code will use the same list const url = this.config.bootstrapUrls[nodeIndex]; - log(`running on node ${nodeIndex} at ${url}`); + logDebug(`running on node ${nodeIndex} at ${url}`); const reqBody: JsonExecutionRequest = this.getLitActionRequestBody(params); @@ -1011,20 +1011,20 @@ export class LitNodeClientNodeJs extends LitCore { // -- execute keys.forEach((key: any) => { - log('key:', key); + logDebug('key:', key); const shares = signedData.map((r: any) => r[key]); - log('shares:', shares); + logDebug('shares:', shares); shares.sort((a: any, b: any) => a.shareIndex - b.shareIndex); const sigShares: Array = shares.map((s: any, index: number) => { - log('Original Share Struct:', s); + logDebug('Original Share Struct:', s); const share = this._getFlattenShare(s); - log('share:', share); + logDebug('share:', share); if (!share) { throw new Error('share is null or undefined'); @@ -1039,8 +1039,8 @@ export class LitNodeClientNodeJs extends LitCore { const sanitisedBigR = sanitise(share.bigr); const sanitisedSigShare = sanitise(share.publicKey); - log('sanitisedBigR:', sanitisedBigR); - log('sanitisedSigShare:', sanitisedSigShare); + logDebug('sanitisedBigR:', sanitisedBigR); + logDebug('sanitisedSigShare:', sanitisedSigShare); return { sigType: share.sigType, @@ -1053,7 +1053,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - log('getSessionSignatures - sigShares', sigShares); + logDebug('getSessionSignatures - sigShares', sigShares); const sigType = mostCommonString(sigShares.map((s: any) => s.sigType)); @@ -1502,7 +1502,7 @@ export class LitNodeClientNodeJs extends LitCore { logs: mostCommonLogs, }; - log('returnVal:', returnVal); + logDebug('returnVal:', returnVal); // -- case: debug mode if (debug) { @@ -1746,7 +1746,7 @@ export class LitNodeClientNodeJs extends LitCore { res as SuccessNodePromises ).values; - log('signatureShares', signatureShares); + logDebug('signatureShares', signatureShares); // ========== Result ========== const finalJwt: string = this.combineSharesAndGetJWT( @@ -2072,7 +2072,7 @@ export class LitNodeClientNodeJs extends LitCore { formattedAccessControlConditions = accessControlConditions.map((c: any) => canonicalAccessControlConditionFormatter(c) ); - log( + logDebug( 'formattedAccessControlConditions', JSON.stringify(formattedAccessControlConditions) ); @@ -2105,7 +2105,7 @@ export class LitNodeClientNodeJs extends LitCore { return signature; } catch (e) { - log('Error - signed_ecdsa_messages - ', e); + logDebug('Error - signed_ecdsa_messages - ', e); const signed_ecdsa_message = nodePromises[0]; return signed_ecdsa_message; } @@ -2199,7 +2199,7 @@ export class LitNodeClientNodeJs extends LitCore { let res; try { res = await this.handleNodePromises(nodePromises, requestId); - log('signSessionKey node promises:', res); + logDebug('signSessionKey node promises:', res); } catch (e) { throw new Error(`Error when handling node promises: ${e}`); } @@ -2246,7 +2246,7 @@ export class LitNodeClientNodeJs extends LitCore { // check if all required fields are present for (const field of requiredFields) { if (!sessionSig[field] || sessionSig[field] === '') { - log( + logDebug( `Invalid signed data. ${field} is missing. Not a problem, we only need ${this.config.minNodeCount} nodes to sign the session key.` ); return null; @@ -2257,7 +2257,11 @@ export class LitNodeClientNodeJs extends LitCore { }) .filter((item) => item !== null); - logDebugWithRequestId(requestId, 'requested length:', signedDataList.length); + logDebugWithRequestId( + requestId, + 'requested length:', + signedDataList.length + ); logDebugWithRequestId( requestId, 'validated length:', @@ -2298,7 +2302,7 @@ export class LitNodeClientNodeJs extends LitCore { params: GetSignSessionKeySharesProp, requestId: string ) => { - log('getSignSessionKeyShares'); + logDebug('getSignSessionKeyShares'); const urlWithPath = `${url}/web/sign_session_key`; return await this.sendCommandToNode({ url: urlWithPath, @@ -2387,7 +2391,7 @@ export class LitNodeClientNodeJs extends LitCore { // -- (CHECK) if we need to resign the session key if (needToResignSessionKey) { - log('need to re-sign session key. Signing...'); + logDebug('need to re-sign session key. Signing...'); authSig = await this.#authCallbackAndUpdateStorageItem({ authCallback: params.authNeededCallback, authCallbackParams: { @@ -2448,7 +2452,7 @@ export class LitNodeClientNodeJs extends LitCore { const uint8arrayMessage = uint8arrayFromString(signedMessage, 'utf8'); let signature = nacl.sign.detached(uint8arrayMessage, uint8arrayKey); - // log("signature", signature); + // logDebug("signature", signature); signatures[nodeAddress] = { sig: uint8arrayToString(signature, 'base16'), derivedVia: 'litSessionSignViaNacl', @@ -2458,7 +2462,7 @@ export class LitNodeClientNodeJs extends LitCore { }; }); - log('signatures:', signatures); + logDebug('signatures:', signatures); return signatures; }; diff --git a/packages/lit-node-client/src/index.ts b/packages/lit-node-client/src/index.ts index 91c73a1761..eecc281d80 100644 --- a/packages/lit-node-client/src/index.ts +++ b/packages/lit-node-client/src/index.ts @@ -3,7 +3,7 @@ import * as _LitNodeClient from './lib/lit-node-client'; // ==================== Environment ==================== if (isNode()) { - log('Oh hey you are running in Node.js!'); + logDebug('Oh hey you are running in Node.js!'); const fetch = require('node-fetch'); globalThis.fetch = fetch; } diff --git a/packages/lit-node-client/src/lib/lit-node-client.ts b/packages/lit-node-client/src/lib/lit-node-client.ts index 603a451e1a..c45009c788 100644 --- a/packages/lit-node-client/src/lib/lit-node-client.ts +++ b/packages/lit-node-client/src/lib/lit-node-client.ts @@ -31,7 +31,7 @@ export class LitNodeClient extends LitNodeClientNodeJs { // -- validate if (storageConfigOrError.type === EITHER_TYPE.ERROR) { - log(`Storage key "${storageKey}" is missing. `); + logDebug(`Storage key "${storageKey}" is missing. `); return; } diff --git a/packages/logger/src/lib/logger.ts b/packages/logger/src/lib/logger.ts index 0ed28c4b6a..1488dc0e09 100644 --- a/packages/logger/src/lib/logger.ts +++ b/packages/logger/src/lib/logger.ts @@ -290,7 +290,7 @@ export class Logger { } private _log(level: LogLevel, message: string = '', ...args: any[]): void { - const log = new Log( + const log = new logDebug( new Date().toISOString(), message, args, diff --git a/packages/pkp-base/src/lib/pkp-base.ts b/packages/pkp-base/src/lib/pkp-base.ts index 4b7a90e740..3d1b4cb0d7 100644 --- a/packages/pkp-base/src/lib/pkp-base.ts +++ b/packages/pkp-base/src/lib/pkp-base.ts @@ -398,7 +398,7 @@ export class PKPBase { * @returns {void} - This function does not return a value. */ - log(...args: any[]): void { + logDebug(...args: any[]): void { if (this.debug) { console.log(this.orange + this.PREFIX + this.reset, ...args); } diff --git a/packages/pkp-client/src/lib/pkp-client.ts b/packages/pkp-client/src/lib/pkp-client.ts index 44a58e4e84..93d0570f54 100644 --- a/packages/pkp-client/src/lib/pkp-client.ts +++ b/packages/pkp-client/src/lib/pkp-client.ts @@ -115,7 +115,7 @@ export class PKPClient { ).length; if (successfulInits !== this._wallets.size) { - log( + logDebug( `Not all wallets initialized successfully. Details: ${JSON.stringify( walletStatus, null, diff --git a/packages/sev-snp-utils-sdk/README.md b/packages/sev-snp-utils-sdk/README.md index 4fff08a3b8..bbe2426f78 100644 --- a/packages/sev-snp-utils-sdk/README.md +++ b/packages/sev-snp-utils-sdk/README.md @@ -17,7 +17,7 @@ import { initSevSnpUtilsSdk } from '@lit-protocol/sev-snp-utils-sdk'; initSevSnpUtilsSdk().then((exports) => { globalThis.wasmExports = exports; - log( + logDebug( `✅ [SEV SNP Utils SDK] wasmExports loaded. ${ Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` From d914054d60be7b7be54cd0668a27d337a30cebad Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 10:50:27 -0500 Subject: [PATCH 07/11] updated import references for logDebug and logDebugWithRequestId --- packages/access-control-conditions/src/lib/hashing.ts | 2 +- packages/access-control-conditions/src/lib/humanizer.ts | 2 +- packages/auth-browser/src/lib/chains/cosmos.ts | 2 +- packages/auth-browser/src/lib/chains/eth.ts | 2 +- packages/auth-browser/src/lib/chains/sol.ts | 2 +- packages/core/src/lib/lit-core.ts | 4 ++-- packages/crypto/src/lib/crypto.ts | 2 +- packages/encryption/src/lib/encryption.ts | 2 +- packages/encryption/src/lib/params-validators.ts | 2 +- packages/lit-auth-client/src/lib/lit-auth-client.ts | 6 +++++- .../lit-auth-client/src/lib/providers/EthWalletProvider.ts | 2 +- packages/lit-node-client-nodejs/src/index.ts | 2 +- .../src/lib/lit-node-client-nodejs.ts | 4 ++-- packages/lit-node-client/src/index.ts | 2 +- packages/lit-node-client/src/lib/lit-node-client.ts | 2 +- packages/pkp-client/src/lib/pkp-client.ts | 2 +- 16 files changed, 22 insertions(+), 18 deletions(-) diff --git a/packages/access-control-conditions/src/lib/hashing.ts b/packages/access-control-conditions/src/lib/hashing.ts index 6fc2faabc3..8a7cee7268 100644 --- a/packages/access-control-conditions/src/lib/hashing.ts +++ b/packages/access-control-conditions/src/lib/hashing.ts @@ -9,7 +9,7 @@ import { UnifiedAccessControlConditions, } from '@lit-protocol/types'; -import { log, throwError } from '@lit-protocol/misc'; +import { logDebug, throwError } from '@lit-protocol/misc'; import { canonicalAccessControlConditionFormatter, canonicalEVMContractConditionFormatter, diff --git a/packages/access-control-conditions/src/lib/humanizer.ts b/packages/access-control-conditions/src/lib/humanizer.ts index 64d79aa76e..77b7e09f38 100644 --- a/packages/access-control-conditions/src/lib/humanizer.ts +++ b/packages/access-control-conditions/src/lib/humanizer.ts @@ -10,7 +10,7 @@ import { UnifiedAccessControlConditions, } from '@lit-protocol/types'; -import { decimalPlaces, log, throwError } from '@lit-protocol/misc'; +import { decimalPlaces, logDebug, throwError } from '@lit-protocol/misc'; import { formatEther, formatUnits } from 'ethers/lib/utils'; /** diff --git a/packages/auth-browser/src/lib/chains/cosmos.ts b/packages/auth-browser/src/lib/chains/cosmos.ts index e4786d01f6..417dbef4a5 100644 --- a/packages/auth-browser/src/lib/chains/cosmos.ts +++ b/packages/auth-browser/src/lib/chains/cosmos.ts @@ -11,7 +11,7 @@ import { } from '@lit-protocol/constants'; import { AuthSig, CosmosWalletType } from '@lit-protocol/types'; -import { log, sortedObject, throwError } from '@lit-protocol/misc'; +import { logDebug, sortedObject, throwError } from '@lit-protocol/misc'; /** ---------- Declaration ---------- */ declare global { diff --git a/packages/auth-browser/src/lib/chains/eth.ts b/packages/auth-browser/src/lib/chains/eth.ts index 36fcac0eb8..e0524d4b31 100644 --- a/packages/auth-browser/src/lib/chains/eth.ts +++ b/packages/auth-browser/src/lib/chains/eth.ts @@ -36,7 +36,7 @@ import { Buffer as BufferPolyfill } from 'buffer'; import { isBrowser, isNode, - log, + logDebug, numberToHex, throwError, } from '@lit-protocol/misc'; diff --git a/packages/auth-browser/src/lib/chains/sol.ts b/packages/auth-browser/src/lib/chains/sol.ts index 7a9717cc22..66a10a2a7a 100644 --- a/packages/auth-browser/src/lib/chains/sol.ts +++ b/packages/auth-browser/src/lib/chains/sol.ts @@ -9,7 +9,7 @@ import { } from '@lit-protocol/constants'; import { IProvider, AuthSig } from '@lit-protocol/types'; -import { log, throwError } from '@lit-protocol/misc'; +import { logDebug, throwError } from '@lit-protocol/misc'; import { getStorageItem } from '@lit-protocol/misc-browser'; // import { toString as uint8arrayToString } from 'uint8arrays'; diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index c5aae39519..eaeb45276d 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -29,10 +29,10 @@ import { bootstrapLogManager, isBrowser, isNode, - log, + logDebug, logError, logErrorWithRequestId, - logWithRequestId, + logDebugWithRequestId, mostCommonString, throwError, } from '@lit-protocol/misc'; diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index fe50bd22e1..34735177b0 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -8,7 +8,7 @@ import * as ecdsaSdk from '@lit-protocol/ecdsa-sdk'; import * as sevSnpUtilsSdk from '@lit-protocol/sev-snp-utils-sdk'; -import { isBrowser, log, throwError } from '@lit-protocol/misc'; +import { isBrowser, logDebug, throwError } from '@lit-protocol/misc'; import { uint8arrayFromString, diff --git a/packages/encryption/src/lib/encryption.ts b/packages/encryption/src/lib/encryption.ts index d8b06f26a2..f5d7105ebd 100644 --- a/packages/encryption/src/lib/encryption.ts +++ b/packages/encryption/src/lib/encryption.ts @@ -35,7 +35,7 @@ import { uint8arrayToString, } from '@lit-protocol/uint8arrays'; -import { checkType, isBrowser, log, throwError } from '@lit-protocol/misc'; +import { checkType, isBrowser, logDebug, throwError } from '@lit-protocol/misc'; import { safeParams } from './params-validators'; diff --git a/packages/encryption/src/lib/params-validators.ts b/packages/encryption/src/lib/params-validators.ts index a0ea98a5a7..918bf7461e 100644 --- a/packages/encryption/src/lib/params-validators.ts +++ b/packages/encryption/src/lib/params-validators.ts @@ -37,7 +37,7 @@ import { checkIfAuthSigRequiresChainParam, checkType, is, - log, + logDebug, } from '@lit-protocol/misc'; import { isHexString } from 'ethers/lib/utils'; import { isValidBooleanExpression } from './utils'; diff --git a/packages/lit-auth-client/src/lib/lit-auth-client.ts b/packages/lit-auth-client/src/lib/lit-auth-client.ts index 9f67133a23..86ddea13f6 100644 --- a/packages/lit-auth-client/src/lib/lit-auth-client.ts +++ b/packages/lit-auth-client/src/lib/lit-auth-client.ts @@ -20,7 +20,11 @@ import WebAuthnProvider from './providers/WebAuthnProvider'; import { StytchOtpProvider } from './providers/StytchOtpProvider'; import AppleProvider from './providers/AppleProvider'; import StytchAuthFactorOtpProvider from './providers/StytchAuthFactorOtp'; -import { bootstrapLogManager, getLoggerbyId, log } from '@lit-protocol/misc'; +import { + bootstrapLogManager, + getLoggerbyId, + logDebug, +} from '@lit-protocol/misc'; import { ethers } from 'ethers'; /** diff --git a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts index 8956a06b85..226e2bc01b 100644 --- a/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts +++ b/packages/lit-auth-client/src/lib/providers/EthWalletProvider.ts @@ -10,7 +10,7 @@ import { SiweMessage } from 'lit-siwe'; import { ethers } from 'ethers'; import { BaseProvider } from './BaseProvider'; import { checkAndSignAuthMessage } from '@lit-protocol/lit-node-client'; -import { log, throwError } from '@lit-protocol/misc'; +import { logDebug, throwError } from '@lit-protocol/misc'; export default class EthWalletProvider extends BaseProvider { /** diff --git a/packages/lit-node-client-nodejs/src/index.ts b/packages/lit-node-client-nodejs/src/index.ts index 2ed6442937..d71030a4f0 100644 --- a/packages/lit-node-client-nodejs/src/index.ts +++ b/packages/lit-node-client-nodejs/src/index.ts @@ -1,4 +1,4 @@ -import { isNode, log } from '@lit-protocol/misc'; +import { isNode, logDebug } from '@lit-protocol/misc'; import * as _LitNodeClientNodeJs from './lib/lit-node-client-nodejs'; // ==================== Environment ==================== diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index 0c141802be..02e3ba1b6f 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -22,10 +22,10 @@ import { convertLitActionsParams, defaultMintClaimCallback, hexPrefixed, - log, + logDebug, logError, logErrorWithRequestId, - logWithRequestId, + logDebugWithRequestId, mostCommonString, throwError, } from '@lit-protocol/misc'; diff --git a/packages/lit-node-client/src/index.ts b/packages/lit-node-client/src/index.ts index eecc281d80..6900db897b 100644 --- a/packages/lit-node-client/src/index.ts +++ b/packages/lit-node-client/src/index.ts @@ -1,4 +1,4 @@ -import { isNode, log } from '@lit-protocol/misc'; +import { isNode, logDebug } from '@lit-protocol/misc'; import * as _LitNodeClient from './lib/lit-node-client'; // ==================== Environment ==================== diff --git a/packages/lit-node-client/src/lib/lit-node-client.ts b/packages/lit-node-client/src/lib/lit-node-client.ts index c45009c788..e5568a8c18 100644 --- a/packages/lit-node-client/src/lib/lit-node-client.ts +++ b/packages/lit-node-client/src/lib/lit-node-client.ts @@ -1,7 +1,7 @@ import { LitNodeClientNodeJs } from '@lit-protocol/lit-node-client-nodejs'; import { checkAndSignAuthMessage } from '@lit-protocol/auth-browser'; import { CustomNetwork, LitNodeClientConfig } from '@lit-protocol/types'; -import { isNode, log } from '@lit-protocol/misc'; +import { isNode, logDebug } from '@lit-protocol/misc'; import { getStorageItem } from '@lit-protocol/misc-browser'; import { EITHER_TYPE } from '@lit-protocol/constants'; diff --git a/packages/pkp-client/src/lib/pkp-client.ts b/packages/pkp-client/src/lib/pkp-client.ts index 93d0570f54..f44834c8c2 100644 --- a/packages/pkp-client/src/lib/pkp-client.ts +++ b/packages/pkp-client/src/lib/pkp-client.ts @@ -3,7 +3,7 @@ import { PKPCosmosWallet } from '@lit-protocol/pkp-cosmos'; import { PKPClientProp } from '@lit-protocol/types'; import { PKPBase } from '@lit-protocol/pkp-base'; import { WalletFactory } from './wallet-factory'; -import { log } from '@lit-protocol/misc'; +import { logDebug } from '@lit-protocol/misc'; import { PKP_CLIENT_SUPPORTED_CHAINS } from '@lit-protocol/constants'; export class PKPClient { From 685ebb9a8edb25b20ddcc0d5f093a91786aa815f Mon Sep 17 00:00:00 2001 From: cipherZ Date: Thu, 25 Jan 2024 11:48:26 -0500 Subject: [PATCH 08/11] yarn build will not build whole project --- apps/html/index.html | 604 +----------------- apps/nodejs/main.ts | 14 - apps/react/src/app/app.tsx | 520 +-------------- .../access-control-conditions/package.json | 2 +- packages/auth-browser/package.json | 2 +- packages/auth-helpers/package.json | 2 +- packages/bls-sdk/package.json | 2 +- packages/constants/package.json | 2 +- .../src/lib/constants/autogen_internal.ts | 48 +- packages/contracts-sdk/package.json | 2 +- packages/contracts-sdk/src/abis/types.d.ts | 22 +- .../contracts-sdk/src/lib/contracts-sdk.ts | 2 +- packages/core/package.json | 2 +- packages/crypto/package.json | 2 +- packages/ecdsa-sdk/package.json | 2 +- packages/encryption/package.json | 2 +- packages/lit-auth-client/package.json | 6 +- packages/lit-auth-client/src/lib/relay.ts | 2 +- packages/lit-node-client-nodejs/package.json | 6 +- packages/lit-node-client/package.json | 6 +- packages/lit-third-party-libs/package.json | 4 +- packages/logger/package.json | 6 +- packages/logger/src/lib/logger.ts | 2 +- packages/misc-browser/package.json | 6 +- packages/misc/package.json | 6 +- packages/nacl/package.json | 6 +- packages/pkp-base/package.json | 6 +- packages/pkp-client/package.json | 6 +- packages/pkp-cosmos/package.json | 6 +- packages/pkp-ethers/package.json | 6 +- packages/pkp-sui/package.json | 6 +- packages/pkp-walletconnect/package.json | 6 +- packages/sev-snp-utils-sdk/package.json | 6 +- packages/types/package.json | 6 +- packages/uint8arrays/package.json | 6 +- tsconfig.json | 17 +- 36 files changed, 105 insertions(+), 1246 deletions(-) diff --git a/apps/html/index.html b/apps/html/index.html index cde59daf09..eb937e2489 100644 --- a/apps/html/index.html +++ b/apps/html/index.html @@ -1,4 +1,4 @@ - + @@ -62,7 +62,7 @@ - (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Tue, 23 Jan 2024 01:27:49 GMT + (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Thu, 25 Jan 2024 16:40:38 GMT @@ -75,19 +75,11 @@ - - - - - - - - @@ -814,79 +806,7 @@

LitJsSdk_encryption has ${entries.length} functions

- - - - - + - - - - - + - + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + diff --git a/apps/react/src/app/app.tsx b/apps/react/src/app/app.tsx index 0c5a83b2a5..6f5f2232a0 100644 --- a/apps/react/src/app/app.tsx +++ b/apps/react/src/app/app.tsx @@ -1361,7 +1361,7 @@ pre { `, }} /> - (REACT) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-react.mjs Thu, 25 Jan 2024 16:40:39 GMT + (REACT) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-react.mjs Thu, 25 Jan 2024 16:56:14 GMT
diff --git a/packages/constants/src/lib/constants/autogen_internal.ts b/packages/constants/src/lib/constants/autogen_internal.ts index 3eb2fd114a..3a04c9c564 100644 --- a/packages/constants/src/lib/constants/autogen_internal.ts +++ b/packages/constants/src/lib/constants/autogen_internal.ts @@ -1,4 +1,4 @@ -// Last Modified: 2024-01-25 16:38:05 +// Last Modified: 2024-01-25 16:53:41 // This file is auto-generated by tools/scripts/gen-internal-dev.mjs export const INTERNAL_DEV = [ "https://167.114.17.204:443", diff --git a/packages/lit-auth-client/src/lib/contracts-sdk.ts b/packages/lit-auth-client/src/lib/contracts-sdk.ts new file mode 100644 index 0000000000..1493a6c99c --- /dev/null +++ b/packages/lit-auth-client/src/lib/contracts-sdk.ts @@ -0,0 +1,1889 @@ +import { BigNumberish, BytesLike, ethers } from 'ethers'; +import { hexToDec, decToHex, intToIP } from './hex2dec'; +import bs58 from 'bs58'; +import { isBrowser, isNode, logDebug } from '@lit-protocol/misc'; +import { AuthMethod } from '@lit-protocol/types'; + +let CID: any; +try { + CID = require('multiformats/cid'); +} catch (e) {} + +// ----- autogen:import-data:start ----- +// Generated at 2023-11-07T01:50:52.460Z +import { AllowlistData } from '../abis/Allowlist.sol/AllowlistData'; +import { LITTokenData } from '../abis/LITToken.sol/LITTokenData'; +import { MultisenderData } from '../abis/Multisender.sol/MultisenderData'; +import { PKPHelperData } from '../abis/PKPHelper.sol/PKPHelperData'; +import { PKPNFTData } from '../abis/PKPNFT.sol/PKPNFTData'; +import { PKPNFTMetadataData } from '../abis/PKPNFTMetadata.sol/PKPNFTMetadataData'; +import { PKPPermissionsData } from '../abis/PKPPermissions.sol/PKPPermissionsData'; +import { PubkeyRouterData } from '../abis/PubkeyRouter.sol/PubkeyRouterData'; +import { RateLimitNFTData } from '../abis/RateLimitNFT.sol/RateLimitNFTData'; +import { StakingData } from '../abis/Staking.sol/StakingData'; +import { StakingBalancesData } from '../abis/StakingBalances.sol/StakingBalancesData'; +// ----- autogen:import-data:end ----- + +// ----- autogen:imports:start ----- +// Generated at 2023-11-07T01:50:52.460Z +import * as allowlistContract from '../abis/Allowlist.sol/Allowlist'; +import * as litTokenContract from '../abis/LITToken.sol/LITToken'; +import * as multisenderContract from '../abis/Multisender.sol/Multisender'; +import * as pkpHelperContract from '../abis/PKPHelper.sol/PKPHelper'; +import * as pkpNftContract from '../abis/PKPNFT.sol/PKPNFT'; +import * as pkpNftMetadataContract from '../abis/PKPNFTMetadata.sol/PKPNFTMetadata'; +import * as pkpPermissionsContract from '../abis/PKPPermissions.sol/PKPPermissions'; +import * as pubkeyRouterContract from '../abis/PubkeyRouter.sol/PubkeyRouter'; +import * as rateLimitNftContract from '../abis/RateLimitNFT.sol/RateLimitNFT'; +import * as stakingContract from '../abis/Staking.sol/Staking'; +import * as stakingBalancesContract from '../abis/StakingBalances.sol/StakingBalances'; +// ----- autogen:imports:end ----- + +import { TokenInfo, derivedAddresses } from './addresses'; +import { IPubkeyRouter } from '../abis/PKPNFT.sol/PKPNFT'; +import { computeAddress } from 'ethers/lib/utils'; +import { getAuthIdByAuthMethod } from './auth-utils'; +import { Logger, LogManager } from '@lit-protocol/logger'; + +const DEFAULT_RPC = 'https://chain-rpc.litprotocol.com/http'; +const BLOCK_EXPLORER = 'https://chain.litprotocol.com/'; + +// This function asynchronously executes a provided callback function for each item in the given array. +// The callback function is awaited before continuing to the next iteration. +// The resulting array of callback return values is then returned. +// +// @param {Array} array - The array to iterate over +// @param {Function} callback - The function to execute for each item in the array. This function +// must be asynchronous and should take the following parameters: +// - currentValue: The current item being processed in the array +// - index: The index of the current item being processed in the array +// - array: The array being iterated over +// @return {Array} The array of callback return values +export const asyncForEachReturn = async ( + array: Array, + callback: Function +) => { + const list = []; + + for (let index = 0; index < array.length; index++) { + const item = await callback(array[index], index, array); + list.push(item); + } + return list; +}; + +export interface IPFSHash { + digest: string; + hashFunction: number; + size: number; +} + +declare global { + interface Window { + ethereum: any; + } +} + +// This code defines a LitContracts class that acts as a container for a collection of smart contracts. The class has a constructor that accepts an optional args object with provider and rpc properties. If no provider is specified, the class will create a default provider using the specified rpc URL. If no rpc URL is specified, the class will use a default URL. +// The class has a number of properties that represent the smart contract instances, such as accessControlConditionsContract, litTokenContract, pkpNftContract, etc. These smart contract instances are created by passing the contract address, ABI, and provider to the ethers.Contract constructor. +// The class also has a utils object with helper functions for converting between hexadecimal and decimal representation of numbers, as well as functions for working with multihashes and timestamps. +export class LitContracts { + provider: ethers.providers.JsonRpcProvider | any; + rpc: string; + rpcs: string[]; + signer: ethers.Signer | ethers.Wallet; + privateKey: string | undefined; + options?: { + storeOrUseStorageKey?: boolean; + }; + randomPrivateKey: boolean = false; + connected: boolean = false; + isPKP: boolean = false; + debug: boolean = false; + network: 'cayenne'; + + static logger: Logger = LogManager.Instance.get('contract-sdk'); + // ----- autogen:declares:start ----- + // Generated at 2023-11-07T01:50:52.460Z + allowlistContract: { + read: allowlistContract.Allowlist; + write: allowlistContract.Allowlist; + }; + + litTokenContract: { + read: litTokenContract.LITToken; + write: litTokenContract.LITToken; + }; + + multisenderContract: { + read: multisenderContract.Multisender; + write: multisenderContract.Multisender; + }; + + pkpHelperContract: { + read: pkpHelperContract.PKPHelper; + write: pkpHelperContract.PKPHelper; + }; + + pkpNftContract: { + read: pkpNftContract.PKPNFT; + write: pkpNftContract.PKPNFT; + }; + + pkpNftMetadataContract: { + read: pkpNftMetadataContract.PKPNFTMetadata; + write: pkpNftMetadataContract.PKPNFTMetadata; + }; + + pkpPermissionsContract: { + read: pkpPermissionsContract.PKPPermissions; + write: pkpPermissionsContract.PKPPermissions; + }; + + pubkeyRouterContract: { + read: pubkeyRouterContract.PubkeyRouter; + write: pubkeyRouterContract.PubkeyRouter; + }; + + rateLimitNftContract: { + read: rateLimitNftContract.RateLimitNFT; + write: rateLimitNftContract.RateLimitNFT; + }; + + stakingContract: { + read: stakingContract.Staking; + write: stakingContract.Staking; + }; + + stakingBalancesContract: { + read: stakingBalancesContract.StakingBalances; + write: stakingBalancesContract.StakingBalances; + }; + + // ----- autogen:declares:end ----- + + // make the constructor args optional + constructor(args?: { + provider?: ethers.providers.JsonRpcProvider | any; + rpcs?: string[] | any; + rpc?: string | any; + signer?: ethers.Signer | any; + privateKey?: string | undefined; + randomPrivatekey?: boolean; + options?: { + storeOrUseStorageKey?: boolean; + }; + debug?: boolean; + network?: 'cayenne'; + }) { + // this.provider = args?.provider; + this.rpc = args?.rpc; + this.rpcs = args?.rpcs; + this.signer = args?.signer; + this.privateKey = args?.privateKey; + this.provider = args?.provider; + this.randomPrivateKey = args?.randomPrivatekey ?? false; + this.options = args?.options; + this.debug = args?.debug ?? false; + this.network = args?.network || 'cayenne'; + // if rpc is not specified, use the default rpc + if (!this.rpc) { + this.rpc = DEFAULT_RPC; + } + + if (!this.rpcs) { + this.rpcs = [this.rpc]; + } + + // ----- autogen:blank-init:start ----- + // Generated at 2023-11-07T01:50:52.460Z + this.allowlistContract = {} as any; + this.litTokenContract = {} as any; + this.multisenderContract = {} as any; + this.pkpHelperContract = {} as any; + this.pkpNftContract = {} as any; + this.pkpNftMetadataContract = {} as any; + this.pkpPermissionsContract = {} as any; + this.pubkeyRouterContract = {} as any; + this.rateLimitNftContract = {} as any; + this.stakingContract = {} as any; + this.stakingBalancesContract = {} as any; + // ----- autogen:blank-init:end ----- + } + + /** + * Logs a message to the console. + * + * @param {any} [args] An optional value to logDebug with the message. + */ + logDebug = (...args: any) => { + if (this.debug) { + LitContracts.logger.debug(...args); + } + }; + + connect = async () => { + // ======================================= + // SETTING UP PROVIDER + // ======================================= + + // ------------------------------------------------- + // (Browser) Setting up Provider + // ------------------------------------------------- + let wallet; + let SETUP_DONE = false; + + if (isBrowser() && !this.signer) { + this.logDebug("----- We're in the browser! -----"); + + const web3Provider = window.ethereum; + + if (!web3Provider) { + const msg = + 'No web3 provider found. Please install Brave, MetaMask or another web3 provider.'; + alert(msg); + throw new Error(msg); + } + + const chainInfo = { + chainId: '0x2AC49', + chainName: 'Chronicle - Lit Protocol Testnet', + nativeCurrency: { name: 'LIT', symbol: 'LIT', decimals: 18 }, + rpcUrls: this.rpcs, + blockExplorerUrls: [BLOCK_EXPLORER], + iconUrls: ['future'], + }; + + try { + await web3Provider.send('wallet_switchEthereumChain', [ + { chainId: chainInfo.chainId }, + ]); + } catch (e) { + await web3Provider.request({ + method: 'wallet_addEthereumChain', + params: [chainInfo], + }); + } + + wallet = new ethers.providers.Web3Provider(web3Provider); + + await wallet.send('eth_requestAccounts', []); + + // this will ask metamask to connect to the wallet + // this.signer = wallet.getSigner(); + + this.provider = wallet; + } + + // ---------------------------------------------- + // (Node) Setting up Provider + // ---------------------------------------------- + if (isNode()) { + this.logDebug("----- We're in node! -----"); + this.provider = new ethers.providers.JsonRpcProvider(this.rpc); + } + + // ====================================== + // CUSTOM PRIVATE KEY + // ====================================== + if (this.privateKey) { + this.logDebug('Using your own private key'); + this.signer = new ethers.Wallet(this.privateKey, this.provider); + this.provider = this.signer.provider; + SETUP_DONE = true; + } + + // ===================================== + // SETTING UP SIGNER + // ===================================== + if ( + (!this.privateKey && this.randomPrivateKey) || + this.options?.storeOrUseStorageKey + ) { + console.warn('THIS.SIGNER:', this.signer); + + let STORAGE_KEY = 'lit-contracts-sdk-private-key'; + + this.logDebug( + "Let's see if you have a private key in your local storage!" + ); + + // -- find private key in local storage + let storagePrivateKey; + + try { + storagePrivateKey = localStorage.getItem(STORAGE_KEY); + } catch (e) { + // swallow + // this.logDebug('Not a problem.'); + } + + // -- (NOT FOUND) no private key found + if (!storagePrivateKey) { + this.logDebug('Not a problem, we will generate a random private key'); + storagePrivateKey = ethers.utils.hexlify(ethers.utils.randomBytes(32)); + } + + // -- (FOUND) private key found + else { + this.logDebug("Found your private key in local storage. Let's use it!"); + } + + this.signer = new ethers.Wallet(storagePrivateKey, this.provider); + + this.logDebug('- Your private key:', storagePrivateKey); + this.logDebug('- Your address:', await this.signer.getAddress()); + this.logDebug('- this.signer:', this.signer); + this.logDebug('- this.provider.getSigner():', this.provider.getSigner()); + + // -- (OPTION) store private key in local storage + if (this.options?.storeOrUseStorageKey) { + console.warn( + "You've set the option to store your private key in local storage." + ); + localStorage.setItem(STORAGE_KEY, storagePrivateKey); + } + } else { + // ---------------------------------------- + // Ask Metamask to sign + // ---------------------------------------- + if (isBrowser() && wallet && !SETUP_DONE) { + // this.logDebug('HERE????'); + this.logDebug('this.signer:', this.signer); + this.signer = wallet.getSigner(); + } + } + + if (this.signer !== undefined && this.signer !== null) { + if ('litNodeClient' in this.signer && 'rpcProvider' in this.signer) { + this.logDebug(` + // *********************************************************************************************** + // THIS IS A PKP WALLET, USING IT AS A SIGNER AND ITS RPC PROVIDER AS PROVIDER + // *********************************************************************************************** + `); + + // @ts-ignore + this.provider = this.signer.rpcProvider; + this.isPKP = true; + } + } + + this.logDebug('Your Signer:', this.signer); + this.logDebug('Your Provider:', this.provider); + + if (!this.provider) { + this.logDebug( + 'No provide found. Will try to use the one from the signer.' + ); + this.provider = this.signer.provider; + this.logDebug('Your Provider(from signer):', this.provider); + } + + let addresses: any = await LitContracts.getContractAddresses(this.network); + this.logDebug('resolved contract addresses for: ', this.network, addresses); + // ----- autogen:init:start ----- + // Generated at 2023-11-07T01:50:52.460Z + + this.allowlistContract = { + read: new ethers.Contract( + addresses.Allowlist.address, + addresses.Allowlist.abi as any, + this.provider + ) as unknown as allowlistContract.Allowlist & allowlistContract.Allowlist, + write: new ethers.Contract( + addresses.Allowlist.address, + addresses.Allowlist.abi as any, + this.signer + ) as unknown as allowlistContract.Allowlist & allowlistContract.Allowlist, + }; + + this.litTokenContract = { + read: new ethers.Contract( + addresses.LITToken.address, + addresses.LITToken.abi as any, + this.provider + ) as unknown as litTokenContract.LITToken & litTokenContract.LITToken, + write: new ethers.Contract( + addresses.LITToken.address, + addresses.LITToken.abi as any, + this.signer + ) as unknown as litTokenContract.LITToken & litTokenContract.LITToken, + }; + + this.multisenderContract = { + read: new ethers.Contract( + addresses.Multisender.address, + addresses.Multisender.abi as any, + this.provider + ) as unknown as multisenderContract.Multisender & + multisenderContract.Multisender, + write: new ethers.Contract( + addresses.Multisender.address, + addresses.Multisender.abi as any, + this.signer + ) as unknown as multisenderContract.Multisender & + multisenderContract.Multisender, + }; + + this.pkpHelperContract = { + read: new ethers.Contract( + addresses.PKPHelper.address, + addresses.PKPHelper.abi as any, + this.provider + ) as unknown as pkpHelperContract.PKPHelper & pkpHelperContract.PKPHelper, + write: new ethers.Contract( + addresses.PKPHelper.address, + addresses.PKPHelper.abi as any, + this.signer + ) as unknown as pkpHelperContract.PKPHelper & pkpHelperContract.PKPHelper, + }; + + this.pkpNftContract = { + read: new ethers.Contract( + addresses.PKPNFT.address, + addresses.PKPNFT.abi as any, + this.provider + ) as unknown as pkpNftContract.PKPNFT & pkpNftContract.PKPNFT, + write: new ethers.Contract( + addresses.PKPNFT.address, + addresses.PKPNFT.abi as any, + this.signer + ) as unknown as pkpNftContract.PKPNFT & pkpNftContract.PKPNFT, + }; + + this.pkpNftMetadataContract = { + read: new ethers.Contract( + addresses.PKPNFTMetadata.address, + addresses.PKPNFTMetadata.abi as any, + this.provider + ) as unknown as pkpNftMetadataContract.PKPNFTMetadata & + pkpNftMetadataContract.PKPNFTMetadata, + write: new ethers.Contract( + addresses.PKPNFTMetadata.address, + addresses.PKPNFTMetadata.abi as any, + this.signer + ) as unknown as pkpNftMetadataContract.PKPNFTMetadata & + pkpNftMetadataContract.PKPNFTMetadata, + }; + + this.pkpPermissionsContract = { + read: new ethers.Contract( + addresses.PKPPermissions.address, + addresses.PKPPermissions.abi as any, + this.provider + ) as unknown as pkpPermissionsContract.PKPPermissions & + pkpPermissionsContract.PKPPermissions, + write: new ethers.Contract( + addresses.PKPPermissions.address, + addresses.PKPPermissions.abi as any, + this.signer + ) as unknown as pkpPermissionsContract.PKPPermissions & + pkpPermissionsContract.PKPPermissions, + }; + + this.pubkeyRouterContract = { + read: new ethers.Contract( + addresses.PubkeyRouter.address, + addresses.PubkeyRouter.abi as any, + this.provider + ) as unknown as pubkeyRouterContract.PubkeyRouter & + pubkeyRouterContract.PubkeyRouter, + write: new ethers.Contract( + addresses.PubkeyRouter.address, + addresses.PubkeyRouter.abi as any, + this.signer + ) as unknown as pubkeyRouterContract.PubkeyRouter & + pubkeyRouterContract.PubkeyRouter, + }; + + this.rateLimitNftContract = { + read: new ethers.Contract( + addresses.RateLimitNFT.address, + addresses.RateLimitNFT.abi as any, + this.provider + ) as unknown as rateLimitNftContract.RateLimitNFT & + rateLimitNftContract.RateLimitNFT, + write: new ethers.Contract( + addresses.RateLimitNFT.address, + addresses.RateLimitNFT.abi as any, + this.signer + ) as unknown as rateLimitNftContract.RateLimitNFT & + rateLimitNftContract.RateLimitNFT, + }; + + this.stakingContract = { + read: new ethers.Contract( + addresses.Staking.address, + addresses.Staking.abi as any, + this.provider + ) as unknown as stakingContract.Staking & stakingContract.Staking, + write: new ethers.Contract( + addresses.Staking.address, + addresses.Staking.abi as any, + this.signer + ) as unknown as stakingContract.Staking & stakingContract.Staking, + }; + + this.stakingBalancesContract = { + read: new ethers.Contract( + addresses.StakingBalances.address, + addresses.StakingBalances.abi as any, + this.provider + ) as unknown as stakingBalancesContract.StakingBalances & + stakingBalancesContract.StakingBalances, + write: new ethers.Contract( + addresses.StakingBalances.address, + addresses.StakingBalances.abi as any, + this.signer + ) as unknown as stakingBalancesContract.StakingBalances & + stakingBalancesContract.StakingBalances, + }; + // ----- autogen:init:end ----- + + this.connected = true; + }; + + public static async getStakingContract( + network: 'cayenne' | 'custom' | 'localhost' + ) { + let manifest = await LitContracts._resolveContractContext(network); + + const rpcUrl = DEFAULT_RPC; + const provider = new ethers.providers.JsonRpcProvider(rpcUrl); + + const { config, data: contractData } = manifest; + + const stakingContract = contractData.find( + (item: { name: string }) => item.name === 'Staking' + ).contracts[0]; + const { address_hash, ABI } = stakingContract; + + // Validate the required data + if (!address_hash || !ABI) { + throw new Error('❌ Required contract data is missing'); + } + + return new ethers.Contract(address_hash, ABI, provider); + } + + public static async getContractAddresses( + network: 'cayenne' | 'custom' | 'localhost' + ) { + const data = await LitContracts._resolveContractContext(network); + // Destructure the data for easier access + const { config, data: contractData } = data; + const addresses: any = {}; + for (const contract of contractData) { + switch (contract.name) { + case 'Allowlist': + addresses.Allowlist = {}; + addresses.Allowlist.address = contract.contracts[0].address_hash; + addresses.Allowlist.abi = contract.contracts[0].ABI; + break; + case 'PKPHelper': + addresses.PKPHelper = {}; + addresses.PKPHelper.address = contract.contracts[0].address_hash; + addresses.PKPHelper.abi = contract.contracts[0].ABI; + break; + case 'PKPNFT': + addresses.PKPNFT = {}; + addresses.PKPNFT.address = contract.contracts[0].address_hash; + addresses.PKPNFT.abi = contract.contracts[0].ABI; + break; + case 'Staking': + addresses.Staking = {}; + addresses.Staking.address = contract.contracts[0].address_hash; + addresses.Staking.abi = contract.contracts[0].ABI; + break; + case 'RateLimitNFT': + addresses.RateLimitNFT = {}; + addresses.RateLimitNFT.address = contract.contracts[0].address_hash; + addresses.RateLimitNFT.abi = contract.contracts[0].ABI; + break; + case 'PKPPermissions': + addresses.PKPPermissions = {}; + addresses.PKPPermissions.address = contract.contracts[0].address_hash; + addresses.PKPPermissions.abi = contract.contracts[0].ABI; + break; + case 'PKPNFTMetadata': + addresses.PKPNFTMetadata = {}; + addresses.PKPNFTMetadata.address = contract.contracts[0].address_hash; + addresses.PKPNFTMetadata.abi = contract.contracts[0].ABI; + break; + case 'PubkeyRouter': + addresses.PubkeyRouter = {}; + addresses.PubkeyRouter.address = contract.contracts[0].address_hash; + addresses.PubkeyRouter.abi = contract.contracts[0].ABI; + break; + case 'LITToken': + addresses.LITToken = {}; + addresses.LITToken.address = contract.contracts[0].address_hash; + addresses.LITToken.abi = contract.contracts[0].ABI; + break; + case 'StakingBalances': + addresses.StakingBalances = {}; + addresses.StakingBalances.address = + contract.contracts[0].address_hash; + addresses.StakingBalances.abi = contract.contracts[0].ABI; + break; + case 'Multisender': + addresses.Multisender = {}; + addresses.Multisender.address = contract.contracts[0].address_hash; + addresses.Multisender.abi = contract.contracts[0].ABI; + break; + } + } + + // Validate the required data + if (Object.keys(addresses).length < 5) { + throw new Error('❌ Required contract data is missing'); + } + + return addresses; + } + + public static getMinNodeCount = async ( + network: 'cayenne' | 'custom' | 'localhost' + ) => { + const contract = await LitContracts.getStakingContract(network); + + const minNodeCount = await contract['currentValidatorCountForConsensus'](); + + if (!minNodeCount) { + throw new Error('❌ Minimum validator count is not set'); + } + return minNodeCount; + }; + + public static getValidators = async ( + network: 'cayenne' | 'custom' | 'localhost' + ): Promise => { + const contract = await LitContracts.getStakingContract(network); + + // Fetch contract data + const [activeValidators, currentValidatorsCount, kickedValidators] = + await Promise.all([ + contract['getValidatorsInCurrentEpoch'](), + contract['currentValidatorCountForConsensus'](), + contract['getKickedValidators'](), + ]); + + const validators = []; + + // Check if active validator set meets the threshold + if ( + activeValidators.length - kickedValidators.length >= + currentValidatorsCount + ) { + // Process each validator + for (const validator of activeValidators) { + validators.push(validator); + } + } else { + LitContracts.logger.error( + '❌ Active validator set does not meet the threshold' + ); + } + + // remove kicked validators in active validators + const cleanedActiveValidators = activeValidators.filter( + (av: any) => !kickedValidators.some((kv: any) => kv === av) + ); + + const activeValidatorStructs = await contract['getValidatorsStructs']( + cleanedActiveValidators + ); + + const networks = activeValidatorStructs.map((item: any) => { + let proto = 'https://'; + if (item.port !== 443) { + proto = 'http://'; + } + return `${proto}${intToIP(item.ip)}:${item.port}`; + }); + + return networks; + }; + + private static async _resolveContractContext( + network: 'cayenne' | 'custom' | 'localhost' + ) { + let data; + const CAYENNE_API = + 'https://lit-general-worker.getlit.dev/contract-addresses'; + if (network === 'cayenne') { + try { + // Fetch and parse the JSON data in one step + data = await fetch(CAYENNE_API).then((res) => res.json()); + } catch (e: any) { + throw new Error( + `Error fetching data from ${CAYENNE_API}: ${e.toString()}` + ); + } + } + + return data; + } + + mintWithAuth = async ({ + authMethod, + scopes, + pubkey, + }: { + authMethod: AuthMethod; + scopes: string[] | number[] | BigNumberish[]; + pubkey?: string; // only applies to webauthn auth method + }) => { + // -- validate + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpNftContract) { + throw new Error('Contract is not available'); + } + + if (authMethod && !authMethod?.authMethodType) { + throw new Error('authMethodType is required'); + } + + if (authMethod && !authMethod?.accessToken) { + throw new Error('accessToken is required'); + } + + if (scopes.length <= 0) { + throw new Error(`❌ Permission scopes are required! +[0] No Permissions +[1] Sign Anything +[2] Only Sign Messages +Read more here: +https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scopes + `); + } + + // -- prepare + const _pubkey = pubkey ?? '0x'; + + // if scopes are list of strings, turn them into numbers + scopes = scopes.map((scope: any) => { + if (typeof scope === 'string') { + return ethers.BigNumber.from(scope); + } + if (typeof scope === 'number') { + return ethers.BigNumber.from(scope.toString()); + } + return scope; + }); + + const authId = await getAuthIdByAuthMethod(authMethod); + + // -- go + const mintCost = await this.pkpNftContract.read.mintCost(); + + // -- start minting + const tx = await this.pkpHelperContract.write.mintNextAndAddAuthMethods( + 2, // key type + [authMethod.authMethodType], + [authId], + [_pubkey], + [[...scopes]], + true, + true, + { + value: mintCost, + } + ); + + const receipt = await tx.wait(); + + let events = 'events' in receipt ? receipt.events : receipt.logs; + + if (!events) { + throw new Error('No events found in receipt'); + } + + let tokenId; + + tokenId = events[0].topics[1]; + console.warn('tokenId:', tokenId); + + let publicKey = await this.pkpNftContract.read.getPubkey(tokenId); + + if (publicKey.startsWith('0x')) { + publicKey = publicKey.slice(2); + } + + const pubkeyBuffer = Buffer.from(publicKey, 'hex'); + + const ethAddress = computeAddress(pubkeyBuffer); + + return { + pkp: { + tokenId, + publicKey, + ethAddress, + }, + tx: receipt, + }; + }; + + // getRandomPrivateKeySignerProvider = () => { + // const privateKey = ethers.utils.hexlify(ethers.utils.randomBytes(32)); + + // let provider; + + // if (isBrowser()) { + // provider = new ethers.providers.Web3Provider(window.ethereum, 'any'); + // } else { + // provider = new ethers.providers.JsonRpcProvider(this.rpc); + // } + // const signer = new ethers.Wallet(privateKey, provider); + + // return { privateKey, signer, provider }; + // }; + + // getPrivateKeySignerProvider = (privateKey: string) => { + // let provider; + + // if (isBrowser()) { + // provider = new ethers.providers.Web3Provider(window.ethereum, 'any'); + // } else { + // provider = new ethers.providers.JsonRpcProvider(this.rpc); + // } + // const signer = new ethers.Wallet(privateKey, provider); + + // return { privateKey, signer, provider }; + // }; + + utils = { + hexToDec, + decToHex, + /** + * Partition multihash string into object representing multihash + * + * @param {string} multihash A base58 encoded multihash string + * @returns {Multihash} + */ + getBytesFromMultihash: (multihash: string) => { + const decoded = bs58.decode(multihash); + + return `0x${Buffer.from(decoded).toString('hex')}`; + }, + + /** + * + * Convert bytes32 to IPFS ID + * @param { string } byte32 0x1220baa0d1e91f2a22fef53659418ddc3ac92da2a76d994041b86ed62c0c999de477 + * @returns { string } QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW + */ + getMultihashFromBytes: (byte32: string): string => { + const text = byte32.replace('0x', ''); + + const hashFunction = parseInt(text.slice(0, 2), 16); + const digestSize = parseInt(text.slice(2, 4), 16); + const digest = text.slice(4, 4 + digestSize * 2); + + const multihash = bs58.encode(Buffer.from(`1220${digest}`, 'hex')); + + return multihash; + }, + /** + * Partition multihash string into object representing multihash + * + * @param {string} multihash A base58 encoded multihash string + * @returns {Multihash} + */ + getBytes32FromMultihash: (ipfsId: string) => { + const cid = CID.parse(ipfsId); + const hashFunction = cid.multihash.code; + const size = cid.multihash.size; + const digest = '0x' + Buffer.from(cid.multihash.digest).toString('hex'); + + let ipfsHash: IPFSHash = { + digest, + hashFunction, + size, + }; + + return ipfsHash; + }, + + // convert timestamp to YYYY/MM/DD format + timestamp2Date: (timestamp: string): string => { + const date = require('date-and-time'); + + const format = 'YYYY/MM/DD HH:mm:ss'; + + let timestampFormatted: Date = new Date(parseInt(timestamp) * 1000); + + return date.format(timestampFormatted, format); + }, + }; + + pkpNftContractUtils = { + read: { + /** + * (IERC721Enumerable) + * + * Get all PKPs by a given address + * + * @param { string } ownerAddress + * @retu + * */ + + getTokensByAddress: async ( + ownerAddress: string + ): Promise> => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + if (!this.pkpNftContract) { + throw new Error('Contract is not available'); + } + + // -- validate + if (!ethers.utils.isAddress(ownerAddress)) { + throw new Error( + `Given string is not a valid address "${ownerAddress}"` + ); + } + + let tokens = []; + + for (let i = 0; ; i++) { + let token; + + try { + token = await this.pkpNftContract.read.tokenOfOwnerByIndex( + ownerAddress, + i + ); + + token = this.utils.hexToDec(token.toHexString()) as string; + + tokens.push(token); + } catch (e) { + this.logDebug(`[getTokensByAddress] Ended search on index: ${i}`); + break; + } + } + + return tokens; + }, + + /** + * (IERC721Enumerable) + * + * Get the x latest number of tokens + * + * @param { number } latestNumberOfTokens + * + * @returns { Array } a list of PKP NFTs + * + */ + getTokens: async ( + latestNumberOfTokens: number + ): Promise> => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + if (!this.pkpNftContract) { + throw new Error('Contract is not available'); + } + + let tokens = []; + + for (let i = 0; ; i++) { + if (i >= latestNumberOfTokens) { + break; + } + + let token; + + try { + token = await this.pkpNftContract.read.tokenByIndex(i); + + token = this.utils.hexToDec(token.toHexString()) as string; + + tokens.push(token); + } catch (e) { + this.logDebug(`[getTokensByAddress] Ended search on index: ${i}`); + break; + } + } + + return tokens; + }, + + /** + * Get info of all PKPs by a given address + */ + getTokensInfoByAddress: async ( + ownerAddress: string + ): Promise> => { + const tokenIds = await this.pkpNftContractUtils.read.getTokensByAddress( + ownerAddress + ); + + const arr = []; + + // for each pkp + for (let i = 0; i < tokenIds.length; i++) { + const tokenId = tokenIds[i]; + const pubKey = await this.pkpNftContract.read.getPubkey(tokenId); + const addrs = await derivedAddresses({ + pkpTokenId: tokenId, + publicKey: pubKey, + }); + + arr.push(addrs); + } + + return arr; + }, + }, + write: { + mint: async () => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpNftContract) { + throw new Error('Contract is not available'); + } + + let mintCost; + + try { + mintCost = await this.pkpNftContract.read.mintCost(); + } catch (e) { + throw new Error('Could not get mint cost'); + } + + let sentTx; + + if (this.isPKP) { + this.logDebug( + "This is a PKP wallet, so we'll use the PKP wallet to sign the tx" + ); + + this.logDebug('...populating tx'); + let tx = await this.pkpNftContract.write.populateTransaction.mintNext( + 2, + { value: mintCost } + ); + this.logDebug('tx:', tx); + + this.logDebug('...signing tx'); + let signedTx = await this.signer.signTransaction(tx); + this.logDebug('signedTx:', signedTx); + + this.logDebug('sending signed tx...'); + sentTx = await this.signer.sendTransaction( + signedTx as ethers.providers.TransactionRequest + ); + } else { + sentTx = await this.pkpNftContract.write.mintNext(2, { + value: mintCost, + }); + } + + this.logDebug('sentTx:', sentTx); + + const res: any = await sentTx.wait(); + this.logDebug('res:', res); + + let events = 'events' in res ? res.events : res.logs; + + let tokenIdFromEvent; + + tokenIdFromEvent = events[0].topics[1]; + console.warn('tokenIdFromEvent:', tokenIdFromEvent); + + let publicKey = await this.pkpNftContract.read.getPubkey( + tokenIdFromEvent + ); + + if (publicKey.startsWith('0x')) { + publicKey = publicKey.slice(2); + } + + const pubkeyBuffer = Buffer.from(publicKey, 'hex'); + + const ethAddress = computeAddress(pubkeyBuffer); + + return { + pkp: { + tokenId: tokenIdFromEvent, + publicKey, + ethAddress, + }, + tx: sentTx, + tokenId: tokenIdFromEvent, + res, + }; + }, + + claimAndMint: async ( + derivedKeyId: BytesLike, + signatures: IPubkeyRouter.SignatureStruct[], + txOpts?: any + ) => { + let cost = await this.pkpNftContract.read.mintCost(); + const tx = await this.pkpNftContract.write.claimAndMint( + 2, + derivedKeyId, + signatures, + txOpts ?? { value: cost } + ); + let txRec = await tx.wait(); + let events: any = 'events' in txRec ? txRec.events : txRec.logs; + let tokenId = events[1].topics[1]; + return { tx, res: txRec, tokenId }; + }, + }, + }; + + pkpPermissionsContractUtils = { + read: { + /** + * + * Check if an address is permitted + * + * @param { string } tokenId + * @param { string } address + * + * @returns { Promise } + */ + isPermittedAddress: async ( + tokenId: string, + address: string + ): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + const pkpIdHex = this.utils.decToHex(tokenId, null); + + const bool = await this.pkpPermissionsContract.read.isPermittedAddress( + pkpIdHex as any, + address + ); + + return bool; + }, + + getPermittedAddresses: async ( + tokenId: string + ): Promise> => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + this.logDebug('[getPermittedAddresses] input:', tokenId); + + let addresses: Array = []; + + const maxTries = 5; + let tries = 0; + + while (tries < maxTries) { + try { + addresses = + await this.pkpPermissionsContract.read.getPermittedAddresses( + tokenId + ); + if (addresses.length <= 0) { + await new Promise((resolve: any) => setTimeout(resolve, 1000)); + tries++; + continue; + } else { + break; + } + } catch (e: any) { + this.logDebug( + `[getPermittedAddresses] error:`, + e.message + ); + tries++; + } + } + + return addresses; + }, + + /** + * + * Get permitted action + * + * @param { any } id + * + * @returns { Promise> } + * + */ + getPermittedActions: async (tokenId: any): Promise> => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + let actions: Array = []; + + const maxTries = 5; + let tries = 0; + + while (tries < maxTries) { + try { + actions = + await this.pkpPermissionsContract.read.getPermittedActions( + tokenId + ); + + if (actions.length <= 0) { + await new Promise((resolve: any) => setTimeout(resolve, 1000)); + tries++; + continue; + } else { + break; + } + } catch (e: any) { + this.logDebug( + `[getPermittedActions] error:`, + e.message + ); + tries++; + } + } + + return actions; + }, + + /** + * + * Check if an action is permitted given the pkpid and ipfsId + * + * @param { string } pkpId 103309008291725705563022469659474510532358692659842796086905702509072063991354 + * @param { string } ipfsId QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW + * + * @return { object } transaction + */ + isPermittedAction: async ( + pkpId: string, + ipfsId: string + ): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + this.logDebug('[isPermittedAction] input:', pkpId); + this.logDebug('[isPermittedAction] input:', ipfsId); + + const ipfsHash = this.utils.getBytesFromMultihash(ipfsId); + this.logDebug('[isPermittedAction] converted:', ipfsHash); + + const bool = await this.pkpPermissionsContract.read.isPermittedAction( + pkpId, + ipfsHash as any + ); + + return bool; + }, + }, + + write: { + /** + * + * Add permitted action to a given PKP id & ipfsId + * + * @param { string } pkpId 103309008291725705563022469659474510532358692659842796086905702509072063991354 + * @param { string } ipfsId QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW + * + * @return { object } transaction + */ + addPermittedAction: async ( + pkpId: string, + ipfsId: string + ): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract || !this.pubkeyRouterContract) { + throw new Error('Contract is not available'); + } + + this.logDebug('[addPermittedAction] input:', pkpId); + + const pubKey = await this.pubkeyRouterContract.read.getPubkey(pkpId); + this.logDebug('[addPermittedAction] converted:', pubKey); + + const pubKeyHash = ethers.utils.keccak256(pubKey); + this.logDebug( + '[addPermittedAction] converted:', + pubKeyHash + ); + + const tokenId = ethers.BigNumber.from(pubKeyHash); + this.logDebug('[addPermittedAction] converted:', tokenId); + + this.logDebug('[addPermittedAction] input:', ipfsId); + + const ipfsIdBytes = this.utils.getBytesFromMultihash(ipfsId); + this.logDebug( + '[addPermittedAction] converted:', + ipfsIdBytes + ); + + const tx = await this.pkpPermissionsContract.write.addPermittedAction( + tokenId, + ipfsIdBytes as any, + [1] + ); + this.logDebug('[addPermittedAction] output:', tx); + + return tx; + }, + + /** + * TODO: add transaction type + * Add permitted action to a given PKP id & ipfsId + * + * @param { string } pkpId 103309008291725705563022469659474510532358692659842796086905702509072063991354 + * @param { string } ownerAddress 0x3B5dD2605.....22aDC499A1 + * + * @return { object } transaction + */ + addPermittedAddress: async ( + pkpId: string, + ownerAddress: string + ): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + this.logDebug('[addPermittedAddress] input:', pkpId); + this.logDebug( + '[addPermittedAddress] input:', + ownerAddress + ); + + this.logDebug('[addPermittedAddress] input:', pkpId); + + const tx = await this.pkpPermissionsContract.write.addPermittedAddress( + pkpId, + ownerAddress, + [1] + ); + + this.logDebug('[addPermittedAddress] output:', tx); + + return tx; + }, + + /** + * Revoke permitted action of a given PKP id & ipfsId + * + * @param { string } pkpId 103309008291725705563022469659474510532358692659842796086905702509072063991354 + * @param { string } ipfsId QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW + * + * @return { object } transaction + */ + revokePermittedAction: async ( + pkpId: string, + ipfsId: string + ): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.pkpPermissionsContract) { + throw new Error('Contract is not available'); + } + + this.logDebug('[revokePermittedAction] input:', pkpId); + this.logDebug('[revokePermittedAction] input:', ipfsId); + + const ipfsHash = this.utils.getBytesFromMultihash(ipfsId); + this.logDebug('[revokePermittedAction] converted:', ipfsHash); + + const tx = + await this.pkpPermissionsContract.write.removePermittedAction( + pkpId, + ipfsHash as any + ); + this.logDebug('[revokePermittedAction] output:', tx); + + return tx; + }, + }, + }; + + rateLimitNftContractUtils = { + read: { + /** + * getCapacityByIndex: async (index: number): Promise => { + * + * This function takes a token index as a parameter and returns the capacity of the token + * with the given index. The capacity is an object that contains the number of requests + * per millisecond that the token allows, and an object with the expiration timestamp and + * formatted expiration date of the token. + * + * @param {number} index - The index of the token. + * @returns {Promise} - A promise that resolves to the capacity of the token. + * + * Example: + * + * const capacity = await getCapacityByIndex(1); + * this.logDebug(capacity); + * // Output: { + * // requestsPerMillisecond: 100, + * // expiresAt: { + * // timestamp: 1623472800, + * // formatted: '2022-12-31', + * // }, + * // } + * + * } + */ + getCapacityByIndex: async (index: number): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const capacity = await this.rateLimitNftContract.read.capacity(index); + + return { + requestsPerMillisecond: parseInt(capacity[0].toString()), + expiresAt: { + timestamp: parseInt(capacity[1].toString()), + formatted: this.utils.timestamp2Date(capacity[1].toString()), + }, + }; + }, + + /** + * getTokenURIByIndex: async (index: number): Promise => { + * + * This function takes a token index as a parameter and returns the URI of the token + * with the given index. + * + * @param {number} index - The index of the token. + * @returns {Promise} - A promise that resolves to the URI of the token. + * + * Example: + * + * const URI = await getTokenURIByIndex(1); + * this.logDebug(URI); + * // Output: 'https://tokens.com/1' + * + * } + */ + getTokenURIByIndex: async (index: number): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const base64 = await this.rateLimitNftContract.read.tokenURI(index); + + const data = base64.split('data:application/json;base64,')[1]; + + const dataToString = Buffer.from(data, 'base64').toString('binary'); + + return JSON.parse(dataToString); + }, + + /** + * getTokensByOwnerAddress: async (ownerAddress: string): Promise => { + * + * This function takes an owner address as a parameter and returns an array of tokens + * that are owned by the given address. + * + * @param {string} ownerAddress - The address of the owner. + * @returns {Promise} - A promise that resolves to an array of token objects. + * + * Example: + * + * const tokens = await getTokensByOwnerAddress('0x1234...5678'); + * this.logDebug(tokens); + * // Output: [ + * // { + * // tokenId: 1, + * // URI: 'https://tokens.com/1', + * // capacity: 100, + * // isExpired: false, + * // }, + * // { + * // tokenId: 2, + * // URI: 'https://tokens.com/2', + * // capacity: 200, + * // isExpired: true, + * // }, + * // ... + * // ] + * + * } + */ + getTokensByOwnerAddress: async (ownerAddress: string): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + // -- validate + if (!ethers.utils.isAddress(ownerAddress)) { + throw Error(`Given string is not a valid address "${ownerAddress}"`); + } + + let total: any = await this.rateLimitNftContract.read.balanceOf( + ownerAddress + ); + total = parseInt(total.toString()); + + const tokens = await asyncForEachReturn( + [...new Array(total)], + async (_: undefined, i: number) => { + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const token = + await this.rateLimitNftContract.read.tokenOfOwnerByIndex( + ownerAddress, + i + ); + + const tokenIndex = parseInt(token.toString()); + + const URI = + await this.rateLimitNftContractUtils.read.getTokenURIByIndex( + tokenIndex + ); + + const capacity = + await this.rateLimitNftContractUtils.read.getCapacityByIndex( + tokenIndex + ); + + const isExpired = await this.rateLimitNftContract.read.isExpired( + tokenIndex + ); + + return { + tokenId: parseInt(token.toString()), + URI, + capacity, + isExpired, + }; + } + ); + + return tokens; + }, + + /** + * getTokens: async (): Promise => { + * + * This function returns an array of all tokens that have been minted. + * + * @returns {Promise} - A promise that resolves to an array of token objects. + * + * Example: + * + * const tokens = await getTokens(); + * this.logDebug(tokens); + * // Output: [ + * // { + * // tokenId: 1, + * // URI: 'https://tokens.com/1', + * // capacity: 100, + * // isExpired: false, + * // }, + * // { + * // tokenId: 2, + * // URI: 'https://tokens.com/2', + * // capacity: 200, + * // isExpired: true, + * // }, + * // ... + * // ] + * + * } + */ + getTokens: async (): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + let total: any = await this.rateLimitNftContract.read.totalSupply(); + total = parseInt(total.toString()); + + const tokens = await asyncForEachReturn( + [...new Array(total)], + async (_: any, i: number) => { + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const token = await this.rateLimitNftContract.read.tokenByIndex(i); + + const tokenIndex = parseInt(token.toString()); + + const URI = + await this.rateLimitNftContractUtils.read.getTokenURIByIndex( + tokenIndex + ); + + const capacity = + await this.rateLimitNftContractUtils.read.getCapacityByIndex( + tokenIndex + ); + + const isExpired = await this.rateLimitNftContract.read.isExpired( + tokenIndex + ); + + return { + tokenId: parseInt(token.toString()), + URI, + capacity, + isExpired, + }; + } + ); + + return tokens; + }, + }, + write: { + mint: async ({ + mintCost, + timestamp, + }: { + mintCost: { + value: any; + }; + timestamp: number; + }) => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const tx = await this.rateLimitNftContract.write.mint( + timestamp, + mintCost + ); + + const res: any = await tx.wait(); + + const tokenIdFromEvent = res.events[0].topics[1]; + + return { tx, tokenId: tokenIdFromEvent }; + }, + /** + * Transfer RLI token from one address to another + * + * @property { string } fromAddress + * @property { string } toAddress + * @property { stsring } RLITokenAddress + * + * @return { > } void + */ + transfer: async ({ + fromAddress, + toAddress, + RLITokenAddress, + }: { + fromAddress: string; + toAddress: string; + RLITokenAddress: string; + }): Promise => { + if (!this.connected) { + throw new Error( + 'Contracts are not connected. Please call connect() first' + ); + } + + if (!this.rateLimitNftContract) { + throw new Error('Contract is not available'); + } + + const tx = await this.rateLimitNftContract.write.transferFrom( + fromAddress, + toAddress, + RLITokenAddress + ); + + this.logDebug('tx:', tx); + + // const res = await tx.wait(); + + // return { + // tx, + // events: res.events + // } + + return tx; + }, + }, + }; + + routerContractUtils = { + read: { + /** + * + * Convert IPFS response from Solidity to IPFS ID + * From: "0xb4200a696794b8742fab705a8c065ea6788a76bc6d270c0bc9ad900b6ed74ebc" + * To: "QmUnwHVcaymJWiYGQ6uAHvebGtmZ8S1r9E6BVmJMtuK5WY" + * + * @param { string } solidityIpfsId + * + * @return { Promise } + */ + // getIpfsIds: async (solidityIpfsId: string): Promise => { + // this.logDebug('[getIpfsIds] input:', solidityIpfsId); + // const ipfsId = this.utils.getMultihashFromBytes(solidityIpfsId); + // this.logDebug('[getIpfsIds] output:', ipfsId); + // return ipfsId; + // }, + }, + write: {}, + }; + + pkpHelperContractUtil = { + read: {}, + + write: { + /** + * + * @param param0 + * @returns + */ + mintNextAndAddAuthMethods: async ({ + keyType, + permittedAuthMethodTypes, + permittedAuthMethodIds, + permittedAuthMethodPubkeys, + permittedAuthMethodScopes, + addPkpEthAddressAsPermittedAddress, + sendPkpToItself, + }: { + keyType: string; + permittedAuthMethodTypes: string[]; + permittedAuthMethodIds: string[]; + permittedAuthMethodPubkeys: string[]; + permittedAuthMethodScopes: string[][]; + addPkpEthAddressAsPermittedAddress: boolean; + sendPkpToItself: boolean; + }): Promise => { + // first get mint cost + const mintCost = await this.pkpNftContract.read.mintCost(); + const tx = await this.pkpHelperContract.write.mintNextAndAddAuthMethods( + keyType, + permittedAuthMethodTypes, + permittedAuthMethodIds as BytesLike[], + permittedAuthMethodPubkeys as BytesLike[], + permittedAuthMethodScopes, + addPkpEthAddressAsPermittedAddress, + sendPkpToItself, + { value: mintCost } + ); + console.logDebug('tx', tx); + return tx; + }, + // claimAndMintNextAndAddAuthMethods: async ( + // keyType: number, + // derivedKeyId: string, + // signatures: pkpHelperContract.IPubkeyRouter.SignatureStruct[], + // permittedAuthMethodTypes: string[], + // permittedAuthMethodIds: string[], + // permittedAuthMethodPubkeys: string[], + // permittedAuthMethodScopes: string[][], + // addPkpEthAddressAsPermittedAddress: boolean, + // sendPkpToItself: boolean + // ): Promise => { + // const mintCost = await this.pkpNftContract.read.mintCost(); + // this.pkpHelperContract.write.claimAndMintNextAndAddAuthMethods( + // keyType, + // `0x${derivedKeyId}` as BytesLike, + // signatures, + // permittedAuthMethodTypes, + // permittedAuthMethodIds as BytesLike[], + // permittedAuthMethodPubkeys as BytesLike[], + // permittedAuthMethodScopes, + // addPkpEthAddressAsPermittedAddress, + // sendPkpToItself, + // { value: mintCost } + // ); + // }, + }, + }; +} diff --git a/packages/lit-node-client/src/lib/hashing.ts b/packages/lit-node-client/src/lib/hashing.ts new file mode 100644 index 0000000000..8a7cee7268 --- /dev/null +++ b/packages/lit-node-client/src/lib/hashing.ts @@ -0,0 +1,171 @@ +import { LIT_ERROR } from '@lit-protocol/constants'; + +import { + AccessControlConditions, + ConditionItem, + EvmContractConditions, + JsonSigningResourceId, + SolRpcConditions, + UnifiedAccessControlConditions, +} from '@lit-protocol/types'; + +import { logDebug, throwError } from '@lit-protocol/misc'; +import { + canonicalAccessControlConditionFormatter, + canonicalEVMContractConditionFormatter, + canonicalResourceIdFormatter, + canonicalSolRpcConditionFormatter, + canonicalUnifiedAccessControlConditionFormatter, +} from './canonicalFormatter'; +import { uint8arrayToString } from '@lit-protocol/uint8arrays'; + +/** + * + * Hash the unified access control conditions using SHA-256 in a deterministic way. + * + * @param { UnifiedAccessControlConditions } unifiedAccessControlConditions - The unified access control conditions to hash. + * @returns { Promise } A promise that resolves to an ArrayBuffer that contains the hash + */ +export const hashUnifiedAccessControlConditions = ( + unifiedAccessControlConditions: UnifiedAccessControlConditions +): Promise => { + logDebug('unifiedAccessControlConditions:', unifiedAccessControlConditions); + + const conditions = unifiedAccessControlConditions.map( + (condition: ConditionItem) => { + return canonicalUnifiedAccessControlConditionFormatter(condition); + } + ); + logDebug('conditions:', conditions); + + // check if there's any undefined in the conditions + const hasUndefined = conditions.some((c) => c === undefined); + if (hasUndefined) { + throwError({ + message: 'Invalid access control conditions', + errorKind: LIT_ERROR.INVALID_ACCESS_CONTROL_CONDITIONS.kind, + errorCode: LIT_ERROR.INVALID_ACCESS_CONTROL_CONDITIONS.name, + }); + } + + if (conditions.length === 0) { + throwError({ + message: 'No conditions provided', + errorKind: LIT_ERROR.INVALID_ACCESS_CONTROL_CONDITIONS.kind, + errorCode: LIT_ERROR.INVALID_ACCESS_CONTROL_CONDITIONS.name, + }); + } + const toHash = JSON.stringify(conditions); + + logDebug('Hashing unified access control conditions: ', toHash); + + const encoder = new TextEncoder(); + const data = encoder.encode(toHash); + return crypto.subtle.digest('SHA-256', data); +}; + +/** + * + * Hash resource id + * + * @param { JsonSigningResourceId } resourceId + * + * @returns { Promise } + * + */ +export const hashResourceId = ( + resourceId: JsonSigningResourceId +): Promise => { + const resId = canonicalResourceIdFormatter(resourceId); + const toHash = JSON.stringify(resId); + const encoder = new TextEncoder(); + const data = encoder.encode(toHash); + + return crypto.subtle.digest('SHA-256', data); +}; + +/** + * + * Hash resourceId for signing + * + * @param { JSONSigningResourceId } resourceId + * + * @returns { string } example: "5b36d72f2145af3617e5da2a8a626f9f42e64ed14340622bdfe1a6f0702b9e8d" + */ +export const hashResourceIdForSigning = async ( + resourceId: JsonSigningResourceId +): Promise => { + const hashed = await hashResourceId(resourceId); + return uint8arrayToString(new Uint8Array(hashed), 'base16'); +}; + +/** + * + * Hash access control conditions + * + * @param { AccessControlConditions } accessControlConditions + * + * @returns { Promise } example: {"data": [83, 176, 31, 130, 12, 130, 232, 109, 126, 76, 216, 4, 184, 166, 246, 134, 130, 34, 30, 235, 125, 247, 111, 212, 62, 231, 119, 200, 202, 171, 86, 40], "type": "Buffer"} + * + */ +export const hashAccessControlConditions = ( + accessControlConditions: AccessControlConditions +): Promise => { + const conds = accessControlConditions.map((c) => + canonicalAccessControlConditionFormatter(c) + ); + + const toHash = JSON.stringify(conds); + logDebug('Hashing access control conditions: ', toHash); + const encoder = new TextEncoder(); + const data = encoder.encode(toHash); + + return crypto.subtle.digest('SHA-256', data); +}; + +/** + * + * Hash EVM access control conditions + * + * @param { EvmContractConditions } evmContractConditions + * + * @returns { Promise } {"data": [216, 92, 128, 31, 171, 114, 74, 115, 133, 44, 234, 171, 214, 205, 228, 137, 117, 238, 14, 229, 254, 239, 97, 126, 1, 20, 166, 144, 176, 147, 217, 32], "type": "Buffer"} + * + */ +export const hashEVMContractConditions = ( + evmContractConditions: EvmContractConditions +): Promise => { + const conds = evmContractConditions.map((c) => + canonicalEVMContractConditionFormatter(c) + ); + + const toHash = JSON.stringify(conds); + logDebug('Hashing evm contract conditions: ', toHash); + const encoder = new TextEncoder(); + const data = encoder.encode(toHash); + return crypto.subtle.digest('SHA-256', data); +}; + +/** + * + * Hash SOL access control conditions + * + * @param { SolRpcConditions } solRpcConditions + * + * @returns { Promise } + * + */ +export const hashSolRpcConditions = ( + solRpcConditions: SolRpcConditions +): Promise => { + const conds = solRpcConditions.map((c: any) => + canonicalSolRpcConditionFormatter(c) + ); + + const toHash = JSON.stringify(conds); + logDebug('Hashing sol rpc conditions: ', toHash); + const encoder = new TextEncoder(); + const data = encoder.encode(toHash); + + return crypto.subtle.digest('SHA-256', data); +}; From 2aad0b331bf3859be495b19c899274523df3e590 Mon Sep 17 00:00:00 2001 From: Josh Long Date: Sat, 27 Jan 2024 08:51:11 -0500 Subject: [PATCH 10/11] fix from upstream merge --- README.md | 62 +- apps/html/index.html | 529 +++++++++++++++++- apps/nodejs/main.ts | 14 + apps/react/src/app/app.tsx | 520 ++++++++++++++++- lit.config.json | 26 +- .../access-control-conditions/package.json | 2 +- packages/auth-browser/package.json | 2 +- packages/auth-helpers/package.json | 2 +- packages/bls-sdk/package.json | 2 +- packages/constants/package.json | 2 +- .../src/lib/constants/autogen_internal.ts | 4 +- packages/contracts-sdk/package.json | 2 +- packages/contracts-sdk/src/abis/types.d.ts | 22 +- .../contracts-sdk/src/lib/contracts-sdk.ts | 399 ++----------- packages/core/package.json | 2 +- packages/core/src/lib/lit-core.ts | 18 +- packages/crypto/package.json | 2 +- packages/ecdsa-sdk/package.json | 2 +- packages/encryption/package.json | 2 +- packages/lit-auth-client/package.json | 6 +- .../src/lib/lit-node-client-nodejs.ts | 37 +- packages/lit-node-client/src/lib/hashing.ts | 171 ------ packages/logger/package.json | 6 +- packages/pkp-base/package.json | 6 +- packages/pkp-base/src/lib/pkp-base.ts | 12 +- packages/pkp-client/package.json | 6 +- packages/pkp-cosmos/package.json | 6 +- packages/pkp-cosmos/src/lib/pkp-cosmos.ts | 2 +- packages/pkp-ethers/src/lib/pkp-ethers.ts | 41 +- packages/pkp-sui/package.json | 6 +- packages/pkp-walletconnect/package.json | 6 +- tsconfig.json | 17 +- 32 files changed, 1268 insertions(+), 668 deletions(-) delete mode 100644 packages/lit-node-client/src/lib/hashing.ts diff --git a/README.md b/README.md index aaf4d41df0..7b86256552 100644 --- a/README.md +++ b/README.md @@ -67,39 +67,41 @@ For usage directly in the browser with a script tag -| Package | Category | Version | Download | -| -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [@lit-protocol/lit-node-client-nodejs](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-node-client-nodejs) | ![lit-node-client-nodejs](https://img.shields.io/badge/-nodejs-2E8B57 'lit-node-client-nodejs') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/lit-node-client](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-node-client) | ![lit-node-client](https://img.shields.io/badge/-universal-8A6496 'lit-node-client') | 3.1.0 | npm
Vanilla JS (UMD) | +Package | Category | Version | Download +--- | --- | --- | --- +| [@lit-protocol/lit-node-client-nodejs](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-node-client-nodejs) | ![lit-node-client-nodejs](https://img.shields.io/badge/-nodejs-2E8B57 "lit-node-client-nodejs") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/lit-node-client](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-node-client) | ![lit-node-client](https://img.shields.io/badge/-universal-8A6496 "lit-node-client") | 3.1.0 | npm
Vanilla JS (UMD) + 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 | Version | Download | -| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [@lit-protocol/access-control-conditions](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/access-control-conditions) | ![access-control-conditions](https://img.shields.io/badge/-universal-8A6496 'access-control-conditions') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/auth-helpers](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/auth-helpers) | ![auth-helpers](https://img.shields.io/badge/-universal-8A6496 'auth-helpers') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/bls-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/bls-sdk) | ![bls-sdk](https://img.shields.io/badge/-universal-8A6496 'bls-sdk') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/constants](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/constants) | ![constants](https://img.shields.io/badge/-universal-8A6496 'constants') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/contracts-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/contracts-sdk) | ![contracts-sdk](https://img.shields.io/badge/-universal-8A6496 'contracts-sdk') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/core](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/core) | ![core](https://img.shields.io/badge/-universal-8A6496 'core') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/crypto](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/crypto) | ![crypto](https://img.shields.io/badge/-universal-8A6496 'crypto') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/ecdsa-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/ecdsa-sdk) | ![ecdsa-sdk](https://img.shields.io/badge/-universal-8A6496 'ecdsa-sdk') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/encryption](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/encryption) | ![encryption](https://img.shields.io/badge/-universal-8A6496 'encryption') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/lit-third-party-libs](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-third-party-libs) | ![lit-third-party-libs](https://img.shields.io/badge/-universal-8A6496 'lit-third-party-libs') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/logger](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/logger) | ![logger](https://img.shields.io/badge/-universal-8A6496 'logger') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/misc](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/misc) | ![misc](https://img.shields.io/badge/-universal-8A6496 'misc') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/nacl](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/nacl) | ![nacl](https://img.shields.io/badge/-universal-8A6496 'nacl') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-base](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-base) | ![pkp-base](https://img.shields.io/badge/-universal-8A6496 'pkp-base') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-client](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-client) | ![pkp-client](https://img.shields.io/badge/-universal-8A6496 'pkp-client') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-cosmos](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-cosmos) | ![pkp-cosmos](https://img.shields.io/badge/-universal-8A6496 'pkp-cosmos') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-ethers](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-ethers) | ![pkp-ethers](https://img.shields.io/badge/-universal-8A6496 'pkp-ethers') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-sui](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-sui) | ![pkp-sui](https://img.shields.io/badge/-universal-8A6496 'pkp-sui') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/pkp-walletconnect](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-walletconnect) | ![pkp-walletconnect](https://img.shields.io/badge/-universal-8A6496 'pkp-walletconnect') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/sev-snp-utils-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/sev-snp-utils-sdk) | ![sev-snp-utils-sdk](https://img.shields.io/badge/-universal-8A6496 'sev-snp-utils-sdk') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/types](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/types) | ![types](https://img.shields.io/badge/-universal-8A6496 'types') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/uint8arrays](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/uint8arrays) | ![uint8arrays](https://img.shields.io/badge/-universal-8A6496 'uint8arrays') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/auth-browser](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/auth-browser) | ![auth-browser](https://img.shields.io/badge/-browser-E98869 'auth-browser') | 3.1.0 | npm
Vanilla JS (UMD) | -| [@lit-protocol/misc-browser](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/misc-browser) | ![misc-browser](https://img.shields.io/badge/-browser-E98869 'misc-browser') | 3.1.0 | npm
Vanilla JS (UMD) | + +Package | Category | Version | Download +--- | --- | --- | --- +| [@lit-protocol/access-control-conditions](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/access-control-conditions) | ![access-control-conditions](https://img.shields.io/badge/-universal-8A6496 "access-control-conditions") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/auth-helpers](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/auth-helpers) | ![auth-helpers](https://img.shields.io/badge/-universal-8A6496 "auth-helpers") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/bls-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/bls-sdk) | ![bls-sdk](https://img.shields.io/badge/-universal-8A6496 "bls-sdk") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/constants](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/constants) | ![constants](https://img.shields.io/badge/-universal-8A6496 "constants") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/contracts-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/contracts-sdk) | ![contracts-sdk](https://img.shields.io/badge/-universal-8A6496 "contracts-sdk") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/core](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/core) | ![core](https://img.shields.io/badge/-universal-8A6496 "core") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/crypto](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/crypto) | ![crypto](https://img.shields.io/badge/-universal-8A6496 "crypto") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/ecdsa-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/ecdsa-sdk) | ![ecdsa-sdk](https://img.shields.io/badge/-universal-8A6496 "ecdsa-sdk") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/encryption](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/encryption) | ![encryption](https://img.shields.io/badge/-universal-8A6496 "encryption") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/lit-third-party-libs](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/lit-third-party-libs) | ![lit-third-party-libs](https://img.shields.io/badge/-universal-8A6496 "lit-third-party-libs") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/logger](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/logger) | ![logger](https://img.shields.io/badge/-universal-8A6496 "logger") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/misc](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/misc) | ![misc](https://img.shields.io/badge/-universal-8A6496 "misc") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/nacl](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/nacl) | ![nacl](https://img.shields.io/badge/-universal-8A6496 "nacl") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-base](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-base) | ![pkp-base](https://img.shields.io/badge/-universal-8A6496 "pkp-base") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-client](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-client) | ![pkp-client](https://img.shields.io/badge/-universal-8A6496 "pkp-client") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-cosmos](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-cosmos) | ![pkp-cosmos](https://img.shields.io/badge/-universal-8A6496 "pkp-cosmos") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-ethers](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-ethers) | ![pkp-ethers](https://img.shields.io/badge/-universal-8A6496 "pkp-ethers") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-sui](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-sui) | ![pkp-sui](https://img.shields.io/badge/-universal-8A6496 "pkp-sui") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/pkp-walletconnect](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-walletconnect) | ![pkp-walletconnect](https://img.shields.io/badge/-universal-8A6496 "pkp-walletconnect") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/sev-snp-utils-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/sev-snp-utils-sdk) | ![sev-snp-utils-sdk](https://img.shields.io/badge/-universal-8A6496 "sev-snp-utils-sdk") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/types](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/types) | ![types](https://img.shields.io/badge/-universal-8A6496 "types") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/uint8arrays](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/uint8arrays) | ![uint8arrays](https://img.shields.io/badge/-universal-8A6496 "uint8arrays") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/auth-browser](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/auth-browser) | ![auth-browser](https://img.shields.io/badge/-browser-E98869 "auth-browser") | 3.1.0 | npm
Vanilla JS (UMD) +| [@lit-protocol/misc-browser](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/misc-browser) | ![misc-browser](https://img.shields.io/badge/-browser-E98869 "misc-browser") | 3.1.0 | npm
Vanilla JS (UMD) diff --git a/apps/html/index.html b/apps/html/index.html index 3103aba621..579c76fa1c 100644 --- a/apps/html/index.html +++ b/apps/html/index.html @@ -1,4 +1,4 @@ - + @@ -62,7 +62,7 @@ - (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Fri, 26 Jan 2024 19:51:34 GMT + (HTML) THIS FILE IS AUTOMATICALLY GENERATED FROM tools/scripts/gen-html.mjs Sat, 27 Jan 2024 13:48:38 GMT @@ -76,10 +76,17 @@ + + + + + + + @@ -878,7 +885,79 @@

LitJsSdk_litNodeClientNodejs has ${entries.length} functions

- + + + + + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + - + - +