diff --git a/README.md b/README.md
index e8f6c1cda1..3817ef63bf 100644
--- a/README.md
+++ b/README.md
@@ -65,11 +65,7 @@ If you're a tech-savvy user and wish to utilize only specific submodules that ou
| [@lit-protocol/contracts-sdk](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/contracts-sdk) |  |
|
| [@lit-protocol/core](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/core) |  |
|
| [@lit-protocol/crypto](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/crypto) |  |
|
-| [@lit-protocol/encryption](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/encryption) |  |
|
| [@lit-protocol/event-listener](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/event-listener) |  |
|
-| [@lit-protocol/logger](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/logger) |  |
|
-| [@lit-protocol/misc](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/misc) |  |
|
-| [@lit-protocol/nacl](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/nacl) |  |
|
| [@lit-protocol/networks](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/networks) |  |
|
| [@lit-protocol/pkp-base](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-base) |  |
|
| [@lit-protocol/pkp-cosmos](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-cosmos) |  |
|
@@ -77,7 +73,6 @@ If you're a tech-savvy user and wish to utilize only specific submodules that ou
| [@lit-protocol/pkp-sui](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-sui) |  |
|
| [@lit-protocol/pkp-walletconnect](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/pkp-walletconnect) |  |
|
| [@lit-protocol/types](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/types) |  |
|
-| [@lit-protocol/uint8arrays](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/uint8arrays) |  |
|
| [@lit-protocol/wasm](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/wasm) |  |
|
| [@lit-protocol/wrapped-keys](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/wrapped-keys) |  |
|
| [@lit-protocol/wrapped-keys-lit-actions](https://github.com/LIT-Protocol/js-sdk/tree/master/packages/wrapped-keys-lit-actions) |  |
|
@@ -100,7 +95,7 @@ If you're a tech-savvy user and wish to utilize only specific submodules that ou
## Prerequisite
-- node (v19.x or above)
+- node (v20.x or above)
- rust (v1.70.00 or above)
- [wasm-pack](https://github.com/rustwasm/wasm-pack)
diff --git a/jest.setup.js b/jest.setup.js
index 009e7cb71e..d2f1c82f82 100644
--- a/jest.setup.js
+++ b/jest.setup.js
@@ -4,6 +4,17 @@ global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
global.crypto = crypto;
+if (!global.crypto.subtle) {
+ global.crypto.subtle = {
+ digest: async (algorithm, data) => {
+ const algo = algorithm.toLowerCase().replace('-', '');
+ const hash = crypto.createHash(algo);
+ hash.update(Buffer.from(data));
+ return hash.digest().buffer;
+ },
+ };
+}
+
// If this is not included, you will get the following error when running it in Jest:
// (Error) Details: Request is not defined
// The problem is that Jest is running in a Node.js environment where the global Request API (part of the Fetch API) might not be available or properly configured. Bun, on the other hand, has this API built into its runtime by default, which is why it works.
diff --git a/local-tests/package.json b/local-tests/package.json
index 6942e625b2..da3ef632ae 100644
--- a/local-tests/package.json
+++ b/local-tests/package.json
@@ -81,14 +81,12 @@
"synthetix-js": "^2.74.1",
"tslib": "^2.3.0",
"tweetnacl": "^1.0.3",
- "tweetnacl-util": "^0.15.1",
"uint8arrays": "^4.0.3",
"@openagenda/verror": "^3.1.4",
"ipfs-unixfs-importer": "12.0.1",
"@solana/web3.js": "^1.95.3",
"bech32": "^2.0.0",
"pako": "^2.1.0",
- "@lit-protocol/misc": "8.0.0-alpha.0",
"@lit-protocol/lit-node-client": "8.0.0-alpha.0",
"@lit-protocol/auth": "8.0.0-alpha.0",
"@lit-protocol/contracts": "^0.0.71"
diff --git a/local-tests/setup/session-sigs/get-eoa-session-sigs.ts b/local-tests/setup/session-sigs/get-eoa-session-sigs.ts
index 3e54717b58..f6eb049974 100644
--- a/local-tests/setup/session-sigs/get-eoa-session-sigs.ts
+++ b/local-tests/setup/session-sigs/get-eoa-session-sigs.ts
@@ -9,7 +9,6 @@ import {
AuthSig,
LitResourceAbilityRequest,
} from '@lit-protocol/types';
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import {
LIT_ABILITY,
diff --git a/local-tests/setup/session-sigs/get-pkp-session-sigs.ts b/local-tests/setup/session-sigs/get-pkp-session-sigs.ts
index ae4fb06dca..5e1152242f 100644
--- a/local-tests/setup/session-sigs/get-pkp-session-sigs.ts
+++ b/local-tests/setup/session-sigs/get-pkp-session-sigs.ts
@@ -3,7 +3,6 @@ import {
type AuthenticationContext,
LitResourceAbilityRequest,
} from '@lit-protocol/types';
-import { log } from '@lit-protocol/misc';
import {
LIT_ABILITY,
CENTRALISATION_BY_NETWORK,
@@ -43,7 +42,7 @@ export const getPkpAuthContext = (
}),
});
- log('[getPkpAuthContext]: ', authContext);
+ console.log('[getPkpAuthContext]: ', authContext);
return authContext;
};
diff --git a/local-tests/setup/tinny-environment.ts b/local-tests/setup/tinny-environment.ts
index 0891664665..c38e5851f6 100644
--- a/local-tests/setup/tinny-environment.ts
+++ b/local-tests/setup/tinny-environment.ts
@@ -1,5 +1,6 @@
import { LitContracts } from '@lit-protocol/contracts-sdk';
import { LitNodeClient } from '@lit-protocol/lit-node-client';
+import { getChildLogger } from '@lit-protocol/logger';
import {
AuthSig,
LitContractContext,
@@ -8,7 +9,6 @@ import {
import { ProcessEnvs, TinnyEnvConfig } from './tinny-config';
import { TinnyPerson } from './tinny-person';
-import { createSiweMessage, generateAuthSig } from '@lit-protocol/auth-helpers';
import {
CENTRALISATION_BY_NETWORK,
LIT_NETWORK,
@@ -20,7 +20,9 @@ import { ethers, Signer } from 'ethers';
import { ShivaClient, TestnetClient } from './shiva-client';
import { toErrorWithMessage } from './tinny-utils';
-console.log('checking env', process.env['DEBUG']);
+const logger = getChildLogger({ module: 'tinny-environment' });
+
+logger.info({ msg: 'checking env', env: process.env['DEBUG'] });
const DEFAULT_ANVIL_PRIVATE_KEYS = [
'0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
@@ -49,7 +51,7 @@ export class TinnyEnvironment {
DEBUG: process.env['DEBUG'] === 'true',
REQUEST_PER_KILOSECOND:
parseInt(process.env['REQUEST_PER_KILOSECOND']) ||
- (process.env['NETWORK'] as LIT_NETWORK_VALUES) === 'datil-dev'
+ (process.env['NETWORK'] as LIT_NETWORK_VALUES) === LIT_NETWORK.NagaDev
? 1
: 200,
LIT_RPC_URL: process.env['LIT_RPC_URL'],
@@ -147,10 +149,10 @@ export class TinnyEnvironment {
);
}
- console.log(
- '[𐬺🧪 Tinny Environment𐬺] Done configuring environment current config: ',
- this.processEnvs
- );
+ logger.info({
+ msg: '[𐬺🧪 Tinny Environment𐬺] Done configuring environment current config: ',
+ processEnvs: this.processEnvs,
+ });
}
world: Map = new Map();
@@ -183,11 +185,12 @@ export class TinnyEnvironment {
if (index !== -1) {
// If an available key is found
this.processEnvs.KEY_IN_USE[index] = true; // Mark the key as in use
- // console.log('[𐬺🧪 Tinny Environment𐬺] 🔑 Selected key at index', index); // Log a message indicating that we have selected a key
+ // logger.info({ msg: '[𐬺🧪 Tinny Environment𐬺] 🔑 Selected key at index', index }); // Log a message indicating that we have selected a key
return { privateKey: this.processEnvs.PRIVATE_KEYS[index], index }; // Return the key and its index
} else {
- console.log('[𐬺🧪 Tinny Environment𐬺] No available keys. Waiting...', {
+ logger.info({
+ msg: '[𐬺🧪 Tinny Environment𐬺] No available keys. Waiting...',
keysInUse: this.processEnvs.KEY_IN_USE,
}); // Log a message indicating that we are waiting
// Wait for the specified interval before checking again
@@ -205,9 +208,9 @@ export class TinnyEnvironment {
releasePrivateKeyFromUser(user: TinnyPerson) {
const index = this.processEnvs.PRIVATE_KEYS.indexOf(user.privateKey);
this.processEnvs.KEY_IN_USE[index] = false;
- // console.log(
- // `[𐬺🧪 Tinny Environment𐬺] 🪽 Released key at index ${index}. Thank you for your service!`
- // );
+ // logger.info({
+ // msg: `[𐬺🧪 Tinny Environment𐬺] 🪽 Released key at index ${index}. Thank you for your service!`
+ // });
}
/**
@@ -216,9 +219,9 @@ export class TinnyEnvironment {
*/
releasePrivateKey(index: number) {
this.processEnvs.KEY_IN_USE[index] = false;
- // console.log(
- // `[𐬺🧪 Tinny Environment𐬺] 🪽 Released key at index ${index}. Thank you for your service!`
- // );
+ // logger.info({
+ // msg: `[𐬺🧪 Tinny Environment𐬺] 🪽 Released key at index ${index}. Thank you for your service!`
+ // });
}
/**
@@ -234,9 +237,9 @@ export class TinnyEnvironment {
*/
async setupLitNodeClient() {
- console.log('[𐬺🧪 Tinny Environment𐬺] Setting up LitNodeClient');
+ logger.info({ msg: '[𐬺🧪 Tinny Environment𐬺] Setting up LitNodeClient' });
- console.log('this.network:', this.network);
+ logger.info({ msg: 'network', network: this.network });
const centralisation = CENTRALISATION_BY_NETWORK[this.network];
if (this.network === LIT_NETWORK.Custom || centralisation === 'unknown') {
@@ -324,7 +327,7 @@ export class TinnyEnvironment {
* @throws Error if the name is not provided.
*/
async createNewPerson(name: string) {
- console.log('[𐬺🧪 Tinny Environment𐬺] Creating new person:', name);
+ logger.info({ msg: '[𐬺🧪 Tinny Environment𐬺] Creating new person', name });
if (!name) {
throw new Error('Name is required');
}
@@ -373,7 +376,7 @@ export class TinnyEnvironment {
async init() {
try {
if (this.processEnvs.NO_SETUP) {
- console.log('[𐬺🧪 Tinny Environment𐬺] Skipping setup');
+ logger.info({ msg: '[𐬺🧪 Tinny Environment𐬺] Skipping setup' });
return;
}
if (this.network === LIT_NETWORK.Custom && this.processEnvs.USE_SHIVA) {
@@ -381,9 +384,9 @@ export class TinnyEnvironment {
// wait for the testnet to be active before we start the tests.
let state = await this.testnet.pollTestnetForActive();
if (state === `UNKNOWN`) {
- console.log(
- 'Testnet state found to be Unknown meaning there was an error with testnet creation. shutting down'
- );
+ logger.info({
+ msg: 'Testnet state found to be Unknown meaning there was an error with testnet creation. shutting down',
+ });
throw new Error(`Error while creating testnet, aborting test run`);
}
@@ -398,10 +401,10 @@ export class TinnyEnvironment {
await this.setupSuperCapacityDelegationAuthSig();
} catch (e) {
const err = toErrorWithMessage(e);
- console.log(
- `[𐬺🧪 Tinny Environment𐬺] Failed to init() tinny ${err.message}`
- );
- console.log(err.stack);
+ logger.error({
+ msg: `[𐬺🧪 Tinny Environment𐬺] Failed to init() tinny ${err.message}`,
+ stack: err.stack,
+ });
process.exit(1);
}
}
@@ -417,7 +420,7 @@ export class TinnyEnvironment {
) {
await this.testnet.stopTestnet();
} else {
- console.log('skipping testnet shutdown.');
+ logger.info('skipping testnet shutdown.');
}
}
//============= END SHIVA ENDPOINTS =============
@@ -498,9 +501,9 @@ export class TinnyEnvironment {
// get wallet balance
const balance = await wallet.getBalance();
- console.log('this.rpc:', rpc);
- console.log('this.wallet.address', wallet.address);
- console.log('Balance:', balance.toString());
+ logger.info({ msg: 'this.rpc:', rpc });
+ logger.info({ msg: 'this.wallet.address', address: wallet.address });
+ logger.info({ msg: 'Balance:', balance: balance.toString() });
const transferTx = await wallet.sendTransaction({
to: capacityCreditWallet.address,
@@ -520,7 +523,7 @@ export class TinnyEnvironment {
}
if (!this.contractsClient) {
- console.log('❗️Contracts client not initialized');
+ logger.info('❗️Contracts client not initialized');
process.exit();
}
@@ -537,7 +540,7 @@ export class TinnyEnvironment {
};
async mintSuperCapacityDelegationAuthSig(wallet: Signer) {
- console.log(
+ logger.info(
'[𐬺🧪 Tinny Environment𐬺] Mint a Capacity Credits NFT and get a capacity delegation authSig with it'
);
@@ -552,9 +555,9 @@ export class TinnyEnvironment {
).capacityDelegationAuthSig;
} catch (e: any) {
if (e.message.includes(`Can't allocate capacity beyond the global max`)) {
- console.log('❗️Skipping capacity delegation auth sig setup.', e);
+ logger.info('❗️Skipping capacity delegation auth sig setup.', e);
} else {
- console.log(
+ logger.info(
'❗️Error while setting up capacity delegation auth sig',
e
);
diff --git a/local-tests/setup/tinny-person.ts b/local-tests/setup/tinny-person.ts
index 2555737ba8..1890d59a0e 100644
--- a/local-tests/setup/tinny-person.ts
+++ b/local-tests/setup/tinny-person.ts
@@ -1,11 +1,8 @@
-import {
- AuthSig,
- generateAuthSig,
- createSiweMessage,
-} from '@lit-protocol/auth-helpers';
+import { generateAuthSig, createSiweMessage } from '@lit-protocol/auth-helpers';
import { LitContracts } from '@lit-protocol/contracts-sdk';
import {
AuthMethod,
+ AuthSig,
BaseSiweMessage,
LitContractContext,
} from '@lit-protocol/types';
diff --git a/local-tests/test.ts b/local-tests/test.ts
index cb1a898ec4..f4ef5e7a81 100644
--- a/local-tests/test.ts
+++ b/local-tests/test.ts
@@ -1,293 +1,27 @@
-import { TinnyEnvironment } from './setup/tinny-environment';
-import { runInBand, runTestsParallel } from './setup/tinny-operations';
-
-// import { testBundleSpeed } from './tests/test-bundle-speed';
-// import { testExample } from './tests/test-example';
-
-import { testUseEoaSessionSigsToExecuteJsSigningInParallel } from './tests/testUseEoaSessionSigsToExecuteJsSigningInParallel';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning';
-import { testUseValidLitActionCodeGeneratedSessionSigsToPkpSign } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToPkpSign';
-import { testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning } from './tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning';
-
-import { testUseEoaSessionSigsToEncryptDecryptFile } from './tests/testUseEoaSessionSigsToEncryptDecryptFile';
-import { testUseEoaSessionSigsToEncryptDecryptString } from './tests/testUseEoaSessionSigsToEncryptDecryptString';
-import { testUseEoaSessionSigsToEncryptDecryptUint8Array } from './tests/testUseEoaSessionSigsToEncryptDecryptUint8Array';
-import { testUseEoaSessionSigsToExecuteJsClaimKeys } from './tests/testUseEoaSessionSigsToExecuteJsClaimKeys';
-import { testUseEoaSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseEoaSessionSigsToExecuteJsClaimMultipleKeys';
-import { testUseEoaSessionSigsToExecuteJsConsoleLog } from './tests/testUseEoaSessionSigsToExecuteJsConsoleLog';
-import { testUseEoaSessionSigsToExecuteJsJsonResponse } from './tests/testUseEoaSessionSigsToExecuteJsJsonResponse';
-import { testUseEoaSessionSigsToExecuteJsSigning } from './tests/testUseEoaSessionSigsToExecuteJsSigning';
-import { testUseEoaSessionSigsToPkpSign } from './tests/testUseEoaSessionSigsToPkpSign';
-import { testUseEoaSessionSigsToRequestSingleResponse } from './tests/testUseEoaSessionSigsToRequestSingleResponse';
-
-import { testUseInvalidLitActionCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionCodeToGenerateSessionSigs';
-import { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel';
-
-import { testUsePkpSessionSigsToEncryptDecryptFile } from './tests/testUsePkpSessionSigsToEncryptDecryptFile';
-import { testUsePkpSessionSigsToEncryptDecryptString } from './tests/testUsePkpSessionSigsToEncryptDecryptString';
-import { testUsePkpSessionSigsToExecuteJsClaimKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimKeys';
-import { testUsePkpSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimMultipleKeys';
-import { testUsePkpSessionSigsToExecuteJsConsoleLog } from './tests/testUsePkpSessionSigsToExecuteJsConsoleLog';
-import { testUsePkpSessionSigsToExecuteJsJsonResponse } from './tests/testUsePkpSessionSigsToExecuteJsJsonResponse';
-import { testUsePkpSessionSigsToExecuteJsSigning } from './tests/testUsePkpSessionSigsToExecuteJsSigning';
-import { testUsePkpSessionSigsToExecuteJsSigningInParallel } from './tests/testUsePkpSessionSigsToExecuteJsSigningInParallel';
-import { testUsePkpSessionSigsToPkpSign } from './tests/testUsePkpSessionSigsToPkpSign';
-
-import { testUseInvalidLitActionIpfsCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionIpfsCodeToGenerateSessionSigs';
-import { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog';
-import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse';
-import { testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign } from './tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign';
-import { testPkpEthersWithEoaSessionSigsToEthSign } from './tests/testPkpEthersWithEoaSessionSigsToEthSign';
-import { testPkpEthersWithEoaSessionSigsToEthSignTransaction } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTransaction';
-import { testPkpEthersWithEoaSessionSigsToPersonalSign } from './tests/testPkpEthersWithEoaSessionSigsToPersonalSign';
-import { testPkpEthersWithEoaSessionSigsToSendTx } from './tests/testPkpEthersWithEoaSessionSigsToSendTx';
-import { testPkpEthersWithEoaSessionSigsToSignMessage } from './tests/testPkpEthersWithEoaSessionSigsToSignMessage';
-import { testPkpEthersWithEoaSessionSigsToSignWithAuthContext } from './tests/testPkpEthersWithEoaSessionSigsToSignWithAuthContext';
-import { testPkpEthersWithPkpSessionSigsToEthSign } from './tests/testPkpEthersWithPkpSessionSigsToEthSign';
-import { testPkpEthersWithPkpSessionSigsToPersonalSign } from './tests/testPkpEthersWithPkpSessionSigsToPersonalSign';
-import { testPkpEthersWithPkpSessionSigsToSendTx } from './tests/testPkpEthersWithPkpSessionSigsToSendTx';
-import { testPkpEthersWithPkpSessionSigsToSignMessage } from './tests/testPkpEthersWithPkpSessionSigsToSignMessage';
-
-import { testPkpEthersWithEoaSessionSigsToEthSignTypedData } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTypedData';
-import { testPkpEthersWithEoaSessionSigsToEthSignTypedDataUtil } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTypedDataUtil';
-import { testPkpEthersWithEoaSessionSigsToEthSignTypedDataV1 } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTypedDataV1';
-import { testPkpEthersWithEoaSessionSigsToEthSignTypedDataV3 } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTypedDataV3';
-import { testPkpEthersWithEoaSessionSigsToEthSignTypedDataV4 } from './tests/testPkpEthersWithEoaSessionSigsToEthSignTypedDataV4';
-import { testPkpEthersWithLitActionSessionSigsToEthSign } from './tests/testPkpEthersWithLitActionSessionSigsToEthSign';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTransaction } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTransaction';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTypedData } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedData';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV1 } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV1';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV3 } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV3';
-import { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV4 } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV4';
-import { testPkpEthersWithLitActionSessionSigsToPersonalSign } from './tests/testPkpEthersWithLitActionSessionSigsToPersonalSign';
-import { testPkpEthersWithLitActionSessionSigsToSendTx } from './tests/testPkpEthersWithLitActionSessionSigsToSendTx';
-import { testPkpEthersWithLitActionSessionSigsToSignMessage } from './tests/testPkpEthersWithLitActionSessionSigsToSignMessage';
-import { testPkpEthersWithPkpSessionSigsToEthSignTransaction } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTransaction';
-import { testPkpEthersWithPkpSessionSigsToEthSignTypedData } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTypedData';
-import { testPkpEthersWithPkpSessionSigsToEthSignTypedDataUtil } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTypedDataUtil';
-import { testPkpEthersWithPkpSessionSigsToEthSignTypedDataV1 } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTypedDataV1';
-import { testPkpEthersWithPkpSessionSigsToEthSignTypedDataV3 } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTypedDataV3';
-import { testPkpEthersWithPkpSessionSigsToEthSignTypedDataV4 } from './tests/testPkpEthersWithPkpSessionSigsToEthSignTypedDataV4';
-
-import { testUseCustomAuthSessionSigsToPkpSignExecuteJs } from './tests/testUseCustomAuthSessionSigsToPkpSignExecuteJs';
+import { setLoggerOptions, logger } from '@lit-protocol/logger';
-import { testExecuteJsBroadcastAndCollect } from './tests/testExecuteJsBroadcastAndCollect';
-import { testExecuteJsDecryptAndCombine } from './tests/testExecuteJsDecryptAndCombine';
-import { testExecuteJsSignAndCombineEcdsa } from './tests/testExecuteJsSignAndCombineEcdsa';
-import { testRelayer } from './tests/testRelayer';
-
-// import { testEthereumSignMessageGeneratedKey } from './tests/wrapped-keys/testEthereumSignMessageGeneratedKey';
-// import { testEthereumBroadcastTransactionGeneratedKey } from './tests/wrapped-keys/testEthereumBroadcastTransactionGeneratedKey';
-// import { testEthereumSignMessageWrappedKey } from './tests/wrapped-keys/testEthereumSignMessageWrappedKey';
-// import { testFailEthereumSignTransactionWrappedKeyInvalidDecryption } from './tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyInvalidDecryption';
-// import { testEthereumSignTransactionWrappedKey } from './tests/wrapped-keys/testEthereumSignTransactionWrappedKey';
-// import { testFailEthereumSignTransactionWrappedKeyWithInvalidParam } from './tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithInvalidParam';
-// import { testFailEthereumSignTransactionWrappedKeyWithMissingParam } from './tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithMissingParam';
-// import { testEthereumBroadcastTransactionWrappedKey } from './tests/wrapped-keys/testEthereumBroadcastTransactionWrappedKey';
-// import { testEthereumBroadcastWrappedKeyWithFetchGasParams } from './tests/wrapped-keys/testEthereumBroadcastWrappedKeyWithFetchGasParams';
-// import { testImportWrappedKey } from './tests/wrapped-keys/testImportWrappedKey';
-// import { testGenerateEthereumWrappedKey } from './tests/wrapped-keys/testGenerateEthereumWrappedKey';
-// import { testGenerateSolanaWrappedKey } from './tests/wrapped-keys/testGenerateSolanaWrappedKey';
-// import { testFailImportWrappedKeysWithSamePrivateKey } from './tests/wrapped-keys/testFailImportWrappedKeysWithSamePrivateKey';
-// import { testFailImportWrappedKeysWithEoaSessionSig } from './tests/wrapped-keys/testFailImportWrappedKeysWithEoaSessionSig';
-// import { testFailImportWrappedKeysWithMaxExpirySessionSig } from './tests/wrapped-keys/testFailImportWrappedKeysWithMaxExpirySessionSig';
-// import { testFailImportWrappedKeysWithInvalidSessionSig } from './tests/wrapped-keys/testFailImportWrappedKeysWithInvalidSessionSig';
-// import { testFailImportWrappedKeysWithExpiredSessionSig } from './tests/wrapped-keys/testFailImportWrappedKeysWithExpiredSessionSig';
-// import { testExportWrappedKey } from './tests/wrapped-keys/testExportWrappedKey';
-// import { testSignMessageWithSolanaEncryptedKey } from './tests/wrapped-keys/testSignMessageWithSolanaEncryptedKey';
-// import { testSignTransactionWithSolanaEncryptedKey } from './tests/wrapped-keys/testSignTransactionWithSolanaEncryptedKey';
-// import { testBatchGeneratePrivateKeys } from './tests/wrapped-keys/testBatchGeneratePrivateKeys';
-// import { testFailBatchGeneratePrivateKeysAtomic } from './tests/wrapped-keys/testFailStoreEncryptedKeyBatchIsAtomic';
+setLoggerOptions({
+ transport: {
+ target: 'pino-pretty',
+ },
+});
+import { TinnyEnvironment } from './setup/tinny-environment';
+import { runInBand, runTestsParallel } from './setup/tinny-operations';
+import { tinnyTests } from './tests';
import { setLitActionsCodeToLocal } from './tests/wrapped-keys/util';
// Use the current LIT action code to test against
setLitActionsCodeToLocal();
(async () => {
- console.log('[𐬺🧪 Tinny𐬺] Running tests...');
+ logger.info({ msg: '[𐬺🧪 Tinny𐬺] Running tests...' });
const devEnv = new TinnyEnvironment();
await devEnv.init();
- const relayerTests = {
- testRelayer,
- };
-
- // --filter=WrappedKey
- const wrappedKeysTests = {
- // // -- valid cases
- // testBatchGeneratePrivateKeys,
- // testEthereumSignMessageGeneratedKey,
- // testEthereumBroadcastTransactionGeneratedKey,
- // testEthereumSignMessageWrappedKey,
- // testEthereumSignTransactionWrappedKey,
- // testEthereumBroadcastTransactionWrappedKey,
- // testEthereumBroadcastWrappedKeyWithFetchGasParams,
- //
- // // -- generate wrapped keys
- // testGenerateEthereumWrappedKey,
- // testGenerateSolanaWrappedKey,
- //
- // // -- import wrapped keys
- // testImportWrappedKey,
- //
- // // -- export wrapped keys
- // testExportWrappedKey,
- //
- // // -- solana wrapped keys
- // testSignMessageWithSolanaEncryptedKey,
- // testSignTransactionWithSolanaEncryptedKey,
- //
- // // -- invalid cases
- // testFailEthereumSignTransactionWrappedKeyWithMissingParam,
- // testFailEthereumSignTransactionWrappedKeyWithInvalidParam,
- // testFailEthereumSignTransactionWrappedKeyInvalidDecryption,
- // testFailBatchGeneratePrivateKeysAtomic,
- //
- // // -- import wrapped keys
- // testFailImportWrappedKeysWithSamePrivateKey,
- // testFailImportWrappedKeysWithEoaSessionSig,
- // testFailImportWrappedKeysWithMaxExpirySessionSig,
- // testFailImportWrappedKeysWithInvalidSessionSig,
- // testFailImportWrappedKeysWithExpiredSessionSig,
- };
-
- const eoaSessionSigsTests = {
- testUseEoaSessionSigsToExecuteJsSigning,
- testUseEoaSessionSigsToRequestSingleResponse,
- testUseEoaSessionSigsToPkpSign,
- testUseEoaSessionSigsToExecuteJsSigningInParallel,
- testUseEoaSessionSigsToExecuteJsClaimKeys,
- testUseEoaSessionSigsToExecuteJsClaimMultipleKeys,
- testUseEoaSessionSigsToExecuteJsJsonResponse,
- testUseEoaSessionSigsToExecuteJsConsoleLog,
- testUseEoaSessionSigsToEncryptDecryptString,
- testUseEoaSessionSigsToEncryptDecryptUint8Array,
- testUseEoaSessionSigsToEncryptDecryptFile,
- };
-
- const pkpSessionSigsTests = {
- testUsePkpSessionSigsToExecuteJsSigning,
- testUsePkpSessionSigsToPkpSign,
- testUsePkpSessionSigsToExecuteJsSigningInParallel,
- testUsePkpSessionSigsToExecuteJsClaimKeys,
- testUsePkpSessionSigsToExecuteJsClaimMultipleKeys,
- testUsePkpSessionSigsToExecuteJsJsonResponse,
- testUsePkpSessionSigsToExecuteJsConsoleLog,
- testUsePkpSessionSigsToEncryptDecryptString,
- testUsePkpSessionSigsToEncryptDecryptFile,
- };
-
- const litActionSessionSigsTests = {
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning,
- testUseValidLitActionCodeGeneratedSessionSigsToPkpSign,
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel,
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys,
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys,
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse,
- testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog,
- testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString,
- testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile,
-
- // -- invalid cases
- testUseInvalidLitActionIpfsCodeToGenerateSessionSigs,
-
- // -- custom auth methods
- testUseCustomAuthSessionSigsToPkpSignExecuteJs,
- };
-
- const litActionIpfsIdSessionSigsTests = {
- testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign,
- testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning,
-
- // -- invalid cases
- testUseInvalidLitActionCodeToGenerateSessionSigs,
- };
-
- const eip1271AuthSigTests = {
- // testKeccakEip1271AuthSigToEncryptDecryptString,
- // testShaEip1271AuthSigToEncryptDecryptString,
- };
-
- const pkpEthersTest = {
- eoaSessionSigs: {
- testPkpEthersWithEoaSessionSigsToSignWithAuthContext,
- testPkpEthersWithEoaSessionSigsToSignMessage,
- testPkpEthersWithEoaSessionSigsToEthSign,
- testPkpEthersWithEoaSessionSigsToPersonalSign,
- testPkpEthersWithEoaSessionSigsToSendTx,
- testPkpEthersWithEoaSessionSigsToEthSignTransaction,
- testPkpEthersWithEoaSessionSigsToEthSignTypedDataV1,
- testPkpEthersWithEoaSessionSigsToEthSignTypedDataV3,
- testPkpEthersWithEoaSessionSigsToEthSignTypedDataV4,
- testPkpEthersWithEoaSessionSigsToEthSignTypedData,
- testPkpEthersWithEoaSessionSigsToEthSignTypedDataUtil,
- },
- pkpSessionSigs: {
- testPkpEthersWithPkpSessionSigsToSignMessage,
- testPkpEthersWithPkpSessionSigsToEthSign,
- testPkpEthersWithPkpSessionSigsToPersonalSign,
- testPkpEthersWithPkpSessionSigsToSendTx,
- testPkpEthersWithPkpSessionSigsToEthSignTransaction,
- testPkpEthersWithPkpSessionSigsToEthSignTypedDataV1,
- testPkpEthersWithPkpSessionSigsToEthSignTypedDataV3,
- testPkpEthersWithPkpSessionSigsToEthSignTypedDataV4,
- testPkpEthersWithPkpSessionSigsToEthSignTypedData,
- testPkpEthersWithPkpSessionSigsToEthSignTypedDataUtil,
- },
- litActionSessionSigs: {
- testPkpEthersWithLitActionSessionSigsToSignMessage,
- testPkpEthersWithLitActionSessionSigsToEthSign,
- testPkpEthersWithLitActionSessionSigsToPersonalSign,
- testPkpEthersWithLitActionSessionSigsToSendTx,
- testPkpEthersWithLitActionSessionSigsToEthSignTransaction,
- testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV1,
- testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV3,
- testPkpEthersWithLitActionSessionSigsToEthSignTypedDataV4,
- testPkpEthersWithLitActionSessionSigsToEthSignTypedData,
- testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil,
- },
- };
-
- const litActionCombiningTests = {
- ecdsaSignAndCombine: {
- testExecuteJsSignAndCombineEcdsa,
- },
- decryptAndCombine: {
- testExecuteJsDecryptAndCombine,
- },
- broadcastAndCombine: {
- testExecuteJsBroadcastAndCollect,
- },
- };
-
const testConfig = {
- tests: {
- // testExample,
- // testBundleSpeed,
- ...eoaSessionSigsTests,
- ...pkpSessionSigsTests,
- ...litActionSessionSigsTests,
- ...litActionIpfsIdSessionSigsTests,
- ...eip1271AuthSigTests,
-
- ...pkpEthersTest.eoaSessionSigs,
- ...pkpEthersTest.pkpSessionSigs,
- ...pkpEthersTest.litActionSessionSigs,
-
- ...litActionCombiningTests.broadcastAndCombine,
- ...litActionCombiningTests.decryptAndCombine,
- ...litActionCombiningTests.ecdsaSignAndCombine,
-
- ...relayerTests,
- ...wrappedKeysTests,
- },
+ tests: tinnyTests,
devEnv,
};
diff --git a/local-tests/tests.ts b/local-tests/tests.ts
index ed882cd6d6..19ef4e873c 100644
--- a/local-tests/tests.ts
+++ b/local-tests/tests.ts
@@ -1,3 +1,4 @@
+import { testUseEoaSessionSigsToRequestSingleResponse } from './tests/testUseEoaSessionSigsToRequestSingleResponse';
import { testUseEoaSessionSigsToExecuteJsSigning } from './tests/testUseEoaSessionSigsToExecuteJsSigning';
import { testUseEoaSessionSigsToPkpSign } from './tests/testUseEoaSessionSigsToPkpSign';
import { testUsePkpSessionSigsToExecuteJsSigning } from './tests/testUsePkpSessionSigsToExecuteJsSigning';
@@ -10,24 +11,17 @@ import { testUseEoaSessionSigsToExecuteJsClaimKeys } from './tests/testUseEoaSes
import { testUseEoaSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseEoaSessionSigsToExecuteJsClaimMultipleKeys';
import { testUseEoaSessionSigsToExecuteJsJsonResponse } from './tests/testUseEoaSessionSigsToExecuteJsJsonResponse';
import { testUseEoaSessionSigsToExecuteJsConsoleLog } from './tests/testUseEoaSessionSigsToExecuteJsConsoleLog';
-import { testUseEoaSessionSigsToEncryptDecryptString } from './tests/testUseEoaSessionSigsToEncryptDecryptString';
-import { testUseEoaSessionSigsToEncryptDecryptUint8Array } from './tests/testUseEoaSessionSigsToEncryptDecryptUint8Array';
-import { testUsePkpSessionSigsToEncryptDecryptString } from './tests/testUsePkpSessionSigsToEncryptDecryptString';
-import { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString';
import { testUseInvalidLitActionCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionCodeToGenerateSessionSigs';
-import { testUseEoaSessionSigsToEncryptDecryptFile } from './tests/testUseEoaSessionSigsToEncryptDecryptFile';
import { testUsePkpSessionSigsToExecuteJsSigningInParallel } from './tests/testUsePkpSessionSigsToExecuteJsSigningInParallel';
import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel';
import { testUsePkpSessionSigsToExecuteJsClaimKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimKeys';
import { testUsePkpSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimMultipleKeys';
import { testUsePkpSessionSigsToExecuteJsJsonResponse } from './tests/testUsePkpSessionSigsToExecuteJsJsonResponse';
import { testUsePkpSessionSigsToExecuteJsConsoleLog } from './tests/testUsePkpSessionSigsToExecuteJsConsoleLog';
-import { testUsePkpSessionSigsToEncryptDecryptFile } from './tests/testUsePkpSessionSigsToEncryptDecryptFile';
import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys';
import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys';
import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse';
import { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog';
-import { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile';
import { testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign } from './tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign';
import { testUseInvalidLitActionIpfsCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionIpfsCodeToGenerateSessionSigs';
import { testPkpEthersWithEoaSessionSigsToSignMessage } from './tests/testPkpEthersWithEoaSessionSigsToSignMessage';
@@ -64,7 +58,6 @@ import { testPkpEthersWithPkpSessionSigsToEthSignTypedDataUtil } from './tests/t
import { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil';
import { testUseCustomAuthSessionSigsToPkpSignExecuteJs } from './tests/testUseCustomAuthSessionSigsToPkpSignExecuteJs';
import { testExecuteJsSignAndCombineEcdsa } from './tests/testExecuteJsSignAndCombineEcdsa';
-import { testExecuteJsDecryptAndCombine } from './tests/testExecuteJsDecryptAndCombine';
import { testExecuteJsBroadcastAndCollect } from './tests/testExecuteJsBroadcastAndCollect';
import { testRelayer } from './tests/testRelayer';
@@ -103,24 +96,17 @@ export { testUseEoaSessionSigsToExecuteJsClaimKeys } from './tests/testUseEoaSes
export { testUseEoaSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseEoaSessionSigsToExecuteJsClaimMultipleKeys';
export { testUseEoaSessionSigsToExecuteJsJsonResponse } from './tests/testUseEoaSessionSigsToExecuteJsJsonResponse';
export { testUseEoaSessionSigsToExecuteJsConsoleLog } from './tests/testUseEoaSessionSigsToExecuteJsConsoleLog';
-export { testUseEoaSessionSigsToEncryptDecryptString } from './tests/testUseEoaSessionSigsToEncryptDecryptString';
-export { testUseEoaSessionSigsToEncryptDecryptUint8Array } from './tests/testUseEoaSessionSigsToEncryptDecryptUint8Array';
-export { testUsePkpSessionSigsToEncryptDecryptString } from './tests/testUsePkpSessionSigsToEncryptDecryptString';
-export { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString';
export { testUseInvalidLitActionCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionCodeToGenerateSessionSigs';
-export { testUseEoaSessionSigsToEncryptDecryptFile } from './tests/testUseEoaSessionSigsToEncryptDecryptFile';
export { testUsePkpSessionSigsToExecuteJsSigningInParallel } from './tests/testUsePkpSessionSigsToExecuteJsSigningInParallel';
export { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel';
export { testUsePkpSessionSigsToExecuteJsClaimKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimKeys';
export { testUsePkpSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUsePkpSessionSigsToExecuteJsClaimMultipleKeys';
export { testUsePkpSessionSigsToExecuteJsJsonResponse } from './tests/testUsePkpSessionSigsToExecuteJsJsonResponse';
export { testUsePkpSessionSigsToExecuteJsConsoleLog } from './tests/testUsePkpSessionSigsToExecuteJsConsoleLog';
-export { testUsePkpSessionSigsToEncryptDecryptFile } from './tests/testUsePkpSessionSigsToEncryptDecryptFile';
export { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimKeys';
export { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys';
export { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse';
export { testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog';
-export { testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile } from './tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile';
export { testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign } from './tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign';
export { testUseInvalidLitActionIpfsCodeToGenerateSessionSigs } from './tests/testUseInvalidLitActionIpfsCodeToGenerateSessionSigs';
@@ -163,7 +149,6 @@ export { testPkpEthersWithPkpSessionSigsToEthSignTypedDataUtil } from './tests/t
export { testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil } from './tests/testPkpEthersWithLitActionSessionSigsToEthSignTypedDataUtil';
export { testUseCustomAuthSessionSigsToPkpSignExecuteJs } from './tests/testUseCustomAuthSessionSigsToPkpSignExecuteJs';
export { testExecuteJsSignAndCombineEcdsa } from './tests/testExecuteJsSignAndCombineEcdsa';
-export { testExecuteJsDecryptAndCombine } from './tests/testExecuteJsDecryptAndCombine';
export { testExecuteJsBroadcastAndCollect } from './tests/testExecuteJsBroadcastAndCollect';
export { testRelayer } from './tests/testRelayer';
@@ -197,7 +182,7 @@ const relayerTests = {
// --filter=WrappedKey
const wrappedKeysTests = {
- // -- valid cases
+ // // -- valid cases
// testBatchGeneratePrivateKeys,
// testEthereumSignMessageGeneratedKey,
// testEthereumBroadcastTransactionGeneratedKey,
@@ -205,22 +190,22 @@ const wrappedKeysTests = {
// testEthereumSignTransactionWrappedKey,
// testEthereumBroadcastTransactionWrappedKey,
// testEthereumBroadcastWrappedKeyWithFetchGasParams,
- // -- generate wrapped keys
+ // // -- generate wrapped keys
// testGenerateEthereumWrappedKey,
// testGenerateSolanaWrappedKey,
- // -- import wrapped keys
+ // // -- import wrapped keys
// testImportWrappedKey,
- // -- export wrapped keys
+ // // -- export wrapped keys
// testExportWrappedKey,
- // -- solana wrapped keys
+ // // -- solana wrapped keys
// testSignMessageWithSolanaEncryptedKey,
// testSignTransactionWithSolanaEncryptedKey,
- // -- invalid cases
+ // // -- invalid cases
// testFailEthereumSignTransactionWrappedKeyWithMissingParam,
// testFailEthereumSignTransactionWrappedKeyWithInvalidParam,
// testFailEthereumSignTransactionWrappedKeyInvalidDecryption,
// testFailBatchGeneratePrivateKeysAtomic,
- // -- import wrapped keys
+ // // -- import wrapped keys
// testFailImportWrappedKeysWithSamePrivateKey,
// testFailImportWrappedKeysWithEoaSessionSig,
// testFailImportWrappedKeysWithMaxExpirySessionSig,
@@ -230,15 +215,13 @@ const wrappedKeysTests = {
const eoaSessionSigsTests = {
testUseEoaSessionSigsToExecuteJsSigning,
+ testUseEoaSessionSigsToRequestSingleResponse,
testUseEoaSessionSigsToPkpSign,
testUseEoaSessionSigsToExecuteJsSigningInParallel,
testUseEoaSessionSigsToExecuteJsClaimKeys,
testUseEoaSessionSigsToExecuteJsClaimMultipleKeys,
testUseEoaSessionSigsToExecuteJsJsonResponse,
testUseEoaSessionSigsToExecuteJsConsoleLog,
- testUseEoaSessionSigsToEncryptDecryptString,
- testUseEoaSessionSigsToEncryptDecryptUint8Array,
- testUseEoaSessionSigsToEncryptDecryptFile,
};
const pkpSessionSigsTests = {
@@ -249,8 +232,6 @@ const pkpSessionSigsTests = {
testUsePkpSessionSigsToExecuteJsClaimMultipleKeys,
testUsePkpSessionSigsToExecuteJsJsonResponse,
testUsePkpSessionSigsToExecuteJsConsoleLog,
- testUsePkpSessionSigsToEncryptDecryptString,
- testUsePkpSessionSigsToEncryptDecryptFile,
};
const litActionSessionSigsTests = {
@@ -261,8 +242,6 @@ const litActionSessionSigsTests = {
testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsClaimMultipleKeys,
testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsJsonResponse,
testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsConsoleLog,
- testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString,
- testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile,
// -- invalid cases
testUseInvalidLitActionIpfsCodeToGenerateSessionSigs,
@@ -288,6 +267,11 @@ const bareAuthSigTests = {
// testCosmosAuthSigToEncryptDecryptString,
};
+const eip1271AuthSigTests = {
+ // testKeccakEip1271AuthSigToEncryptDecryptString,
+ // testShaEip1271AuthSigToEncryptDecryptString,
+};
+
const pkpEthersTest = {
eoaSessionSigs: {
testPkpEthersWithEoaSessionSigsToSignWithAuthContext,
@@ -332,9 +316,6 @@ const litActionCombiningTests = {
ecdsaSignAndCombine: {
testExecuteJsSignAndCombineEcdsa,
},
- decryptAndCombine: {
- testExecuteJsDecryptAndCombine,
- },
broadcastAndCombine: {
testExecuteJsBroadcastAndCollect,
},
@@ -347,6 +328,7 @@ export const tinnyTests = {
...pkpSessionSigsTests,
...litActionSessionSigsTests,
...litActionIpfsIdSessionSigsTests,
+ ...eip1271AuthSigTests,
...bareAuthSigTests,
...pkpEthersTest.eoaSessionSigs,
@@ -354,7 +336,6 @@ export const tinnyTests = {
...pkpEthersTest.litActionSessionSigs,
...litActionCombiningTests.broadcastAndCombine,
- ...litActionCombiningTests.decryptAndCombine,
...litActionCombiningTests.ecdsaSignAndCombine,
...relayerTests,
diff --git a/local-tests/tests/test-example.ts b/local-tests/tests/test-example.ts
deleted file mode 100644
index 7cf55fd939..0000000000
--- a/local-tests/tests/test-example.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { getEoaSessionSigs } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
-import { getLitActionSessionSigs } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
-import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
-
-import { LIT_NETWORK } from '@lit-protocol/constants';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-
-export const testExample = async (devEnv: TinnyEnvironment) => {
- // Note: This test will be skipped if we are testing on the DatilDev network
- devEnv.setUnavailable(LIT_NETWORK.DatilDev);
-
- const alice = await devEnv.createRandomPerson();
-
- const aliceEoaSessionSigs = await getEoaSessionSigs(devEnv, alice);
-
- const aliceExecuteJsRes = await devEnv.litNodeClient.executeJs({
- sessionSigs: aliceEoaSessionSigs,
- code: `(async () => {
- const sigShare = await LitActions.signEcdsa({
- toSign: dataToSign,
- publicKey,
- sigName: "sig",
- });
- })();`,
- jsParams: {
- dataToSign: alice.loveLetter,
- publicKey: alice.pkp.publicKey,
- },
- });
-
- console.log('aliceExecuteJsRes:', aliceExecuteJsRes);
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- // console.log('aliceEoaSessionSigs: ', aliceEoaSessionSigs);
-
- // const alicePkpSessionSigs = await getPkpSessionSigs(devEnv, alice);
- // console.log('alicePkpSessionSigs: ', alicePkpSessionSigs);
-
- // const aliceLitActionSessionSigs = await getLitActionSessionSigs(
- // devEnv,
- // alice
- // );
- // console.log('aliceLitActionSessionSigs: ', aliceLitActionSessionSigs);
-};
diff --git a/local-tests/tests/testExecuteJsDecryptAndCombine.ts b/local-tests/tests/testExecuteJsDecryptAndCombine.ts
deleted file mode 100644
index 5022f9f252..0000000000
--- a/local-tests/tests/testExecuteJsDecryptAndCombine.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { LIT_NETWORK } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { getLitActionAuthContext } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString
- * ✅ NETWORK=custom yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString
- *
- */
-export const testExecuteJsDecryptAndCombine = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.authMethodOwnedPkp.ethAddress,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const res = await devEnv.litNodeClient.executeJs({
- authContext: getLitActionAuthContext(devEnv, alice),
- code: `(async () => {
- const resp = await Lit.Actions.decryptAndCombine({
- accessControlConditions,
- ciphertext,
- dataToEncryptHash,
- authSig: null,
- chain: 'ethereum',
- });
- Lit.Actions.setResponse({
- response: resp
- });
- })();`,
- jsParams: {
- accessControlConditions: accs,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- ciphertext: encryptRes.ciphertext,
- },
- });
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (res.response !== 'Hello world') {
- throw new Error('content does not match what was expected');
- }
-};
diff --git a/local-tests/tests/testRelayer.ts b/local-tests/tests/testRelayer.ts
index c8d34ea2e3..57c6b148ab 100644
--- a/local-tests/tests/testRelayer.ts
+++ b/local-tests/tests/testRelayer.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ClaimRequest, ClientClaimProcessor } from '@lit-protocol/types';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { authenticators, LitRelay } from '@lit-protocol/auth';
@@ -90,5 +89,5 @@ export const testRelayer = async (devEnv: TinnyEnvironment) => {
}
});
- log('✅ 2. [testRelayer] Claim works');
+ console.log('✅ 2. [testRelayer] Claim works');
};
diff --git a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptFile.ts b/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptFile.ts
deleted file mode 100644
index 18b76d5a58..0000000000
--- a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptFile.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToFile } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=datil-test yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=custom yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptFile
- */
-export const testUseEoaSessionSigsToEncryptDecryptFile = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
- const message = 'Hello world';
- const blob = new Blob([message], { type: 'text/plain' });
- const blobArray = new Uint8Array(await blob.arrayBuffer());
-
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.wallet.address,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // await 5 seconds for the encryption to be mined
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decriptedFile = await decryptToFile(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getEoaAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (blobArray.length !== decriptedFile.length) {
- throw new Error(
- `decrypted file should match the original file but received ${decriptedFile}`
- );
- }
- for (let i = 0; i < blobArray.length; i++) {
- if (blobArray[i] !== decriptedFile[i]) {
- throw new Error(`decrypted file should match the original file`);
- }
- }
-
- console.log('decriptedFile:', decriptedFile);
-};
diff --git a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptString.ts b/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptString.ts
deleted file mode 100644
index 0b7a6676d3..0000000000
--- a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptString.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-// DEBUG=true LIT_RPC_URL=https://yellowstone-rpc.litprotocol.com NETWORK=custom yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptString
-import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToString } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptString
- * ✅ NETWORK=datil-test yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptString
- * ✅ NETWORK=custom yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptString
- */
-export const testUseEoaSessionSigsToEncryptDecryptString = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.wallet.address,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // await 5 seconds for the encryption to be mined
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decryptRes = await decryptToString(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getEoaAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (decryptRes !== 'Hello world') {
- throw new Error(
- `Expected decryptRes to be 'Hello world' but got ${decryptRes}`
- );
- }
-};
diff --git a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptUint8Array.ts b/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptUint8Array.ts
deleted file mode 100644
index 20e29dba02..0000000000
--- a/local-tests/tests/testUseEoaSessionSigsToEncryptDecryptUint8Array.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import {
- encryptUint8Array,
- decryptToUint8Array,
-} from '@lit-protocol/encryption';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptUint8Array
- * ✅ NETWORK=datil-test yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptUint8Array
- * ✅ NETWORK=custom yarn test:local --filter=testUseEoaSessionSigsToEncryptDecryptUint8Array
- */
-export const testUseEoaSessionSigsToEncryptDecryptUint8Array = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.wallet.address,
- });
-
- const message = 'Hello world';
- const messageToEncrypt = uint8arrayFromString(message, 'utf8');
-
- const encryptRes = await encryptUint8Array(
- {
- accessControlConditions: accs,
- dataToEncrypt: messageToEncrypt,
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // await 5 seconds for the encryption to be mined
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decryptRes = await decryptToUint8Array(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getEoaAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
- const decryptResString = uint8arrayToString(decryptRes, 'utf8');
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (decryptResString !== message) {
- throw new Error(
- `Expected decryptRes to be 'Hello world' but got ${decryptRes}`
- );
- }
-};
diff --git a/local-tests/tests/testUseEoaSessionSigsToExecuteJsClaimKeys.ts b/local-tests/tests/testUseEoaSessionSigsToExecuteJsClaimKeys.ts
index 9fb521bd90..ba0b98a7da 100644
--- a/local-tests/tests/testUseEoaSessionSigsToExecuteJsClaimKeys.ts
+++ b/local-tests/tests/testUseEoaSessionSigsToExecuteJsClaimKeys.ts
@@ -1,13 +1,5 @@
-// import { LitContracts } from '@lit-protocol/contracts-sdk';
-// import { log } from '@lit-protocol/misc';
-// import {
-// ClaimRequest,
-// ClaimResult,
-// ClientClaimProcessor,
-// } from '@lit-protocol/types';
import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
/**
* ## Scenario:
@@ -174,5 +166,5 @@ export const testUseEoaSessionSigsToExecuteJsClaimKeys = async (
// }
// });
- log('✅ testUseEoaSessionSigsToExecuteJsClaimKeys');
+ console.log('✅ testUseEoaSessionSigsToExecuteJsClaimKeys');
};
diff --git a/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigning.ts b/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigning.ts
index 415572de85..cc17a962d8 100644
--- a/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigning.ts
+++ b/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigning.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -62,5 +61,5 @@ export const testUseEoaSessionSigsToExecuteJsSigning = async (
throw new Error(`Expected "publicKey" in res.signatures.sig`);
}
- log('✅ testUseEoaSessionSigsToExecuteJsSigning');
+ console.log('✅ testUseEoaSessionSigsToExecuteJsSigning');
};
diff --git a/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigningInParallel.ts b/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigningInParallel.ts
index a3782ebbcd..ca2894abaa 100644
--- a/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigningInParallel.ts
+++ b/local-tests/tests/testUseEoaSessionSigsToExecuteJsSigningInParallel.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -14,7 +13,7 @@ export const testUseEoaSessionSigsToExecuteJsSigningInParallel = async (
const alice = await devEnv.createRandomPerson();
const fn = async (index: number) => {
- log(`Index: ${index}`);
+ console.log(`Index: ${index}`);
return await devEnv.litNodeClient.executeJs({
authContext: getEoaAuthContext(devEnv, alice),
@@ -34,7 +33,7 @@ export const testUseEoaSessionSigsToExecuteJsSigningInParallel = async (
const res = await Promise.all([fn(1), fn(2), fn(3)]);
devEnv.releasePrivateKeyFromUser(alice);
- log('res:', res);
+ console.log('res:', res);
// -- Expected output:
// [
@@ -114,5 +113,5 @@ export const testUseEoaSessionSigsToExecuteJsSigningInParallel = async (
}
});
- log('✅ testUseEoaSessionSigsToExecuteJsSigningInParallel');
+ console.log('✅ testUseEoaSessionSigsToExecuteJsSigningInParallel');
};
diff --git a/local-tests/tests/testUseEoaSessionSigsToPkpSign.ts b/local-tests/tests/testUseEoaSessionSigsToPkpSign.ts
index 0431da2142..852c1da223 100644
--- a/local-tests/tests/testUseEoaSessionSigsToPkpSign.ts
+++ b/local-tests/tests/testUseEoaSessionSigsToPkpSign.ts
@@ -1,6 +1,5 @@
import { ethers } from 'ethers';
-import { log } from '@lit-protocol/misc';
import { getEoaAuthContext } from 'local-tests/setup/session-sigs/get-eoa-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -82,5 +81,5 @@ export const testUseEoaSessionSigsToPkpSign = async (
);
}
- log('✅ testUseEoaSessionSigsToPkpSign');
+ console.log('✅ testUseEoaSessionSigsToPkpSign');
};
diff --git a/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptFile.ts b/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptFile.ts
deleted file mode 100644
index d854df3574..0000000000
--- a/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptFile.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToFile } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=datil-test yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=custom yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptFile
- */
-export const testUsePkpSessionSigsToEncryptDecryptFile = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
-
- const message = 'Hello world';
- const blob = new Blob([message], { type: 'text/plain' });
- const blobArray = new Uint8Array(await blob.arrayBuffer());
-
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.authMethodOwnedPkp.ethAddress,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // await 5 seconds for the encryption to be mined
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decriptedFile = await decryptToFile(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getPkpAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (blobArray.length !== decriptedFile.length) {
- throw new Error(
- `decrypted file should match the original file but received ${decriptedFile}`
- );
- }
- for (let i = 0; i < blobArray.length; i++) {
- if (blobArray[i] !== decriptedFile[i]) {
- throw new Error(`decrypted file should match the original file`);
- }
- }
-
- console.log('decriptedFile:', decriptedFile);
-};
diff --git a/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptString.ts b/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptString.ts
deleted file mode 100644
index 54c8c76207..0000000000
--- a/local-tests/tests/testUsePkpSessionSigsToEncryptDecryptString.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToString } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptString
- * ✅ NETWORK=datil-test yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptString
- * ✅ NETWORK=custom yarn test:local --filter=testUsePkpSessionSigsToEncryptDecryptString
- */
-export const testUsePkpSessionSigsToEncryptDecryptString = async (
- devEnv: TinnyEnvironment
-) => {
- const alice = await devEnv.createRandomPerson();
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.authMethodOwnedPkp.ethAddress,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decryptRes = await decryptToString(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getPkpAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (decryptRes !== 'Hello world') {
- throw new Error(
- `Expected decryptRes to be 'Hello world' but got ${decryptRes}`
- );
- }
-};
diff --git a/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigning.ts b/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigning.ts
index 982dbe0142..53a17cc73a 100644
--- a/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigning.ts
+++ b/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigning.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -76,5 +75,5 @@ export const testUsePkpSessionSigsToExecuteJsSigning = async (
throw new Error(`Expected "recid" to be parseable as a number`);
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigningInParallel.ts b/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigningInParallel.ts
index 28b467e4c8..ec530e2950 100644
--- a/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigningInParallel.ts
+++ b/local-tests/tests/testUsePkpSessionSigsToExecuteJsSigningInParallel.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -14,7 +13,7 @@ export const testUsePkpSessionSigsToExecuteJsSigningInParallel = async (
const alice = await devEnv.createRandomPerson();
const fn = async (index: number) => {
- log(`Index: ${index}`);
+ console.log(`Index: ${index}`);
return await devEnv.litNodeClient.executeJs({
authContext: getPkpAuthContext(devEnv, alice),
@@ -35,7 +34,7 @@ export const testUsePkpSessionSigsToExecuteJsSigningInParallel = async (
devEnv.releasePrivateKeyFromUser(alice);
const res = await Promise.all([fn(1), fn(2), fn(3)]);
- log('res:', res);
+ console.log('res:', res);
// -- Expected output:
// [
@@ -115,5 +114,5 @@ export const testUsePkpSessionSigsToExecuteJsSigningInParallel = async (
}
});
- log('✅ testUsePkpSessionSigsToExecuteJsSigningInParallel');
+ console.log('✅ testUsePkpSessionSigsToExecuteJsSigningInParallel');
};
diff --git a/local-tests/tests/testUsePkpSessionSigsToPkpSign.ts b/local-tests/tests/testUsePkpSessionSigsToPkpSign.ts
index 3f54db9f58..87c369b059 100644
--- a/local-tests/tests/testUsePkpSessionSigsToPkpSign.ts
+++ b/local-tests/tests/testUsePkpSessionSigsToPkpSign.ts
@@ -1,6 +1,5 @@
import { ethers } from 'ethers';
-import { log } from '@lit-protocol/misc';
import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -88,5 +87,5 @@ export const testUsePkpSessionSigsToPkpSign = async (
// );
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile.ts b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile.ts
deleted file mode 100644
index e5772f31a9..0000000000
--- a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { getPkpAuthContext } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToFile } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=datil-test yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=custom yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile
- */
-export const testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptFile =
- async (devEnv: TinnyEnvironment) => {
- const alice = await devEnv.createRandomPerson();
-
- const message = 'Hello world';
- const blob = new Blob([message], { type: 'text/plain' });
- const blobArray = new Uint8Array(await blob.arrayBuffer());
-
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.authMethodOwnedPkp.ethAddress,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // await 5 seconds for the encryption to be mined
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decriptedFile = await decryptToFile(
- {
- authContext: getPkpAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (blobArray.length !== decriptedFile.length) {
- throw new Error(
- `decrypted file should match the original file but received ${decriptedFile}`
- );
- }
- for (let i = 0; i < blobArray.length; i++) {
- if (blobArray[i] !== decriptedFile[i]) {
- throw new Error(`decrypted file should match the original file`);
- }
- }
-
- console.log('decriptedFile:', decriptedFile);
- };
diff --git a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString.ts b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString.ts
deleted file mode 100644
index b066bdcbf2..0000000000
--- a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { LIT_ABILITY } from '@lit-protocol/constants';
-import { ILitNodeClient } from '@lit-protocol/types';
-import { AccessControlConditions } from 'local-tests/setup/accs/accs';
-import { LitAccessControlConditionResource } from '@lit-protocol/auth-helpers';
-import { getLitActionAuthContext } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
-import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
-import { log } from '@lit-protocol/misc';
-import { encryptString, decryptToString } from '@lit-protocol/encryption';
-
-/**
- * Test Commands:
- * ✅ NETWORK=datil-dev yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString
- * ✅ NETWORK=custom yarn test:local --filter=testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString
- *
- */
-export const testUseValidLitActionCodeGeneratedSessionSigsToEncryptDecryptString =
- async (devEnv: TinnyEnvironment) => {
- const alice = await devEnv.createRandomPerson();
- // set access control conditions for encrypting and decrypting
- const accs = AccessControlConditions.getEvmBasicAccessControlConditions({
- userAddress: alice.authMethodOwnedPkp.ethAddress,
- });
-
- const encryptRes = await encryptString(
- {
- accessControlConditions: accs,
- dataToEncrypt: 'Hello world',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- log('encryptRes:', encryptRes);
-
- // -- Expected output:
- // {
- // ciphertext: "pSP1Rq4xdyLBzSghZ3DtTtHp2UL7/z45U2JDOQho/WXjd2ntr4IS8BJfqJ7TC2U4CmktrvbVT3edoXJgFqsE7vy9uNrBUyUSTuUdHLfDVMIgh4a7fqMxsdQdkWZjHign3JOaVBihtOjAF5VthVena28D",
- // dataToEncryptHash: "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c",
- // }
-
- // -- assertions
- if (!encryptRes.ciphertext) {
- throw new Error(`Expected "ciphertext" in encryptRes`);
- }
-
- if (!encryptRes.dataToEncryptHash) {
- throw new Error(`Expected "dataToEncryptHash" to in encryptRes`);
- }
-
- const accsResourceString =
- await LitAccessControlConditionResource.generateResourceString(
- accs,
- encryptRes.dataToEncryptHash
- );
-
- // -- Decrypt the encrypted string
- const decryptRes = await decryptToString(
- {
- accessControlConditions: accs,
- ciphertext: encryptRes.ciphertext,
- dataToEncryptHash: encryptRes.dataToEncryptHash,
- authContext: getLitActionAuthContext(devEnv, alice, [
- {
- resource: new LitAccessControlConditionResource(accsResourceString),
- ability: LIT_ABILITY.AccessControlConditionDecryption,
- },
- ]),
- chain: 'ethereum',
- },
- devEnv.litNodeClient as unknown as ILitNodeClient
- );
-
- devEnv.releasePrivateKeyFromUser(alice);
-
- if (decryptRes !== 'Hello world') {
- throw new Error(
- `Expected decryptRes to be 'Hello world' but got ${decryptRes}`
- );
- }
- };
diff --git a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning.ts b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning.ts
index 3191ae21ef..3d68cc4412 100644
--- a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning.ts
+++ b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning.ts
@@ -1,6 +1,6 @@
import { LitActionResource, LitPKPResource } from '@lit-protocol/auth-helpers';
-import { log } from '@lit-protocol/misc';
import { LIT_ABILITY } from '@lit-protocol/constants';
+
import { getLitActionAuthContext } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -74,5 +74,5 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigning =
throw new Error(`Expected "publicKey" in res.signatures.sig`);
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel.ts b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel.ts
index 867098a092..138f15cc38 100644
--- a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel.ts
+++ b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInParallel.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { getLitActionAuthContext } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -12,7 +11,7 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInPa
const alice = await devEnv.createRandomPerson();
const fn = async (index: number) => {
- log(`Index: ${index}`);
+ console.log(`Index: ${index}`);
return await devEnv.litNodeClient.executeJs({
authContext: getLitActionAuthContext(devEnv, alice),
@@ -33,7 +32,7 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInPa
devEnv.releasePrivateKeyFromUser(alice);
const res = await Promise.all([fn(1), fn(2), fn(3)]);
- log('res:', res);
+ console.log('res:', res);
// -- Expected output:
// [
@@ -113,5 +112,5 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToExecuteJsSigningInPa
}
});
- log('✅ testUsePkpSessionSigsToExecuteJsSigningInParallel');
+ console.log('✅ testUsePkpSessionSigsToExecuteJsSigningInParallel');
};
diff --git a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToPkpSign.ts b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToPkpSign.ts
index b59abac7cc..b60f2ed78a 100644
--- a/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToPkpSign.ts
+++ b/local-tests/tests/testUseValidLitActionCodeGeneratedSessionSigsToPkpSign.ts
@@ -1,6 +1,5 @@
import { ethers } from 'ethers';
-import { log } from '@lit-protocol/misc';
import { getLitActionAuthContext } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -78,5 +77,5 @@ export const testUseValidLitActionCodeGeneratedSessionSigsToPkpSign = async (
);
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning.ts b/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning.ts
index ab92a4127e..09762db841 100644
--- a/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning.ts
+++ b/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning.ts
@@ -1,6 +1,6 @@
import { LitActionResource, LitPKPResource } from '@lit-protocol/auth-helpers';
-import { log } from '@lit-protocol/misc';
import { LIT_ABILITY } from '@lit-protocol/constants';
+
import { getLitActionAuthContextUsingIpfsId } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -73,5 +73,5 @@ export const testUseValidLitActionIpfsCodeGeneratedSessionSigsToExecuteJsSigning
throw new Error(`Expected "publicKey" in res.signatures.sig`);
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign.ts b/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign.ts
index 94fd353569..205fbe329a 100644
--- a/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign.ts
+++ b/local-tests/tests/testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign.ts
@@ -1,6 +1,5 @@
import { ethers } from 'ethers';
-import { log } from '@lit-protocol/misc';
import { getLitActionAuthContextUsingIpfsId } from 'local-tests/setup/session-sigs/get-lit-action-session-sigs';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
@@ -78,5 +77,5 @@ export const testUseValidLitActionIpfsCodeGeneratedSessionSigsToPkpSign =
);
}
- log('✅ res:', res);
+ console.log('✅ res:', res);
};
diff --git a/local-tests/tests/wrapped-keys/testBatchGeneratePrivateKeys.ts b/local-tests/tests/wrapped-keys/testBatchGeneratePrivateKeys.ts
index b2c40701bf..486750a7ca 100644
--- a/local-tests/tests/wrapped-keys/testBatchGeneratePrivateKeys.ts
+++ b/local-tests/tests/wrapped-keys/testBatchGeneratePrivateKeys.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
@@ -129,7 +128,7 @@ export const testBatchGeneratePrivateKeys = async (
await verifyEvmSignature(results[0], evmMessageToSign);
console.log('results', results);
- log('✅ testBatchGenerateEncryptedKeys');
+ console.log('✅ testBatchGenerateEncryptedKeys');
} catch (err) {
console.log(err.message, err, err.stack);
throw err;
diff --git a/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionGeneratedKey.ts b/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionGeneratedKey.ts
index 3df75c6de5..3a32b2ea98 100644
--- a/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionGeneratedKey.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionGeneratedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api, EthereumLitTransaction } from '@lit-protocol/wrapped-keys';
@@ -75,7 +74,7 @@ export const testEthereumBroadcastTransactionGeneratedKey = async (
throw new Error(`signedTx isn't hex: ${signedTx}`);
}
- log('✅ testEthereumBroadcastTransactionGeneratedKey');
+ console.log('✅ testEthereumBroadcastTransactionGeneratedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionWrappedKey.ts b/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionWrappedKey.ts
index c10593c782..47e678506d 100644
--- a/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumBroadcastTransactionWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api, EthereumLitTransaction } from '@lit-protocol/wrapped-keys';
@@ -80,7 +79,7 @@ export const testEthereumBroadcastTransactionWrappedKey = async (
throw new Error(`signedTx isn't hex: ${signedTx}`);
}
- log('✅ testEthereumBroadcastTransactionWrappedKey');
+ console.log('✅ testEthereumBroadcastTransactionWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testEthereumBroadcastWrappedKeyWithFetchGasParams.ts b/local-tests/tests/wrapped-keys/testEthereumBroadcastWrappedKeyWithFetchGasParams.ts
index 75804f35cb..6fa8268183 100644
--- a/local-tests/tests/wrapped-keys/testEthereumBroadcastWrappedKeyWithFetchGasParams.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumBroadcastWrappedKeyWithFetchGasParams.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api, EthereumLitTransaction } from '@lit-protocol/wrapped-keys';
@@ -84,7 +83,7 @@ export const testEthereumBroadcastWrappedKeyWithFetchGasParams = async (
throw new Error(`signedTx isn't hex: ${signedTx}`);
}
- log('✅ testEthereumBroadcastWrappedKeyWithDefaultGasParams');
+ console.log('✅ testEthereumBroadcastWrappedKeyWithDefaultGasParams');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testEthereumSignMessageGeneratedKey.ts b/local-tests/tests/wrapped-keys/testEthereumSignMessageGeneratedKey.ts
index e85336caad..8318421c65 100644
--- a/local-tests/tests/wrapped-keys/testEthereumSignMessageGeneratedKey.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumSignMessageGeneratedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
@@ -90,7 +89,7 @@ export const testEthereumSignMessageGeneratedKey = async (
);
}
- log('✅ testEthereumSignMessageGeneratedKey');
+ console.log('✅ testEthereumSignMessageGeneratedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testEthereumSignMessageWrappedKey.ts b/local-tests/tests/wrapped-keys/testEthereumSignMessageWrappedKey.ts
index 08594ace4d..d95afdba41 100644
--- a/local-tests/tests/wrapped-keys/testEthereumSignMessageWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumSignMessageWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
@@ -94,7 +93,7 @@ export const testEthereumSignMessageWrappedKey = async (
);
}
- log('✅ testEthereumSignMessageWrappedKey');
+ console.log('✅ testEthereumSignMessageWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testEthereumSignTransactionWrappedKey.ts b/local-tests/tests/wrapped-keys/testEthereumSignTransactionWrappedKey.ts
index ac6c6bc983..6e0f83a3a1 100644
--- a/local-tests/tests/wrapped-keys/testEthereumSignTransactionWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testEthereumSignTransactionWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
@@ -76,7 +75,7 @@ export const testEthereumSignTransactionWrappedKey = async (
throw new Error(`signedTx isn't hex: ${signedTx}`);
}
- log('✅ testEthereumSignTransactionWrappedKey');
+ console.log('✅ testEthereumSignTransactionWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testExportWrappedKey.ts b/local-tests/tests/wrapped-keys/testExportWrappedKey.ts
index 50f41c142b..f59b562023 100644
--- a/local-tests/tests/wrapped-keys/testExportWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testExportWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from '../../setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from '../../setup/session-sigs/get-pkp-session-sigs';
@@ -64,7 +63,7 @@ export const testExportWrappedKey = async (devEnv: TinnyEnvironment) => {
);
}
- log('✅ testExportWrappedKey');
+ console.log('✅ testExportWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyInvalidDecryption.ts b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyInvalidDecryption.ts
index b62bc52c84..e13011e78e 100644
--- a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyInvalidDecryption.ts
+++ b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyInvalidDecryption.ts
@@ -1,8 +1,6 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
-import { encryptString } from '@lit-protocol/encryption';
import { LIT_PREFIX } from 'packages/wrapped-keys/src/lib/constants';
import { LIT_ACTION_CID_REPOSITORY } from '../../../packages/wrapped-keys/src/lib/lit-actions-client/constants';
import { getBaseTransactionForNetwork } from './util';
@@ -25,13 +23,11 @@ export const testFailEthereumSignTransactionWrappedKeyInvalidDecryption =
const alicePkpAddress = alice.authMethodOwnedPkp.ethAddress;
const decryptionAccessControlCondition =
getPkpAccessControlCondition(alicePkpAddress);
- const { ciphertext, dataToEncryptHash } = await encryptString(
- {
+ const { ciphertext, dataToEncryptHash } =
+ await devEnv.litNodeClient.encrypt({
accessControlConditions: [decryptionAccessControlCondition],
- dataToEncrypt: LIT_PREFIX + privateKey,
- },
- devEnv.litNodeClient
- );
+ dataToEncrypt: Buffer.from(LIT_PREFIX + privateKey, 'utf8'),
+ });
const pkpSessionSigsSigning = await getPkpSessionSigs(
devEnv,
@@ -79,7 +75,9 @@ export const testFailEthereumSignTransactionWrappedKeyInvalidDecryption =
}
}
- log('✅ testFailEthereumSignTransactionWrappedKeyInvalidDecryption');
+ console.log(
+ '✅ testFailEthereumSignTransactionWrappedKeyInvalidDecryption'
+ );
} finally {
devEnv.releasePrivateKeyFromUser(alice);
devEnv.releasePrivateKeyFromUser(bob);
diff --git a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithInvalidParam.ts b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithInvalidParam.ts
index 88b98abbf5..4ee61c0b86 100644
--- a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithInvalidParam.ts
+++ b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithInvalidParam.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api, EthereumLitTransaction } from '@lit-protocol/wrapped-keys';
@@ -82,7 +81,7 @@ export const testFailEthereumSignTransactionWrappedKeyWithInvalidParam = async (
}
}
- log('✅ testFailEthereumSignTransactionWrappedKeyWithInvalidParam');
+ console.log('✅ testFailEthereumSignTransactionWrappedKeyWithInvalidParam');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithMissingParam.ts b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithMissingParam.ts
index adb2b76a35..cec8b565e2 100644
--- a/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithMissingParam.ts
+++ b/local-tests/tests/wrapped-keys/testFailEthereumSignTransactionWrappedKeyWithMissingParam.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { ethers } from 'ethers';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
@@ -77,7 +76,7 @@ export const testFailEthereumSignTransactionWrappedKeyWithMissingParam = async (
}
}
- log('✅ testFailEthereumSignTransactionWrappedKeyWithMissingParam');
+ console.log('✅ testFailEthereumSignTransactionWrappedKeyWithMissingParam');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testFailStoreEncryptedKeyBatchIsAtomic.ts b/local-tests/tests/wrapped-keys/testFailStoreEncryptedKeyBatchIsAtomic.ts
index 7716838387..073c500588 100644
--- a/local-tests/tests/wrapped-keys/testFailStoreEncryptedKeyBatchIsAtomic.ts
+++ b/local-tests/tests/wrapped-keys/testFailStoreEncryptedKeyBatchIsAtomic.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
@@ -115,7 +114,7 @@ export const testFailBatchGeneratePrivateKeysAtomic = async (
);
} catch (err) {
if (err.message.includes('No keys exist for pkpAddress')) {
- log('✅ testFailBatchGeneratePrivateKeysAtomic');
+ console.log('✅ testFailBatchGeneratePrivateKeysAtomic');
} else {
throw err;
}
diff --git a/local-tests/tests/wrapped-keys/testGenerateEthereumWrappedKey.ts b/local-tests/tests/wrapped-keys/testGenerateEthereumWrappedKey.ts
index 5f0c22aa37..743d926692 100644
--- a/local-tests/tests/wrapped-keys/testGenerateEthereumWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testGenerateEthereumWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
@@ -65,7 +64,7 @@ export const testGenerateEthereumWrappedKey = async (
);
}
- log('✅ testGenerateEthereumWrappedKey');
+ console.log('✅ testGenerateEthereumWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testGenerateSolanaWrappedKey.ts b/local-tests/tests/wrapped-keys/testGenerateSolanaWrappedKey.ts
index 1bcb239ce2..532bdcd112 100644
--- a/local-tests/tests/wrapped-keys/testGenerateSolanaWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testGenerateSolanaWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
@@ -102,7 +101,7 @@ export const testGenerateSolanaWrappedKey = async (
);
}
- log('✅ testGenerateSolanaWrappedKey');
+ console.log('✅ testGenerateSolanaWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testImportWrappedKey.ts b/local-tests/tests/wrapped-keys/testImportWrappedKey.ts
index 9c2bdfd00c..d3fe9b7da1 100644
--- a/local-tests/tests/wrapped-keys/testImportWrappedKey.ts
+++ b/local-tests/tests/wrapped-keys/testImportWrappedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { getPkpSessionSigs } from 'local-tests/setup/session-sigs/get-pkp-session-sigs';
@@ -53,7 +52,7 @@ export const testImportWrappedKey = async (devEnv: TinnyEnvironment) => {
);
}
- log('✅ testImportWrappedKey');
+ console.log('✅ testImportWrappedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testSignMessageWithSolanaEncryptedKey.ts b/local-tests/tests/wrapped-keys/testSignMessageWithSolanaEncryptedKey.ts
index b182f3e27d..a00ffbde5e 100644
--- a/local-tests/tests/wrapped-keys/testSignMessageWithSolanaEncryptedKey.ts
+++ b/local-tests/tests/wrapped-keys/testSignMessageWithSolanaEncryptedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { api } from '@lit-protocol/wrapped-keys';
import { Keypair } from '@solana/web3.js';
@@ -77,7 +76,7 @@ export const testSignMessageWithSolanaEncryptedKey = async (
`signature: ${signature} doesn't validate for the Solana public key: ${solanaKeypair.publicKey.toString()}`
);
- log('✅ testSignMessageWithSolanaEncryptedKey');
+ console.log('✅ testSignMessageWithSolanaEncryptedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/local-tests/tests/wrapped-keys/testSignTransactionWithSolanaEncryptedKey.ts b/local-tests/tests/wrapped-keys/testSignTransactionWithSolanaEncryptedKey.ts
index 138d2c5b53..bd9af84d06 100644
--- a/local-tests/tests/wrapped-keys/testSignTransactionWithSolanaEncryptedKey.ts
+++ b/local-tests/tests/wrapped-keys/testSignTransactionWithSolanaEncryptedKey.ts
@@ -1,4 +1,3 @@
-import { log } from '@lit-protocol/misc';
import { TinnyEnvironment } from 'local-tests/setup/tinny-environment';
import { SerializedTransaction, api } from '@lit-protocol/wrapped-keys';
import {
@@ -135,7 +134,7 @@ export const testSignTransactionWithSolanaEncryptedKey = async (
);
}
- log('✅ testSignMessageWithSolanaEncryptedKey');
+ console.log('✅ testSignMessageWithSolanaEncryptedKey');
} finally {
devEnv.releasePrivateKeyFromUser(alice);
}
diff --git a/package.json b/package.json
index 6a0bf1391b..f0f93e9b49 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"@lit-protocol/contracts": "^0.1.7",
"@metamask/eth-sig-util": "5.0.2",
"@mysten/sui.js": "^0.37.1",
+ "@noble/curves": "^1.8.1",
"@openagenda/verror": "^3.1.4",
"@simplewebauthn/browser": "^7.2.0",
"@simplewebauthn/typescript-types": "^7.0.0",
@@ -66,13 +67,13 @@
"micromodal": "^0.4.10",
"multiformats": "^9.7.1",
"pako": "^2.1.0",
+ "pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"siwe": "^2.3.2",
"siwe-recap": "0.0.2-alpha.0",
"stytch": "^12.4.0",
"tslib": "^2.7.0",
"tweetnacl": "^1.0.3",
- "tweetnacl-util": "^0.15.1",
"uint8arrays": "^4.0.3",
"wagmi": "^2.14.13",
"zod": "^3.24.2",
@@ -94,7 +95,7 @@
"@types/depd": "^1.1.36",
"@types/events": "^3.0.3",
"@types/jest": "27.4.1",
- "@types/node": "18.19.18",
+ "@types/node": "20",
"@types/secp256k1": "^4.0.6",
"@typescript-eslint/eslint-plugin": "6.21.0",
"@typescript-eslint/parser": "6.21.0",
@@ -117,13 +118,15 @@
"eslint-plugin-jsx-a11y": "6.9.0",
"inquirer": "^9.2.21",
"ipfs-unixfs-importer": "12.0.1",
- "jest": "27.5.1",
+ "jest": "^29.2.2",
+ "jest-environment-jsdom": "^29.7.0",
"lerna": "^5.4.3",
"live-server": "^1.2.2",
"node-fetch": "^2.6.1",
"node-localstorage": "^3.0.5",
"nx": "17.3.0",
"path": "^0.12.7",
+ "pino-pretty": "^13.0.0",
"prettier": "^2.6.2",
"ts-jest": "29.2.5",
"typedoc": "^0.26.6",
diff --git a/packages/access-control-conditions-schemas/project.json b/packages/access-control-conditions-schemas/project.json
index 683b67e7f8..91e13e6dac 100644
--- a/packages/access-control-conditions-schemas/project.json
+++ b/packages/access-control-conditions-schemas/project.json
@@ -30,7 +30,7 @@
]
}
},
- "testPackage": {
+ "test": {
"executor": "@nx/jest:jest",
"outputs": [
"{workspaceRoot}/coverage/packages/access-control-conditions-schemas"
diff --git a/packages/access-control-conditions/src/index.ts b/packages/access-control-conditions/src/index.ts
index ac7cbe3e77..1b512cc351 100644
--- a/packages/access-control-conditions/src/index.ts
+++ b/packages/access-control-conditions/src/index.ts
@@ -1,3 +1,4 @@
+export * from './lib/booleanExpressions';
export * from './lib/canonicalFormatter';
export * from './lib/hashing';
export * from './lib/humanizer';
diff --git a/packages/misc/src/lib/utils.ts b/packages/access-control-conditions/src/lib/booleanExpressions.ts
similarity index 82%
rename from packages/misc/src/lib/utils.ts
rename to packages/access-control-conditions/src/lib/booleanExpressions.ts
index ea7ef45536..f01e53c7d2 100644
--- a/packages/misc/src/lib/utils.ts
+++ b/packages/access-control-conditions/src/lib/booleanExpressions.ts
@@ -1,3 +1,4 @@
+import { OperatorAccSchema } from '@lit-protocol/access-control-conditions-schemas';
import {
AccessControlConditions,
EvmContractConditions,
@@ -5,9 +6,8 @@ import {
UnifiedAccessControlConditions,
} from '@lit-protocol/types';
-export function isTokenOperator(token: any): boolean {
- const OPERATORS = ['and', 'or']; // Only permissible boolean operators on the nodes
- return token.hasOwnProperty('operator') && OPERATORS.includes(token.operator);
+export function isTokenOperator(token: unknown): boolean {
+ return OperatorAccSchema.safeParse(token).success;
}
export function isValidBooleanExpression(
diff --git a/packages/access-control-conditions/src/lib/canonicalFormatter.spec.ts b/packages/access-control-conditions/src/lib/canonicalFormatter.spec.ts
index d0f36b7146..b3e925539e 100644
--- a/packages/access-control-conditions/src/lib/canonicalFormatter.spec.ts
+++ b/packages/access-control-conditions/src/lib/canonicalFormatter.spec.ts
@@ -1,4 +1,6 @@
+import { InvalidAccessControlConditions } from '@lit-protocol/constants';
import { ConditionItem } from '@lit-protocol/types';
+
import {
canonicalUnifiedAccessControlConditionFormatter,
canonicalSolRpcConditionFormatter,
@@ -11,7 +13,7 @@ import {
// ---------- Test Cases ----------
describe('canonicalFormatter.ts', () => {
it('should format canonical unified access control (ETH + SOLANA Wallet Addresses with "AND" operator)', async () => {
- const EXPECTED_INPUT: Array = [
+ const EXPECTED_INPUT: ConditionItem[] = [
{
conditionType: 'evmBasic',
contractAddress: '',
@@ -74,19 +76,14 @@ describe('canonicalFormatter.ts', () => {
},
];
- const test =
- canonicalUnifiedAccessControlConditionFormatter(EXPECTED_INPUT);
-
- expect(test).toStrictEqual(EXPECTED_OUTPUT);
+ expect(
+ canonicalUnifiedAccessControlConditionFormatter(EXPECTED_INPUT)
+ ).toStrictEqual(EXPECTED_OUTPUT);
});
it('should FAIL to format canonical unified access control if key "conditionType" doesnt exist', async () => {
- console.log = jest.fn();
-
- let test;
-
- try {
- test = canonicalUnifiedAccessControlConditionFormatter([
+ expect(() =>
+ canonicalUnifiedAccessControlConditionFormatter([
{
contractAddress: '',
standardContractType: '',
@@ -98,84 +95,60 @@ describe('canonicalFormatter.ts', () => {
value: '0x3B5dD260598B7579A0b015A1F3BBF322aDC499A2',
},
},
- ]);
- } catch (e) {
- console.log(e);
- }
-
- expect((console.log as any).mock.calls[0][0].message).toContain(
+ ])
+ ).toThrow(
'You passed an invalid access control condition that is missing or has a wrong'
);
});
it('should FAIL to format canonical unified access control (key: foo, value: bar)', async () => {
- console.log = jest.fn();
-
- const MOCK_ACCS_UNKNOWN_KEY: any = [
- {
- foo: 'bar',
- },
- {
- conditionType: 'evmBasic',
- contractAddress: '',
- standardContractType: '',
- chain: 'ethereum',
- method: '',
- parameters: [':userAddress'],
- returnValueTest: {
- comparator: '=',
- value: '0x3B5dD260598B7579A0b015A1F3BBF322aDC499A2',
+ expect(() =>
+ canonicalUnifiedAccessControlConditionFormatter([
+ {
+ // @ts-expect-error we are testing
+ foo: 'bar',
},
- },
- ];
-
- try {
- test = canonicalUnifiedAccessControlConditionFormatter(
- MOCK_ACCS_UNKNOWN_KEY
- );
- } catch (e) {
- console.log(e);
- }
-
- expect((console.log as any).mock.calls[0][0].name).toBe(
- 'InvalidAccessControlConditions'
- );
+ {
+ conditionType: 'evmBasic',
+ contractAddress: '',
+ standardContractType: '',
+ chain: 'ethereum',
+ method: '',
+ parameters: [':userAddress'],
+ returnValueTest: {
+ comparator: '=',
+ value: '0x3B5dD260598B7579A0b015A1F3BBF322aDC499A2',
+ },
+ },
+ ])
+ ).toThrow(InvalidAccessControlConditions);
});
it('should throw error when format canonical sol rpc condition', async () => {
- console.log = jest.fn();
-
- const MOCK_ACCS_UNKNOWN_KEY: any = [
- {
- foo: 'bar',
- },
- {
- conditionType: 'evmBasic',
- contractAddress: '',
- standardContractType: '',
- chain: 'ethereum',
- method: '',
- parameters: [':userAddress'],
- returnValueTest: {
- comparator: '=',
- value: '0x3B5dD260598B7579A0b015A1F3BBF322aDC499A2',
+ expect(() =>
+ canonicalSolRpcConditionFormatter([
+ {
+ // @ts-expect-error we are testing
+ foo: 'bar',
},
- },
- ];
-
- try {
- test = canonicalSolRpcConditionFormatter(MOCK_ACCS_UNKNOWN_KEY);
- } catch (e) {
- console.log(e);
- }
-
- expect((console.log as any).mock.calls[0][0].name).toBe(
- 'InvalidAccessControlConditions'
- );
+ {
+ conditionType: 'evmBasic',
+ contractAddress: '',
+ standardContractType: '',
+ chain: 'ethereum',
+ method: '',
+ parameters: [':userAddress'],
+ returnValueTest: {
+ comparator: '=',
+ value: '0x3B5dD260598B7579A0b015A1F3BBF322aDC499A2',
+ },
+ },
+ ])
+ ).toThrow(InvalidAccessControlConditions);
});
it('should call "canonicalAccessControlConditionFormatter" in node.js', () => {
- const params: any = [];
+ const params = [] as never[];
const OUTPUT = canonicalAccessControlConditionFormatter(params);
@@ -183,7 +156,7 @@ describe('canonicalFormatter.ts', () => {
});
it('should call canonicalEVMContractConditionFormatter in node.js', () => {
- const params: any = [];
+ const params = [] as never[];
const OUTPUT = canonicalEVMContractConditionFormatter(params);
@@ -191,7 +164,7 @@ describe('canonicalFormatter.ts', () => {
});
it('should call canonicalCosmosConditionFormatter in node.js', () => {
- const params: any = [];
+ const params = [] as never[];
const OUTPUT = canonicalCosmosConditionFormatter(params);
@@ -199,11 +172,8 @@ describe('canonicalFormatter.ts', () => {
});
it('should call canonicalResourceIdFormatter in node.js', () => {
- const params: any = [];
-
- const OUTPUT = canonicalResourceIdFormatter(params);
-
- // const res = (console.log as any).mock.calls[0][0];
+ // @ts-expect-error we are testing
+ const OUTPUT = canonicalResourceIdFormatter({});
expect(OUTPUT.baseUrl).toBe(undefined);
});
diff --git a/packages/access-control-conditions/src/lib/canonicalFormatter.ts b/packages/access-control-conditions/src/lib/canonicalFormatter.ts
index a10b4181c8..69640b855a 100644
--- a/packages/access-control-conditions/src/lib/canonicalFormatter.ts
+++ b/packages/access-control-conditions/src/lib/canonicalFormatter.ts
@@ -142,7 +142,7 @@ export const canonicalUnifiedAccessControlConditionFormatter = (
* @returns { any[] | OperatorAcc | AccsSOLV2Params | any }
*/
export const canonicalSolRpcConditionFormatter = (
- cond: ConditionItem,
+ cond: ConditionItem | ConditionItem[],
requireV2Conditions: boolean = false
): any[] | OperatorAcc | ConditionItem | AccsSOLV2Params | any => {
// -- if is array
@@ -186,7 +186,7 @@ export const canonicalSolRpcConditionFormatter = (
cond,
},
},
- 'Solana RPC Conditions have changed and there are some new fields you must include in your condition. Check the docs here: https://developer.litprotocol.com/AccessControlConditions/solRpcConditions'
+ 'Solana RPC Conditions have changed and there are some new fields you must include in your condition. Check the docs here: https://developer.litprotocol.com/AccessControlConditions/solRpcConditions'
);
}
@@ -415,7 +415,7 @@ export const canonicalEVMContractConditionFormatter = (
* @returns
*/
export const canonicalCosmosConditionFormatter = (
- cond: ConditionItem
+ cond: ConditionItem | ConditionItem[]
): any[] | OperatorAcc | AccsCOSMOSParams | any => {
// -- if it's an array
if (Array.isArray(cond)) {
diff --git a/packages/access-control-conditions/src/lib/hashing.spec.ts b/packages/access-control-conditions/src/lib/hashing.spec.ts
index ead036529f..9281186890 100644
--- a/packages/access-control-conditions/src/lib/hashing.spec.ts
+++ b/packages/access-control-conditions/src/lib/hashing.spec.ts
@@ -51,7 +51,6 @@ describe('hashing.ts', () => {
},
},
]);
- // console.log(typeof OUTPUT);
expect(new Uint8Array(OUTPUT).length).toBe(32);
});
@@ -63,7 +62,6 @@ describe('hashing.ts', () => {
role: '',
extraData: '',
});
- // console.log(typeof OUTPUT);
expect(new Uint8Array(OUTPUT).length).toBe(32);
});
@@ -75,7 +73,6 @@ describe('hashing.ts', () => {
role: '',
extraData: '',
});
- // console.log(typeof OUTPUT);
expect(OUTPUT).toBe(
'5b36d72f2145af3617e5da2a8a626f9f42e64ed14340622bdfe1a6f0702b9e8d'
);
@@ -96,7 +93,6 @@ describe('hashing.ts', () => {
},
},
]);
- // console.log(typeof OUTPUT);
expect(typeof OUTPUT).toBe('object');
});
@@ -152,7 +148,6 @@ describe('hashing.ts', () => {
},
},
]);
- // console.log(typeof OUTPUT);
expect(typeof OUTPUT).toBe('object');
});
@@ -172,7 +167,6 @@ describe('hashing.ts', () => {
},
},
]);
- // console.log(typeof OUTPUT);
expect(typeof OUTPUT).toBe('object');
});
});
diff --git a/packages/access-control-conditions/src/lib/hashing.ts b/packages/access-control-conditions/src/lib/hashing.ts
index eecf844836..e936f145e5 100644
--- a/packages/access-control-conditions/src/lib/hashing.ts
+++ b/packages/access-control-conditions/src/lib/hashing.ts
@@ -1,5 +1,5 @@
import { InvalidAccessControlConditions } from '@lit-protocol/constants';
-import { log } from '@lit-protocol/misc';
+import { logger } from '@lit-protocol/logger';
import {
AccessControlConditions,
EvmContractConditions,
@@ -10,7 +10,6 @@ import {
SupportedJsonRequests,
UnifiedAccessControlConditions,
} from '@lit-protocol/types';
-import { uint8arrayToString } from '@lit-protocol/uint8arrays';
import {
canonicalAccessControlConditionFormatter,
@@ -77,7 +76,7 @@ import {
// const hash = await hashUnifiedAccessControlConditions(unifiedAccs);
-// return uint8arrayToString(new Uint8Array(hash), 'base16');
+// return Buffer.from(new Uint8Array(hash), 'hex');
// };
/**
@@ -90,12 +89,15 @@ import {
export const hashUnifiedAccessControlConditions = (
unifiedAccessControlConditions: UnifiedAccessControlConditions
): Promise => {
- log('unifiedAccessControlConditions:', unifiedAccessControlConditions);
+ logger.info({
+ msg: 'unifiedAccessControlConditions',
+ unifiedAccessControlConditions,
+ });
const conditions = unifiedAccessControlConditions.map((condition) => {
return canonicalUnifiedAccessControlConditionFormatter(condition);
});
- log('conditions:', conditions);
+ logger.info({ msg: 'conditions', conditions });
// check if there's any undefined in the conditions
const hasUndefined = conditions.some((c) => c === undefined);
@@ -122,7 +124,7 @@ export const hashUnifiedAccessControlConditions = (
}
const toHash = JSON.stringify(conditions);
- log('Hashing unified access control conditions: ', toHash);
+ logger.info({ msg: 'Hashing unified access control conditions', toHash });
const encoder = new TextEncoder();
const data = encoder.encode(toHash);
@@ -161,7 +163,7 @@ export const hashResourceIdForSigning = async (
resourceId: JsonSigningResourceId
): Promise => {
const hashed = await hashResourceId(resourceId);
- return uint8arrayToString(new Uint8Array(hashed), 'base16');
+ return Buffer.from(new Uint8Array(hashed)).toString('hex');
};
/**
@@ -181,7 +183,7 @@ export const hashAccessControlConditions = (
);
const toHash = JSON.stringify(conds);
- log('Hashing access control conditions: ', toHash);
+ logger.info({ msg: 'Hashing access control conditions', toHash });
const encoder = new TextEncoder();
const data = encoder.encode(toHash);
@@ -205,7 +207,7 @@ export const hashEVMContractConditions = (
);
const toHash = JSON.stringify(conds);
- log('Hashing evm contract conditions: ', toHash);
+ logger.info({ msg: 'Hashing evm contract conditions', toHash });
const encoder = new TextEncoder();
const data = encoder.encode(toHash);
return crypto.subtle.digest('SHA-256', data);
@@ -228,7 +230,7 @@ export const hashSolRpcConditions = (
);
const toHash = JSON.stringify(conds);
- log('Hashing sol rpc conditions: ', toHash);
+ logger.info({ msg: 'Hashing sol rpc conditions', toHash });
const encoder = new TextEncoder();
const data = encoder.encode(toHash);
@@ -301,34 +303,43 @@ export const getFormattedAccessControlConditions = (
formattedAccessControlConditions = accessControlConditions.map((c) =>
canonicalAccessControlConditionFormatter(c)
);
- log(
- 'formattedAccessControlConditions',
- JSON.stringify(formattedAccessControlConditions)
- );
+ logger.info({
+ msg: 'formattedAccessControlConditions',
+ formattedAccessControlConditions: JSON.stringify(
+ formattedAccessControlConditions
+ ),
+ });
} else if (evmContractConditions) {
formattedEVMContractConditions = evmContractConditions.map((c) =>
canonicalEVMContractConditionFormatter(c)
);
- log(
- 'formattedEVMContractConditions',
- JSON.stringify(formattedEVMContractConditions)
- );
+ logger.info({
+ msg: 'formattedEVMContractConditions',
+ formattedEVMContractConditions: JSON.stringify(
+ formattedEVMContractConditions
+ ),
+ });
} else if (solRpcConditions) {
// FIXME: ConditionItem is too narrow, or `solRpcConditions` is too wide
// eslint-disable-next-line @typescript-eslint/no-explicit-any
formattedSolRpcConditions = solRpcConditions.map((c: any) =>
canonicalSolRpcConditionFormatter(c)
);
- log('formattedSolRpcConditions', JSON.stringify(formattedSolRpcConditions));
+ logger.info({
+ msg: 'formattedSolRpcConditions',
+ formattedSolRpcConditions: JSON.stringify(formattedSolRpcConditions),
+ });
} else if (unifiedAccessControlConditions) {
formattedUnifiedAccessControlConditions =
unifiedAccessControlConditions.map((c) =>
canonicalUnifiedAccessControlConditionFormatter(c)
);
- log(
- 'formattedUnifiedAccessControlConditions',
- JSON.stringify(formattedUnifiedAccessControlConditions)
- );
+ logger.info({
+ msg: 'formattedUnifiedAccessControlConditions',
+ formattedUnifiedAccessControlConditions: JSON.stringify(
+ formattedUnifiedAccessControlConditions
+ ),
+ });
} else {
error = true;
}
diff --git a/packages/access-control-conditions/src/lib/humanizer.spec.ts b/packages/access-control-conditions/src/lib/humanizer.spec.ts
index baa6e092a1..cace7f2697 100644
--- a/packages/access-control-conditions/src/lib/humanizer.spec.ts
+++ b/packages/access-control-conditions/src/lib/humanizer.spec.ts
@@ -1,5 +1,3 @@
-import * as humanizer from './humanizer';
-import { humanizeAccessControlConditions } from './humanizer';
import {
AccsCOSMOSParams,
AccsEVMParams,
@@ -7,6 +5,9 @@ import {
UnifiedAccessControlConditions,
} from '@lit-protocol/types';
+import * as humanizer from './humanizer';
+import { humanizeAccessControlConditions } from './humanizer';
+
// ---------- Test Cases ----------
describe('humanizer.ts', () => {
it('should format sol', () => {
@@ -60,7 +61,7 @@ describe('humanizer.ts', () => {
expect(OUTPUT).toBe('at most');
});
it('should humanizeEvmBasicAccessControlConditions', async () => {
- const INPUT: Array = [
+ const INPUT: AccsEVMParams[] = [
{
contractAddress: '0x7C7757a9675f06F3BE4618bB68732c4aB25D2e88',
functionName: 'balanceOf',
@@ -108,7 +109,7 @@ describe('humanizer.ts', () => {
});
it('should humanizeSolRpcConditions', async () => {
- const INPUT: Array = [
+ const INPUT: AccsSOLV2Params[] = [
{
method: 'getTokenAccountBalance',
params: ['tn2WEWk4Kqj157XsSdmBBcjWumVhkyJECXCKPq9ReL9'],
@@ -134,7 +135,7 @@ describe('humanizer.ts', () => {
});
it('should humanizeCosmosConditions', async () => {
- const INPUT: Array = [
+ const INPUT: AccsCOSMOSParams[] = [
{
conditionType: 'cosmos',
path: '/cosmos/bank/v1beta1/balances/:userAddress',
diff --git a/packages/access-control-conditions/src/lib/humanizer.ts b/packages/access-control-conditions/src/lib/humanizer.ts
index 40de46aae7..1c99c4b8ca 100644
--- a/packages/access-control-conditions/src/lib/humanizer.ts
+++ b/packages/access-control-conditions/src/lib/humanizer.ts
@@ -1,7 +1,13 @@
+import { Contract } from '@ethersproject/contracts';
+import { JsonRpcProvider } from '@ethersproject/providers';
import { formatEther, formatUnits } from 'ethers/lib/utils';
-import { InvalidUnifiedConditionType } from '@lit-protocol/constants';
-import { decimalPlaces, log } from '@lit-protocol/misc';
+import {
+ LIT_CHAINS,
+ LitEVMChainKeys,
+ InvalidUnifiedConditionType,
+} from '@lit-protocol/constants';
+import { logger } from '@lit-protocol/logger';
import {
AccessControlConditions,
AccsCOSMOSParams,
@@ -11,6 +17,51 @@ import {
UnifiedAccessControlConditions,
} from '@lit-protocol/types';
+export const ERC20ABI = [
+ {
+ constant: true,
+ inputs: [],
+ name: 'decimals',
+ outputs: [
+ {
+ name: '',
+ type: 'uint8',
+ },
+ ],
+ payable: false,
+ stateMutability: 'view',
+ type: 'function',
+ },
+];
+
+/**
+ *
+ * Get the number of decimal places in a token
+ *
+ * @property { string } contractAddress The token contract address
+ * @property { LitEVMChainKeys } chain The chain on which the token is deployed
+ *
+ * @returns { number } The number of decimal places in the token
+ */
+export const decimalPlaces = async ({
+ contractAddress,
+ chain,
+}: {
+ contractAddress: string;
+ chain: LitEVMChainKeys;
+}): Promise => {
+ const rpcUrl = LIT_CHAINS[chain].rpcUrls[0] as string;
+
+ const web3 = new JsonRpcProvider({
+ url: rpcUrl,
+ skipFetchSetup: true,
+ });
+
+ const contract = new Contract(contractAddress, ERC20ABI, web3);
+
+ return await contract['decimals']();
+};
+
/**
*
* Format SOL number using Ether Units
@@ -58,7 +109,7 @@ export const humanizeComparator = (comparator: string): string | undefined => {
const selected: string | undefined = list[comparator];
if (!selected) {
- log(`Unregonized comparator ${comparator}`);
+ logger.info(`Unrecognized comparator ${comparator}`);
return;
}
@@ -84,9 +135,9 @@ export const humanizeEvmBasicAccessControlConditions = async ({
tokenList?: (any | string)[];
myWalletAddress?: string;
}): Promise => {
- log('humanizing evm basic access control conditions');
- log('myWalletAddress', myWalletAddress);
- log('accessControlConditions', accessControlConditions);
+ logger.info('humanizing evm basic access control conditions');
+ logger.info({ msg: 'myWalletAddress', myWalletAddress });
+ logger.info({ msg: 'accessControlConditions', accessControlConditions });
let fixedConditions = accessControlConditions;
@@ -230,10 +281,10 @@ export const humanizeEvmBasicAccessControlConditions = async ({
chain: acc.chain,
});
} catch (e) {
- console.log(`Failed to get decimals for ${acc.contractAddress}`);
+ logger.info(`Failed to get decimals for ${acc.contractAddress}`); // is this safe to fail and continue?
}
}
- log('decimals', decimals);
+ logger.info({ msg: 'decimals', decimals });
return `Owns ${humanizeComparator(
acc.returnValueTest.comparator
)} ${formatUnits(acc.returnValueTest.value, decimals)} of ${
@@ -284,9 +335,9 @@ export const humanizeEvmContractConditions = async ({
tokenList?: (any | string)[];
myWalletAddress?: string;
}): Promise => {
- log('humanizing evm contract conditions');
- log('myWalletAddress', myWalletAddress);
- log('evmContractConditions', evmContractConditions);
+ logger.info('humanizing evm contract conditions');
+ logger.info({ msg: 'myWalletAddress', myWalletAddress });
+ logger.info({ msg: 'evmContractConditions', evmContractConditions });
const promises = await Promise.all(
evmContractConditions.map(async (acc: any) => {
@@ -345,9 +396,9 @@ export const humanizeSolRpcConditions = async ({
tokenList?: (any | string)[];
myWalletAddress?: string;
}): Promise => {
- log('humanizing sol rpc conditions');
- log('myWalletAddress', myWalletAddress);
- log('solRpcConditions', solRpcConditions);
+ logger.info('humanizing sol rpc conditions');
+ logger.info({ msg: 'myWalletAddress', myWalletAddress });
+ logger.info({ msg: 'solRpcConditions', solRpcConditions });
const promises = await Promise.all(
solRpcConditions.map(async (acc: any) => {
@@ -419,9 +470,9 @@ export const humanizeCosmosConditions = async ({
tokenList?: (any | string)[];
myWalletAddress?: string;
}): Promise => {
- log('humanizing cosmos conditions');
- log('myWalletAddress', myWalletAddress);
- log('cosmosConditions', cosmosConditions);
+ logger.info('humanizing cosmos conditions');
+ logger.info({ msg: 'myWalletAddress', myWalletAddress });
+ logger.info({ msg: 'cosmosConditions', cosmosConditions });
const promises = await Promise.all(
cosmosConditions.map(async (acc: any) => {
diff --git a/packages/access-control-conditions/src/lib/validator.ts b/packages/access-control-conditions/src/lib/validator.ts
index ac4819d75d..78f6245a4a 100644
--- a/packages/access-control-conditions/src/lib/validator.ts
+++ b/packages/access-control-conditions/src/lib/validator.ts
@@ -1,5 +1,3 @@
-import { fromError, isZodErrorLike } from 'zod-validation-error';
-
import {
EvmBasicConditionsSchema,
EvmContractConditionsSchema,
@@ -7,7 +5,7 @@ import {
SolRpcConditionsSchema,
UnifiedConditionsSchema,
} from '@lit-protocol/access-control-conditions-schemas';
-import { InvalidArgumentException } from '@lit-protocol/constants';
+import { applySchemaWithValidation } from '@lit-protocol/schemas';
import {
AccessControlConditions,
EvmContractConditions,
@@ -16,30 +14,6 @@ import {
UnifiedAccessControlConditions,
} from '@lit-protocol/types';
-function formatZodError(accs: unknown, e: unknown): never {
- throw new InvalidArgumentException(
- {
- info: {
- accs,
- },
- cause: isZodErrorLike(e) ? fromError(e) : e,
- },
- 'Invalid access control conditions. Check error cause for more details.'
- );
-}
-
-async function validateSchema(
- accs: T,
- schema: { parse: (arg: unknown) => void }
-): Promise {
- try {
- schema.parse(accs);
- } catch (e) {
- formatZodError(accs, e);
- }
- return true;
-}
-
/**
* Validates Multiple access control conditions schema
* @param { MultipleAccessControlConditions } accs
@@ -47,7 +21,13 @@ async function validateSchema(
export const validateAccessControlConditions = async (
accs: MultipleAccessControlConditions
): Promise => {
- return validateSchema(accs, MultipleAccessControlConditionsSchema);
+ applySchemaWithValidation(
+ 'validateAccessControlConditions',
+ accs,
+ MultipleAccessControlConditionsSchema
+ );
+
+ return true;
};
/**
@@ -57,7 +37,13 @@ export const validateAccessControlConditions = async (
export const validateAccessControlConditionsSchema = async (
accs: AccessControlConditions
): Promise => {
- return validateSchema(accs, EvmBasicConditionsSchema);
+ applySchemaWithValidation(
+ 'validateAccessControlConditionsSchema',
+ accs,
+ EvmBasicConditionsSchema
+ );
+
+ return true;
};
/**
@@ -67,7 +53,13 @@ export const validateAccessControlConditionsSchema = async (
export const validateEVMContractConditionsSchema = async (
accs: EvmContractConditions
): Promise => {
- return validateSchema(accs, EvmContractConditionsSchema);
+ applySchemaWithValidation(
+ 'validateEVMContractConditionsSchema',
+ accs,
+ EvmContractConditionsSchema
+ );
+
+ return true;
};
/**
@@ -77,7 +69,13 @@ export const validateEVMContractConditionsSchema = async (
export const validateSolRpcConditionsSchema = async (
accs: SolRpcConditions
): Promise => {
- return validateSchema(accs, SolRpcConditionsSchema);
+ applySchemaWithValidation(
+ 'validateSolRpcConditionsSchema',
+ accs,
+ SolRpcConditionsSchema
+ );
+
+ return true;
};
/**
@@ -87,5 +85,11 @@ export const validateSolRpcConditionsSchema = async (
export const validateUnifiedAccessControlConditionsSchema = async (
accs: UnifiedAccessControlConditions
): Promise => {
- return validateSchema(accs, UnifiedConditionsSchema);
+ applySchemaWithValidation(
+ 'validateUnifiedAccessControlConditionsSchema',
+ accs,
+ UnifiedConditionsSchema
+ );
+
+ return true;
};
diff --git a/packages/auth-helpers/src/lib/generate-auth-sig.ts b/packages/auth-helpers/src/lib/generate-auth-sig.ts
index 49692f89c8..4cb56c3a5e 100644
--- a/packages/auth-helpers/src/lib/generate-auth-sig.ts
+++ b/packages/auth-helpers/src/lib/generate-auth-sig.ts
@@ -1,6 +1,8 @@
-import { AuthSig, SignerLike } from '@lit-protocol/types';
import { ethers } from 'ethers';
+import { InvalidArgumentException } from '@lit-protocol/constants';
+import { AuthSig, SignerLike } from '@lit-protocol/types';
+
/**
* Generate an AuthSig object using the signer.
*
@@ -26,7 +28,16 @@ export const generateAuthSig = async ({
algo?: 'ed25519';
}): Promise => {
if (!signer?.signMessage) {
- throw new Error('signer does not have a signMessage method');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signer,
+ address,
+ algo,
+ },
+ },
+ 'signer does not have a signMessage method'
+ );
}
const signature = await signer.signMessage(toSign);
@@ -41,7 +52,16 @@ export const generateAuthSig = async ({
// If address is still not available, throw an error
if (!address) {
- throw new Error('address is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signer,
+ address,
+ algo,
+ },
+ },
+ 'address is required'
+ );
}
return {
diff --git a/packages/auth-helpers/src/lib/models.ts b/packages/auth-helpers/src/lib/models.ts
index 6a59af56b0..22b63326c9 100644
--- a/packages/auth-helpers/src/lib/models.ts
+++ b/packages/auth-helpers/src/lib/models.ts
@@ -1,13 +1,3 @@
-import { LIT_ABILITY_VALUES } from '@lit-protocol/constants';
-import { ILitResource } from '@lit-protocol/types';
-
-// This is here to prevent circular dependency issue
-export interface AuthSig {
- sig: any;
- derivedVia: string;
- signedMessage: string;
- address: string;
-}
export type PlainJSON =
| boolean
| number
@@ -18,18 +8,3 @@ export type AttenuationsObject = {
[key: string]: { [key: string]: Array };
};
export type CID = string;
-
-/**
- * A LIT resource ability is a combination of a LIT resource and a LIT ability.
- * It specifies which LIT specific ability is being requested to be performed
- * on the specified LIT resource.
- *
- * @description This object does NOT guarantee compatibility between the
- * specified LIT resource and the specified LIT ability, and will be validated by
- * the LIT-internal systems.
- */
-export type LitResourceAbilityRequest = {
- resource: ILitResource;
- ability: LIT_ABILITY_VALUES;
- data?: any;
-};
diff --git a/packages/auth-helpers/src/lib/recap/recap-session-capability-object.spec.ts b/packages/auth-helpers/src/lib/recap/recap-session-capability-object.spec.ts
index b2884d1fc9..c506a21825 100644
--- a/packages/auth-helpers/src/lib/recap/recap-session-capability-object.spec.ts
+++ b/packages/auth-helpers/src/lib/recap/recap-session-capability-object.spec.ts
@@ -1,14 +1,16 @@
import { SiweMessage } from 'siwe';
+
import {
LIT_ABILITY,
LIT_RESOURCE_PREFIX,
LIT_NAMESPACE,
LIT_RECAP_ABILITY,
} from '@lit-protocol/constants';
+
import { LitAccessControlConditionResource } from '../resources';
import { RecapSessionCapabilityObject } from './recap-session-capability-object';
-const isClass = (v: any) => {
+const isClass = (v: unknown) => {
return typeof v === 'function' && /^\s*class\s+/.test(v.toString());
};
diff --git a/packages/auth-helpers/src/lib/recap/recap-session-capability-object.ts b/packages/auth-helpers/src/lib/recap/recap-session-capability-object.ts
index e9956278e7..847dc69d67 100644
--- a/packages/auth-helpers/src/lib/recap/recap-session-capability-object.ts
+++ b/packages/auth-helpers/src/lib/recap/recap-session-capability-object.ts
@@ -1,24 +1,27 @@
+import { SiweMessage } from 'siwe';
+import { Recap } from 'siwe-recap';
+
import {
InvalidArgumentException,
LIT_ABILITY_VALUES,
} from '@lit-protocol/constants';
-import { ILitResource, ISessionCapabilityObject } from '@lit-protocol/types';
-import depd from 'depd';
-import { SiweMessage } from 'siwe';
-import { Recap } from 'siwe-recap';
-import { AttenuationsObject, CID as CIDString, PlainJSON } from '../models';
-import { sanitizeSiweMessage } from '../siwe/siwe-helper';
+import {
+ AttenuationsObject,
+ CID as CIDString,
+ DefinedJson,
+ ILitResource,
+ ISessionCapabilityObject,
+} from '@lit-protocol/types';
+
import { getRecapNamespaceAndAbility } from './utils';
+import { sanitizeSiweMessage } from '../siwe/siwe-helper';
-const deprecated = depd('lit-js-sdk:auth-recap:session-capability-object');
+export type Restriction = Record;
export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
private _inner: Recap;
- constructor(
- att: AttenuationsObject = {},
- prf: Array | Array = []
- ) {
+ constructor(att: AttenuationsObject = {}, prf: CIDString[] | string[] = []) {
this._inner = new Recap(att, prf);
}
@@ -26,7 +29,7 @@ export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
const recap = Recap.decode_urn(encoded);
return new this(
recap.attenuations,
- recap.proofs.map((cid: any) => cid.toString())
+ recap.proofs.map((cid) => cid.toString())
);
}
@@ -34,7 +37,7 @@ export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
const recap = Recap.extract_and_verify(siwe);
return new this(
recap.attenuations,
- recap.proofs.map((cid: any) => cid.toString())
+ recap.proofs.map((cid) => cid.toString())
);
}
@@ -42,8 +45,8 @@ export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
return this._inner.attenuations;
}
- get proofs(): Array {
- return this._inner.proofs.map((cid: any) => cid.toString());
+ get proofs(): CIDString[] {
+ return this._inner.proofs.map((cid) => cid.toString());
}
get statement(): string {
@@ -56,9 +59,9 @@ export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
addAttenuation(
resource: string,
- namespace: string = '*',
- name: string = '*',
- restriction: { [key: string]: PlainJSON } = {}
+ namespace = '*',
+ name = '*',
+ restriction: Restriction = {}
) {
return this._inner.addAttenuation(resource, namespace, name, restriction);
}
@@ -75,7 +78,7 @@ export class RecapSessionCapabilityObject implements ISessionCapabilityObject {
addCapabilityForResource(
litResource: ILitResource,
ability: LIT_ABILITY_VALUES,
- data = {}
+ data: Restriction = {}
): void {
// Validate Lit ability is compatible with the Lit resource.
if (!litResource.isValidLitAbility(ability)) {
diff --git a/packages/auth-helpers/src/lib/resources.ts b/packages/auth-helpers/src/lib/resources.ts
index 1c729f4bab..a5a494a9ce 100644
--- a/packages/auth-helpers/src/lib/resources.ts
+++ b/packages/auth-helpers/src/lib/resources.ts
@@ -7,7 +7,6 @@ import {
LIT_RESOURCE_PREFIX_VALUES,
} from '@lit-protocol/constants';
import { AccessControlConditions, ILitResource } from '@lit-protocol/types';
-import { uint8arrayToString } from '@lit-protocol/uint8arrays';
import { formatPKPResource } from './utils';
abstract class LitResourceBase {
@@ -73,9 +72,8 @@ export class LitAccessControlConditionResource
}
const hashedAccs = await hashAccessControlConditions(accs);
- const hashedAccsStr = uint8arrayToString(
- new Uint8Array(hashedAccs),
- 'base16'
+ const hashedAccsStr = Buffer.from(new Uint8Array(hashedAccs)).toString(
+ 'hex'
);
const resourceString = `${hashedAccsStr}/${dataToEncryptHash}`;
diff --git a/packages/auth-helpers/src/lib/session-capability-object.ts b/packages/auth-helpers/src/lib/session-capability-object.ts
index babdd3cc75..4e766e559c 100644
--- a/packages/auth-helpers/src/lib/session-capability-object.ts
+++ b/packages/auth-helpers/src/lib/session-capability-object.ts
@@ -1,5 +1,7 @@
import { SiweMessage } from 'siwe';
+
import { ISessionCapabilityObject } from '@lit-protocol/types';
+
import { AttenuationsObject, CID } from './models';
import { RecapSessionCapabilityObject } from './recap/recap-session-capability-object';
@@ -19,7 +21,7 @@ import { RecapSessionCapabilityObject } from './recap/recap-session-capability-o
*/
export function newSessionCapabilityObject(
attenuations: AttenuationsObject = {},
- proof: Array = []
+ proof: CID[] = []
): ISessionCapabilityObject {
return new RecapSessionCapabilityObject(attenuations, proof);
}
diff --git a/packages/auth-helpers/src/lib/siwe/create-siwe-message.ts b/packages/auth-helpers/src/lib/siwe/create-siwe-message.ts
index 55c5f6525a..c50faace1d 100644
--- a/packages/auth-helpers/src/lib/siwe/create-siwe-message.ts
+++ b/packages/auth-helpers/src/lib/siwe/create-siwe-message.ts
@@ -1,5 +1,6 @@
import { SiweMessage } from 'siwe';
+import { InvalidArgumentException } from '@lit-protocol/constants';
import {
BaseSiweMessage,
CapacityDelegationFields,
@@ -23,7 +24,14 @@ export const createSiweMessage = async (
): Promise => {
// -- validations
if (!params.walletAddress) {
- throw new Error('walletAddress is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ params,
+ },
+ },
+ 'walletAddress is required'
+ );
}
const ONE_WEEK_FROM_NOW = new Date(
@@ -62,11 +70,12 @@ export const createSiweMessage = async (
// resource: new LitRLIResource(ccParams.capacityTokenId ?? '*'),
// ability: LIT_ABILITY.RateLimitIncreaseAuth,
- // @ts-ignore - TODO: new resource to be used
+ // @ts-expect-error - TODO: new resource to be used
resource: null,
- // @ts-ignore - TODO: new ability to be used
+ // @ts-expect-error - TODO: new ability to be used
ability: null,
+ // @ts-expect-error Complaining because of index signature in destination
data: capabilities,
},
];
@@ -75,7 +84,14 @@ export const createSiweMessage = async (
// -- add recap resources if needed
if (params.resources) {
if (!params.litNodeClient) {
- throw new Error('litNodeClient is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ params,
+ },
+ },
+ 'litNodeClient is required'
+ );
}
siweMessage = await addRecapToSiweMessage({
@@ -112,7 +128,14 @@ export const createSiweMessageWithCapacityDelegation = async (
params: WithCapacityDelegation
) => {
if (!params.litNodeClient) {
- throw new Error('litNodeClient is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ params,
+ },
+ },
+ 'litNodeClient is required'
+ );
}
return createSiweMessage({
diff --git a/packages/auth-helpers/src/lib/siwe/siwe-helper.ts b/packages/auth-helpers/src/lib/siwe/siwe-helper.ts
index 8a4f63404c..918d2bc6d8 100644
--- a/packages/auth-helpers/src/lib/siwe/siwe-helper.ts
+++ b/packages/auth-helpers/src/lib/siwe/siwe-helper.ts
@@ -1,5 +1,9 @@
import { SiweMessage } from 'siwe';
+import {
+ InvalidArgumentException,
+ UnknownError,
+} from '@lit-protocol/constants';
import {
CapacityDelegationFields,
CapacityDelegationRequest,
@@ -8,6 +12,7 @@ import {
ISessionCapabilityObject,
LitResourceAbilityRequest,
} from '@lit-protocol/types';
+
import { RecapSessionCapabilityObject } from '../recap/recap-session-capability-object';
/**
@@ -87,11 +92,27 @@ export const addRecapToSiweMessage = async ({
litNodeClient: ILitNodeClient;
}) => {
if (!resources || resources.length < 1) {
- throw new Error('resources is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ resources,
+ siweMessage,
+ },
+ },
+ 'resources is required'
+ );
}
if (!litNodeClient) {
- throw new Error('litNodeClient is required');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ resources,
+ siweMessage,
+ },
+ },
+ 'litNodeClient is required'
+ );
}
for (const request of resources) {
@@ -102,7 +123,7 @@ export const addRecapToSiweMessage = async ({
recapObject.addCapabilityForResource(
request.resource,
request.ability,
- request.data || null
+ request.data
);
const verified = recapObject.verifyCapabilitiesForResource(
@@ -111,7 +132,13 @@ export const addRecapToSiweMessage = async ({
);
if (!verified) {
- throw new Error(
+ throw new UnknownError(
+ {
+ info: {
+ recapObject,
+ request,
+ },
+ },
`Failed to verify capabilities for resource: "${request.resource}" and ability: "${request.ability}`
);
}
diff --git a/packages/auth-helpers/src/lib/utils.ts b/packages/auth-helpers/src/lib/utils.ts
index da935f6a7c..f65f33faa6 100644
--- a/packages/auth-helpers/src/lib/utils.ts
+++ b/packages/auth-helpers/src/lib/utils.ts
@@ -1,3 +1,5 @@
+import { InvalidArgumentException } from '@lit-protocol/constants';
+
/**
* Formats the resource ID to a 32-byte hex string.
*
@@ -21,7 +23,14 @@ export function formatPKPResource(resource: string): string {
// Throw an error if the resource length exceeds 64 characters
if (fixedResource.length > 64) {
- throw new Error('Resource ID exceeds 64 characters (32 bytes) in length.');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ resource,
+ },
+ },
+ 'Resource ID exceeds 64 characters (32 bytes) in length.'
+ );
}
/**
diff --git a/packages/auth/src/lib/auth-manager.ts b/packages/auth/src/lib/auth-manager.ts
index 4f5fd9d750..8ce1d540d0 100644
--- a/packages/auth/src/lib/auth-manager.ts
+++ b/packages/auth/src/lib/auth-manager.ts
@@ -1,23 +1,12 @@
-import { nacl } from '@lit-protocol/nacl';
-import { SessionKeyPair } from '@lit-protocol/types';
-import { uint8arrayToString } from '@lit-protocol/uint8arrays';
+import { generateSessionKeyPair } from '@lit-protocol/crypto';
import type { LitAuthStorageProvider } from './storage/types';
-import type { LitAuthData } from '@lit-protocol/auth';
+import type { LitAuthData } from './types';
interface LitAuthManagerConfig {
storage: LitAuthStorageProvider;
}
-function generateSessionKeyPair(): SessionKeyPair {
- const keyPair = nacl.sign.keyPair();
-
- return {
- publicKey: uint8arrayToString(keyPair.publicKey, 'base16'),
- secretKey: uint8arrayToString(keyPair.secretKey, 'base16'),
- };
-}
-
async function tryGetCachedAuthData() {
// Use `storage` to see if there is cached auth data
// If error thrown trying to get it, error to caller or ??
diff --git a/packages/auth/src/lib/authenticators/WebAuthnAuthenticator.ts b/packages/auth/src/lib/authenticators/WebAuthnAuthenticator.ts
index f45ded2b6c..957579b06f 100644
--- a/packages/auth/src/lib/authenticators/WebAuthnAuthenticator.ts
+++ b/packages/auth/src/lib/authenticators/WebAuthnAuthenticator.ts
@@ -8,6 +8,7 @@ import { ethers } from 'ethers';
import {
AUTH_METHOD_TYPE,
+ InvalidArgumentException,
RemovedFunctionError,
UnknownError,
WrongParamFormat,
@@ -278,7 +279,12 @@ function assertAuthenticationResponse(
.credentialPublicKey instanceof Buffer
)
) {
- throw new Error(
+ throw new InvalidArgumentException(
+ {
+ info: {
+ authenticationResponse,
+ },
+ },
'authenticationResponse does not match the expected structure: { attestedCredentialData: { credentialPublicKey: Buffer } }'
);
}
diff --git a/packages/auth/src/lib/authenticators/metamask/MetamaskAuthenticator.ts b/packages/auth/src/lib/authenticators/metamask/MetamaskAuthenticator.ts
index 6b4c43819d..46afd01b1c 100644
--- a/packages/auth/src/lib/authenticators/metamask/MetamaskAuthenticator.ts
+++ b/packages/auth/src/lib/authenticators/metamask/MetamaskAuthenticator.ts
@@ -9,7 +9,7 @@ import {
WrongParamFormat,
} from '@lit-protocol/constants';
import { LitNodeClient } from '@lit-protocol/lit-node-client';
-import { log } from '@lit-protocol/misc';
+import { getChildLogger } from '@lit-protocol/logger';
import {
AuthMethod,
AuthSig,
@@ -27,6 +27,9 @@ interface DomainAndOrigin {
}
export class MetamaskAuthenticator extends BaseAuthenticator {
+ private static readonly _logger = getChildLogger({
+ module: 'MetamaskAuthenticator',
+ });
/**
* The domain from which the signing request is made
*/
@@ -51,7 +54,7 @@ export class MetamaskAuthenticator extends BaseAuthenticator {
domain = options.domain || window.location.hostname;
origin = options.origin || window.location.origin;
} catch (e) {
- log(
+ MetamaskAuthenticator._logger.error(
'⚠️ Error getting "domain" and "origin" from window object, defaulting to "localhost" and "http://localhost"'
);
domain = options.domain || 'localhost';
diff --git a/packages/auth/src/lib/authenticators/metamask/eth.ts b/packages/auth/src/lib/authenticators/metamask/eth.ts
index fc32779fbd..79dceffc3b 100644
--- a/packages/auth/src/lib/authenticators/metamask/eth.ts
+++ b/packages/auth/src/lib/authenticators/metamask/eth.ts
@@ -12,34 +12,27 @@ import depd from 'depd';
import { ethers } from 'ethers';
import { getAddress } from 'ethers/lib/utils';
import { SiweMessage } from 'siwe';
-import * as nacl from 'tweetnacl';
-import * as naclUtil from 'tweetnacl-util';
import {
ConstantValues,
ConstantKeys,
- EITHER_TYPE,
- ELeft,
- ERight,
- IEither,
+ Environment,
InvalidSignatureError,
LIT_CHAINS,
LOCAL_STORAGE_KEYS,
- LocalStorageItemNotFoundException,
UnknownError,
UnsupportedChainException,
WrongNetworkException,
WrongParamFormat,
LIT_CHAINS_KEYS,
} from '@lit-protocol/constants';
+import { validateSessionSig } from '@lit-protocol/lit-node-client';
+import { getChildLogger, logger } from '@lit-protocol/logger';
import {
- isBrowser,
- isNode,
- log,
- numberToHex,
- validateSessionSig,
-} from '@lit-protocol/misc';
-import { getStorageItem } from '@lit-protocol/misc-browser';
+ getStorageItem,
+ setStorageItem,
+ removeStorageItem,
+} from '@lit-protocol/misc-browser';
import { AuthCallbackParams, AuthSig } from '@lit-protocol/types';
import LitConnectModal from './connect-modal/modal';
@@ -163,35 +156,27 @@ export const chainHexIdToChainName = (chainHexId: string): void | string => {
* Get chain id of the current network
* @param { string } chain
* @param { Web3Provider } web3
- * @returns { Promise }
+ * @returns { Promise }
*/
export const getChainId = async (
chain: string,
web3: Web3Provider
-): Promise> => {
- let resultOrError: IEither;
-
+): Promise => {
try {
- const resp = await web3.getNetwork();
- resultOrError = ERight(resp.chainId);
+ const network = await web3.getNetwork();
+ return network.chainId;
} catch (e) {
- // couldn't get chainId. throw the incorrect network error
- log('getNetwork threw an exception', e);
-
- resultOrError = ELeft(
- new WrongNetworkException(
- {
- info: {
- chain,
- },
+ throw new WrongNetworkException(
+ {
+ info: {
+ chain,
},
- `Incorrect network selected. Please switch to the %s network in your wallet and try again.`,
- chain
- )
+ cause: e,
+ },
+ `Incorrect network selected. Please switch to the %s network in your wallet and try again.`,
+ chain
);
}
-
- return resultOrError;
};
/**
@@ -220,7 +205,10 @@ export function isSignedMessageExpired(signedMessage: string) {
*
* @returns { boolean }
*/
-export const getMustResign = (authSig: AuthSig, resources: any): boolean => {
+export const getMustResign = (
+ authSig: AuthSig,
+ resources: unknown
+): boolean => {
let mustResign!: boolean;
// if it's not expired, then we don't need to resign
@@ -230,23 +218,30 @@ export const getMustResign = (authSig: AuthSig, resources: any): boolean => {
try {
const parsedSiwe = new SiweMessage(authSig.signedMessage);
- log('parsedSiwe.resources', parsedSiwe.resources);
+ logger.info({
+ msg: 'parsedSiwe.resources',
+ resources: parsedSiwe.resources,
+ });
if (JSON.stringify(parsedSiwe.resources) !== JSON.stringify(resources)) {
- log(
+ logger.info(
'signing auth message because resources differ from the resources in the auth sig'
);
mustResign = true;
}
if (parsedSiwe.address !== getAddress(parsedSiwe.address)) {
- 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.'
+ logger.info(
+ '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);
+ } catch (error) {
+ logger.error({
+ function: 'getMustResign',
+ msg: 'error parsing siwe sig. Making the user sign again',
+ error,
+ });
mustResign = true;
}
@@ -293,8 +288,8 @@ export const connectWeb3 = async ({
walletConnectProjectId,
}: ConnectWeb3): Promise => {
// -- check if it's nodejs
- if (isNode()) {
- log('connectWeb3 is not supported in nodejs.');
+ if (Environment.isNode) {
+ logger.info('connectWeb3 is not supported in nodejs.');
return { web3: null, account: null };
}
@@ -317,20 +312,20 @@ export const connectWeb3 = async ({
},
};
- if (isBrowser()) {
+ if (Environment.isBrowser) {
litWCProvider = wcProvider;
}
}
- log('getting provider via lit connect modal');
+ logger.info('getting provider via lit connect modal');
const dialog = new LitConnectModal({ providerOptions });
const provider = await dialog.getWalletProvider();
- log('got provider');
+ logger.info('got provider');
- // @ts-ignore
+ // @ts-expect-error provider is not typed
const web3 = new Web3Provider(provider);
// trigger metamask popup
@@ -338,19 +333,19 @@ export const connectWeb3 = async ({
deprecated(
'@deprecated soon to be removed. - trying to enable provider. this will trigger the metamask popup.'
);
- // @ts-ignore
+ // @ts-expect-error provider is not typed
await provider.enable();
- } catch (e) {
- 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
- );
+ } catch (error) {
+ logger.info({
+ msg: "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, those other methods will be tried.",
+ error,
+ });
}
- log('listing accounts');
+ logger.info('listing accounts');
const accounts = await web3.listAccounts();
- log('accounts', accounts);
+ logger.info({ msg: 'accounts', accounts });
const account = ethers.utils.getAddress(accounts[0]);
return { web3, account };
@@ -359,23 +354,22 @@ export const connectWeb3 = async ({
/**
* @browserOnly
* Delete any saved AuthSigs from local storage. Takes no params and returns
- * nothing. This will also clear out the WalletConnect cache in local storage.
+ * nothing. This will also clear out the WalletConnect cache in localstorage.
* We often run this function as a result of the user pressing a "Logout" button.
*
* @return { void }
*/
export const disconnectWeb3 = (): void => {
- if (isNode()) {
- log('disconnectWeb3 is not supported in nodejs.');
+ if (Environment.isNode) {
+ logger.info('disconnectWeb3 is not supported in nodejs.');
return;
}
- // @ts-ignore
- if (isBrowser() && litWCProvider) {
+ if (Environment.isBrowser && litWCProvider) {
try {
litWCProvider.disconnect();
} catch (err) {
- log(
+ logger.info(
'Attempted to disconnect global WalletConnectProvider for lit-connect-modal',
err
);
@@ -384,11 +378,8 @@ export const disconnectWeb3 = (): void => {
const storage = LOCAL_STORAGE_KEYS;
- localStorage.removeItem(storage.AUTH_SIGNATURE);
- localStorage.removeItem(storage.AUTH_SOL_SIGNATURE);
- localStorage.removeItem(storage.AUTH_COSMOS_SIGNATURE);
- localStorage.removeItem(storage.WEB3_PROVIDER);
- localStorage.removeItem(storage.WALLET_SIGNATURE);
+ removeStorageItem(storage.AUTH_SIGNATURE);
+ removeStorageItem(storage.WALLET_SIGNATURE);
};
/**
@@ -407,10 +398,11 @@ export const checkAndSignEVMAuthMessage = async ({
walletConnectProjectId,
nonce,
}: AuthCallbackParams): Promise => {
- // -- check if it's nodejs
- if (isNode()) {
- log(
- 'checkAndSignEVMAuthMessage is not supported in nodejs. You can create a SIWE on your own using the SIWE package.'
+ const logger = getChildLogger({ function: 'checkAndSignEVMAuthMessage' });
+ // -- check if it's Node.js
+ if (Environment.isNode) {
+ logger.info(
+ 'checkAndSignEVMAuthMessage is not supported in nodejs. You can create a SIWE on your own using the SIWE package.'
);
return {
sig: '',
@@ -421,7 +413,7 @@ export const checkAndSignEVMAuthMessage = async ({
}
// --- scoped methods ---
- const _throwIncorrectNetworkError = (error: any) => {
+ const _throwIncorrectNetworkError = (error: any): never => {
if (error.code === WALLET_ERROR.NO_SUCH_METHOD) {
throw new WrongNetworkException(
{
@@ -445,45 +437,28 @@ export const checkAndSignEVMAuthMessage = async ({
walletConnectProjectId,
});
- log(`got web3 and account: ${account}`);
+ logger.info(`got web3 and account: ${account}`);
// -- 2. prepare all required variables
- const currentChainIdOrError = await getChainId(chain, web3);
+ let currentChainId = await getChainId(chain, web3);
const selectedChainId: number = selectedChain.chainId;
- const selectedChainIdHex: string = numberToHex(selectedChainId);
- let authSigOrError = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
-
- 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) {
- throw new UnknownError(
- {
- info: {
- chainId: chain,
- },
- cause: currentChainIdOrError.result,
- },
- 'Unknown error when getting chain id'
- );
- }
-
- log('chainId from web3', currentChainIdOrError);
- log(
- `checkAndSignAuthMessage with chainId ${currentChainIdOrError} and chain set to ${chain} and selectedChain is `,
- selectedChain
- );
+ const selectedChainIdHex: string = `0x${selectedChainId.toString(16)}`;
+
+ logger.info({ msg: 'currentChainId', currentChainId });
+ logger.info({ msg: 'selectedChainId', selectedChainId });
+ logger.info({ msg: 'selectedChainIdHex', selectedChainIdHex });
+ logger.info({
+ msg: `checkAndSignAuthMessage with chainId ${currentChainId} and chain set to ${chain} and selectedChain is `,
+ selectedChain,
+ });
// -- 4. case: (current chain id is NOT equal to selected chain) AND is set to switch chain
- if (currentChainIdOrError.result !== selectedChainId && switchChain) {
+ if (currentChainId !== selectedChainId && switchChain) {
const provider = web3.provider as any;
// -- (case) if able to switch chain id
try {
- log('trying to switch to chainId', selectedChainIdHex);
+ logger.info({ msg: 'trying to switch to chainId', selectedChainIdHex });
await provider.request({
method: 'wallet_switchEthereumChain',
@@ -492,7 +467,7 @@ export const checkAndSignEVMAuthMessage = async ({
// -- (case) if unable to switch chain
} catch (switchError: any) {
- log('error switching to chainId', switchError);
+ logger.error({ msg: 'error switching to chainId', switchError });
// -- (error case)
if (
@@ -517,7 +492,7 @@ export const checkAndSignEVMAuthMessage = async ({
method: 'wallet_addEthereumChain',
params: data,
});
- } catch (addError: any) {
+ } catch (addError) {
_throwIncorrectNetworkError(addError);
}
} else {
@@ -526,17 +501,27 @@ export const checkAndSignEVMAuthMessage = async ({
}
// we may have switched the chain to the selected chain. set the chainId accordingly
- currentChainIdOrError.result = selectedChain.chainId;
+ currentChainId = selectedChain.chainId;
}
+ let authSig: AuthSig | undefined;
// -- 5. case: Lit auth signature is NOT in the local storage
- log('checking if sig is in local storage');
-
- if (authSigOrError.type === EITHER_TYPE.ERROR) {
- log('signing auth message because sig is not in local storage');
+ try {
+ logger.info('checking if sig is in local storage');
+ const authSigString = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
+ authSig = JSON.parse(authSigString);
+ } catch (error) {
+ logger.warn({
+ msg: 'Could not get sig from local storage',
+ error,
+ });
+ }
+ if (!authSig) {
try {
- const authSig = await _signAndGetAuth({
+ logger.info('signing auth message because sig is not in local storage');
+
+ authSig = await _signAndGetAuth({
web3,
account,
chainId: selectedChain.chainId,
@@ -545,12 +530,7 @@ export const checkAndSignEVMAuthMessage = async ({
uri,
nonce,
});
-
- authSigOrError = {
- type: EITHER_TYPE.SUCCESS,
- result: JSON.stringify(authSig),
- };
- } catch (e: any) {
+ } catch (e) {
throw new UnknownError(
{
info: {
@@ -566,20 +546,14 @@ export const checkAndSignEVMAuthMessage = async ({
'Could not get authenticated message'
);
}
-
- // Log new authSig
- log('5. authSigOrError:', authSigOrError);
}
// -- 6. case: Lit auth signature IS in the local storage
- const authSigString: string = authSigOrError.result;
- let authSig = JSON.parse(authSigString);
-
- log('6. authSig:', authSig);
+ logger.info({ msg: 'authSig', authSig });
// -- 7. case: when we are NOT on the right wallet address
if (account.toLowerCase() !== authSig.address.toLowerCase()) {
- log(
+ logger.info(
'signing auth message because account is not the same as the address in the auth sig'
);
authSig = await _signAndGetAuth({
@@ -591,7 +565,7 @@ export const checkAndSignEVMAuthMessage = async ({
uri,
nonce,
});
- log('7. authSig:', authSig);
+ logger.info({ msg: '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 {
@@ -608,7 +582,7 @@ export const checkAndSignEVMAuthMessage = async ({
nonce,
});
}
- log('8. mustResign:', mustResign);
+ logger.info({ msg: 'mustResign', mustResign });
}
// -- 9. finally, if the authSig is expired, re-sign
@@ -617,10 +591,10 @@ export const checkAndSignEVMAuthMessage = async ({
if (isSignedMessageExpired(authSig.signedMessage) || !checkAuthSig.isValid) {
if (!checkAuthSig.isValid) {
- log(`Invalid AuthSig: ${checkAuthSig.errors.join(', ')}`);
+ logger.info(`Invalid AuthSig: ${checkAuthSig.errors.join(', ')}`);
}
- log('9. authSig expired!, resigning..');
+ logger.info('authSig expired!, resigning..');
authSig = await _signAndGetAuth({
web3,
@@ -659,23 +633,8 @@ const _signAndGetAuth = async ({
nonce,
});
- const authSigOrError = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
-
- if (authSigOrError.type === 'ERROR') {
- throw new LocalStorageItemNotFoundException(
- {
- info: {
- storageKey: LOCAL_STORAGE_KEYS.AUTH_SIGNATURE,
- },
- },
- 'Failed to get authSig from local storage'
- );
- }
-
- const authSig: AuthSig =
- typeof authSigOrError.result === 'string'
- ? JSON.parse(authSigOrError.result)
- : authSigOrError.result;
+ const authSigString = getStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
+ const authSig: AuthSig = JSON.parse(authSigString);
return authSig;
};
@@ -698,8 +657,8 @@ export const signAndSaveAuthMessage = async ({
nonce,
}: signAndSaveAuthParams): Promise => {
// check if it's nodejs
- if (isNode()) {
- log('checkAndSignEVMAuthMessage is not supported in nodejs.');
+ if (Environment.isNode) {
+ logger.info('checkAndSignEVMAuthMessage is not supported in nodejs.');
return {
sig: '',
derivedVia: '',
@@ -747,25 +706,10 @@ export const signAndSaveAuthMessage = async ({
};
// -- 4. store auth and a keypair in localstorage for communication with sgx
- if (isBrowser()) {
- localStorage.setItem(
- LOCAL_STORAGE_KEYS.AUTH_SIGNATURE,
- JSON.stringify(authSig)
- );
- }
- const commsKeyPair = nacl.box.keyPair();
-
- if (isBrowser()) {
- localStorage.setItem(
- LOCAL_STORAGE_KEYS.KEY_PAIR,
- JSON.stringify({
- publicKey: naclUtil.encodeBase64(commsKeyPair.publicKey),
- secretKey: naclUtil.encodeBase64(commsKeyPair.secretKey),
- })
- );
+ if (Environment.isBrowser) {
+ setStorageItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE, JSON.stringify(authSig));
}
- log(`generated and saved ${LOCAL_STORAGE_KEYS.KEY_PAIR}`);
return authSig;
};
@@ -782,9 +726,9 @@ export const signMessage = async ({
web3,
account,
}: SignMessageParams): Promise => {
- // check if it's nodejs
- if (isNode()) {
- log('signMessage is not supported in nodejs.');
+ // check if it's Node.js
+ if (Environment.isNode) {
+ logger.info('signMessage is not supported in nodejs.');
return {
signature: '',
address: '',
@@ -793,22 +737,22 @@ export const signMessage = async ({
// -- validate
if (!web3 || !account) {
- log(`web3: ${web3} OR ${account} not found. Connecting web3..`);
+ logger.info(`web3: ${web3} OR ${account} not found. Connecting web3..`);
const res = await connectWeb3({ chainId: 1 });
web3 = res.web3;
account = res.account;
}
- log('pausing...');
+ logger.info('pausing...');
await new Promise((resolve) => setTimeout(resolve, 500));
- log('signing with ', account);
+ logger.info({ msg: 'signing with ', account });
const signature = await signMessageAsync(web3.getSigner(), account, body);
const address = verifyMessage(body, signature).toLowerCase();
- log('Signature: ', signature);
- log('recovered address: ', address);
+ logger.info({ msg: 'Signature', signature });
+ logger.info({ msg: '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.`;
@@ -845,8 +789,8 @@ export const signMessageAsync = async (
message: string
): Promise => {
// check if it's nodejs
- if (isNode()) {
- log('signMessageAsync is not supported in nodejs.');
+ if (Environment.isNode) {
+ logger.warn('signMessageAsync is not supported in nodejs.');
return null;
}
@@ -854,23 +798,25 @@ export const signMessageAsync = async (
if (signer instanceof JsonRpcSigner) {
try {
- log('Signing with personal_sign');
+ logger.info('Signing with personal_sign');
const signature = await signer.provider.send('personal_sign', [
hexlify(messageBytes),
address.toLowerCase(),
]);
return signature;
- } catch (e: any) {
- log(
- 'Signing with personal_sign failed, trying signMessage as a fallback'
- );
- if (e.message.includes('personal_sign')) {
+ } catch (error: any) {
+ logger.warn({
+ function: 'signMessageAsync',
+ msg: 'Signing with personal_sign failed, trying signMessage as a fallback',
+ error,
+ });
+ if (error.message.includes('personal_sign')) {
return await signer.signMessage(messageBytes);
}
- throw e;
+ throw error;
}
} else {
- log('signing with signMessage');
+ logger.info('signing with signMessage');
return await signer.signMessage(messageBytes);
}
};
diff --git a/packages/auth/src/lib/authenticators/stytch/StytchOtpAuthenticator.ts b/packages/auth/src/lib/authenticators/stytch/StytchOtpAuthenticator.ts
index 45659b2631..6eab48436f 100644
--- a/packages/auth/src/lib/authenticators/stytch/StytchOtpAuthenticator.ts
+++ b/packages/auth/src/lib/authenticators/stytch/StytchOtpAuthenticator.ts
@@ -125,7 +125,6 @@ export class StytchOtpAuthenticator extends BaseAuthenticator {
}
const body = Buffer.from(parts[1], 'base64');
const parsedBody: StytchToken = JSON.parse(body.toString('ascii'));
- console.log('JWT body: ', parsedBody);
return parsedBody;
}
}
diff --git a/packages/auth/src/lib/authenticators/utils.ts b/packages/auth/src/lib/authenticators/utils.ts
index e32fadd17b..78c912f9d6 100644
--- a/packages/auth/src/lib/authenticators/utils.ts
+++ b/packages/auth/src/lib/authenticators/utils.ts
@@ -5,7 +5,6 @@ import {
InvalidArgumentException,
UnknownError,
} from '@lit-protocol/constants';
-import { getLoggerbyId } from '@lit-protocol/misc';
import { AuthMethod, LoginUrlParams } from '@lit-protocol/types';
import { DiscordAuthenticator } from './DiscordAuthenticator';
@@ -18,17 +17,6 @@ import { WebAuthnAuthenticator } from './WebAuthnAuthenticator';
export const STATE_PARAM_KEY = 'lit-state-param';
export const LIT_LOGIN_GATEWAY = 'https://login.litgateway.com';
-/**
- * Check if OAuth provider is supported
- *
- * @param provider {string} - Auth provider name
- *
- * @returns {boolean} - True if provider is supported
- */
-export function isSocialLoginSupported(provider: string): boolean {
- return ['google', 'discord'].includes(provider);
-}
-
/**
* Create login url using the parameters provided as arguments when initializing the client
*
@@ -79,11 +67,11 @@ function getLoginRoute(provider: string): string {
/**
* Create query params string from given object
*
- * @param params {any} - Object of query params
+ * @param params {Record} - Object of query params
*
* @returns {string} - Query string
*/
-function createQueryParams(params: any): string {
+function createQueryParams(params: Record): string {
// Strip undefined values from params
const filteredParams = Object.keys(params)
.filter((k) => typeof params[k] !== 'undefined')
@@ -335,11 +323,6 @@ export function unparse(buf: any) {
);
}
-export function log(...args: any) {
- const logger = getLoggerbyId('auth-client');
- logger.debug(...args);
-}
-
/**
* Retrieves the authentication ID based on the provided authentication method.
*
@@ -374,7 +357,6 @@ export async function getAuthIdByAuthMethod(
authId = await StytchAuthFactorOtpAuthenticator.authMethodId(authMethod);
break;
default:
- log(`unsupported AuthMethodType: ${authMethod.authMethodType}`);
throw new InvalidArgumentException(
{
info: {
diff --git a/packages/auth/src/lib/authenticators/validators.spec.ts b/packages/auth/src/lib/authenticators/validators.spec.ts
index 91d1419fbb..f821db1bc1 100644
--- a/packages/auth/src/lib/authenticators/validators.spec.ts
+++ b/packages/auth/src/lib/authenticators/validators.spec.ts
@@ -1,8 +1,16 @@
+const errorMock = jest.fn();
+
+jest.mock('pino', () => {
+ return {
+ pino: jest.fn(() => ({
+ error: errorMock,
+ })),
+ };
+});
+
import { validateMintRequestBody } from './validators';
describe('validateMintRequestBody', () => {
- const mockConsoleError = jest.spyOn(console, 'error').mockImplementation();
-
afterEach(() => {
jest.clearAllMocks();
});
@@ -22,13 +30,13 @@ describe('validateMintRequestBody', () => {
sendPkpToItself: true,
};
expect(validateMintRequestBody(customArgs)).toBe(true);
- expect(mockConsoleError).not.toHaveBeenCalled();
+ expect(errorMock).not.toHaveBeenCalled();
});
it('should pass validation when no fields are provided', () => {
const customArgs = {};
expect(validateMintRequestBody(customArgs)).toBe(true);
- expect(mockConsoleError).not.toHaveBeenCalled();
+ expect(errorMock).not.toHaveBeenCalled();
});
it('should pass validation when some fields are provided and correct', () => {
@@ -37,7 +45,7 @@ describe('validateMintRequestBody', () => {
permittedAuthMethodPubkeys: ['pubkey123'],
};
expect(validateMintRequestBody(customArgs)).toBe(true);
- expect(mockConsoleError).not.toHaveBeenCalled();
+ expect(errorMock).not.toHaveBeenCalled();
});
it('should fail validation and log error for incorrect keyType', () => {
@@ -45,7 +53,7 @@ describe('validateMintRequestBody', () => {
keyType: '2', // should be a number
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid type for keyType')
);
});
@@ -55,7 +63,7 @@ describe('validateMintRequestBody', () => {
permittedAuthMethodTypes: ['1'], // should be an array of numbers
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid type for permittedAuthMethodTypes')
);
});
@@ -65,7 +73,7 @@ describe('validateMintRequestBody', () => {
permittedAuthMethodIds: [123], // should be an array of strings
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid type for permittedAuthMethodIds')
);
});
@@ -75,7 +83,7 @@ describe('validateMintRequestBody', () => {
permittedAuthMethodPubkeys: [123], // should be an array of strings
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid type for permittedAuthMethodPubkeys')
);
});
@@ -91,7 +99,7 @@ describe('validateMintRequestBody', () => {
addPkpEthAddressAsPermittedAddress: 'true', // should be a boolean
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining(
'Invalid type for addPkpEthAddressAsPermittedAddress'
)
@@ -103,7 +111,7 @@ describe('validateMintRequestBody', () => {
sendPkpToItself: 'true', // should be a boolean
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid type for sendPkpToItself')
);
});
@@ -113,7 +121,7 @@ describe('validateMintRequestBody', () => {
extraneousKey: 'unexpected', // This key is not defined in MintRequestBody
};
expect(validateMintRequestBody(customArgs as any)).toBe(false);
- expect(mockConsoleError).toHaveBeenCalledWith(
+ expect(errorMock).toHaveBeenCalledWith(
expect.stringContaining('Invalid key found: extraneousKey')
);
});
diff --git a/packages/auth/src/lib/authenticators/validators.ts b/packages/auth/src/lib/authenticators/validators.ts
index d7cb27dc2a..f9ccf59147 100644
--- a/packages/auth/src/lib/authenticators/validators.ts
+++ b/packages/auth/src/lib/authenticators/validators.ts
@@ -1,8 +1,10 @@
+import { getChildLogger } from '@lit-protocol/logger';
import { MintRequestBody } from '@lit-protocol/types';
export const validateMintRequestBody = (
customArgs: Partial
): boolean => {
+ const logger = getChildLogger({ function: 'validateMintRequestBody' });
let isValid = true;
const validKeys = [
'keyType',
@@ -17,7 +19,7 @@ export const validateMintRequestBody = (
// Check for any extraneous keys
for (const key of Object.keys(customArgs)) {
if (!validKeys.includes(key)) {
- console.error(
+ logger.error(
`Invalid key found: ${key}. This key is not allowed. Valid keys are: ${validKeys.join(
', '
)}`
@@ -30,7 +32,7 @@ export const validateMintRequestBody = (
customArgs.keyType !== undefined &&
typeof customArgs.keyType !== 'number'
) {
- console.error('Invalid type for keyType: expected a number.');
+ logger.error('Invalid type for keyType: expected a number.');
isValid = false;
}
@@ -41,7 +43,7 @@ export const validateMintRequestBody = (
(type) => typeof type === 'number'
))
) {
- console.error(
+ logger.error(
'Invalid type for permittedAuthMethodTypes: expected an array of numbers.'
);
isValid = false;
@@ -52,7 +54,7 @@ export const validateMintRequestBody = (
(!Array.isArray(customArgs.permittedAuthMethodIds) ||
!customArgs.permittedAuthMethodIds.every((id) => typeof id === 'string'))
) {
- console.error(
+ logger.error(
'Invalid type for permittedAuthMethodIds: expected an array of strings.'
);
isValid = false;
@@ -65,7 +67,7 @@ export const validateMintRequestBody = (
(pubkey) => typeof pubkey === 'string'
))
) {
- console.error(
+ logger.error(
'Invalid type for permittedAuthMethodPubkeys: expected an array of strings.'
);
isValid = false;
@@ -79,8 +81,8 @@ export const validateMintRequestBody = (
Array.isArray(scope) && scope.every((s) => typeof s === 'number')
))
) {
- console.error(
- 'Invalid type for permittedAuthMethodScopes: expected an array of arrays of numberr.'
+ logger.error(
+ 'Invalid type for permittedAuthMethodScopes: expected an array of arrays of number.'
);
isValid = false;
}
@@ -89,7 +91,7 @@ export const validateMintRequestBody = (
customArgs.addPkpEthAddressAsPermittedAddress !== undefined &&
typeof customArgs.addPkpEthAddressAsPermittedAddress !== 'boolean'
) {
- console.error(
+ logger.error(
'Invalid type for addPkpEthAddressAsPermittedAddress: expected a boolean.'
);
isValid = false;
@@ -99,7 +101,7 @@ export const validateMintRequestBody = (
customArgs.sendPkpToItself !== undefined &&
typeof customArgs.sendPkpToItself !== 'boolean'
) {
- console.error('Invalid type for sendPkpToItself: expected a boolean.');
+ logger.error('Invalid type for sendPkpToItself: expected a boolean.');
isValid = false;
}
diff --git a/packages/auth/src/lib/relay.ts b/packages/auth/src/lib/relay.ts
index ffec3fd407..a55e53a0c6 100644
--- a/packages/auth/src/lib/relay.ts
+++ b/packages/auth/src/lib/relay.ts
@@ -9,6 +9,7 @@ import {
InvalidParamType,
NetworkError,
} from '@lit-protocol/constants';
+import { getChildLogger } from '@lit-protocol/logger';
import {
AuthMethod,
MintRequestBody,
@@ -19,13 +20,16 @@ import {
LitRelayConfig,
} from '@lit-protocol/types';
-import { getAuthIdByAuthMethod, log } from './authenticators/utils';
+import { getAuthIdByAuthMethod } from './authenticators/utils';
import { WebAuthnAuthenticator } from './authenticators/WebAuthnAuthenticator';
/**
* Class that communicates with Lit relay server
*/
export class LitRelay implements IRelay {
+ private _logger = getChildLogger({
+ module: 'LitRelay',
+ });
/** URL for Lit's relay server */
static getRelayUrl(litNetwork: LIT_NETWORK_VALUES): string {
const relayerUrl = RELAYER_URL_BY_NETWORK[litNetwork];
@@ -71,7 +75,10 @@ export class LitRelay implements IRelay {
this.relayUrl =
config.relayUrl || LitRelay.getRelayUrl(LIT_NETWORK.NagaDev);
this.relayApiKey = config.relayApiKey || '';
- log("Lit's relay server URL:", this.relayUrl);
+ this._logger.info({
+ msg: "Lit's relay server URL",
+ relayUrl: this.relayUrl,
+ });
}
/**
@@ -92,12 +99,25 @@ export class LitRelay implements IRelay {
});
if (response.status < 200 || response.status >= 400) {
- log('Something wrong with the API call', await response.json());
- const err = new Error('Unable to mint PKP through relay server');
- throw err;
+ const responseBody = await response.json();
+ this._logger.info({
+ msg: 'Something wrong with the API call',
+ responseBody,
+ });
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}${this.mintRoute}`,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ responseBody,
+ },
+ },
+ 'Unable to mint PKP through relay server'
+ );
} else {
const resBody = await response.json();
- log('Successfully initiated minting PKP with relayer');
+ this._logger.info('Successfully initiated minting PKP with relayer');
return resBody;
}
}
@@ -231,26 +251,47 @@ export class LitRelay implements IRelay {
);
if (response.status < 200 || response.status >= 400) {
- log('Something wrong with the API call', await response.json());
- const err = new Error(
+ const responseBody = await response.json();
+ this._logger.info({
+ msg: 'Something wrong with the API call',
+ responseBody,
+ });
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}/auth/status/${requestId}`,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ responseBody,
+ },
+ },
`Unable to poll the status of this mint PKP transaction: ${requestId}`
);
- throw err;
}
const resBody = await response.json();
- log('Response OK', { body: resBody });
+ this._logger.info({ msg: 'Response OK', resBody });
if (resBody.error) {
// exit loop since error
- log('Something wrong with the API call', {
+ this._logger.info({
+ msg: 'Something wrong with the API call',
error: resBody.error,
});
- const err = new Error(resBody.error);
- throw err;
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}/auth/status/${requestId}`,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ resBody,
+ },
+ },
+ resBody.error
+ );
} else if (resBody.status === 'Succeeded') {
// exit loop since success
- log('Successfully authed', { ...resBody });
+ this._logger.info({ msg: 'Successfully authed', resBody });
return resBody;
}
@@ -259,9 +300,14 @@ export class LitRelay implements IRelay {
}
// at this point, polling ended and still no success, set failure status
- // console.error(`Hmm this is taking longer than expected...`);
- const err = new Error('Polling for mint PKP transaction status timed out');
- throw err;
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}/auth/status/${requestId}`,
+ },
+ },
+ 'Polling for mint PKP transaction status timed out'
+ );
}
/**
@@ -282,13 +328,25 @@ export class LitRelay implements IRelay {
});
if (response.status < 200 || response.status >= 400) {
- console.warn('Something wrong with the API call', await response.json());
- // console.log("Uh oh, something's not quite right.");
- const err = new Error('Unable to fetch PKPs through relay server');
- throw err;
+ const resBody = await response.json();
+ this._logger.warn({
+ msg: 'Something wrong with the API call',
+ resBody,
+ });
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}${this.fetchRoute}`,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ resBody,
+ },
+ },
+ 'Unable to fetch PKPs through relay server'
+ );
} else {
const resBody = await response.json();
- console.log('Successfully fetched PKPs with relayer');
+ this._logger.info('Successfully fetched PKPs with relayer');
return resBody;
}
}
@@ -312,10 +370,16 @@ export class LitRelay implements IRelay {
},
});
if (response.status < 200 || response.status >= 400) {
- const err = new Error(
+ throw new NetworkError(
+ {
+ info: {
+ route: `${this.relayUrl}${this.fetchRoute}`,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ },
+ },
`Unable to generate registration options: ${response}`
);
- throw err;
}
const registrationOptions = await response.json();
return registrationOptions;
diff --git a/packages/auth/src/lib/storage/localStorage.spec.ts b/packages/auth/src/lib/storage/localStorage.spec.ts
index a1e3b07200..6b706a270d 100644
--- a/packages/auth/src/lib/storage/localStorage.spec.ts
+++ b/packages/auth/src/lib/storage/localStorage.spec.ts
@@ -42,14 +42,17 @@ describe('localStorage', () => {
});
test('writes and reads to/from localStorage correctly', async () => {
- mockLocalStorage.setItem(expect.any(String), JSON.stringify(authData));
+ mockLocalStorage.setItem(
+ `lit-auth:${appName}:${networkName}:${pkpAddress}`,
+ JSON.stringify(authData)
+ );
const storage = createLocalStorage({
appName,
networkName,
localStorage: mockLocalStorage,
});
- expect(storage.read({ pkpAddress })).resolves.toEqual(authData);
+ await expect(storage.read({ pkpAddress })).resolves.toEqual(authData);
});
test('returns null when reading nonexistent data', async () => {
@@ -83,20 +86,20 @@ describe('localStorage', () => {
authData: authDataNetworkA,
});
- expect(storageNetworkA.read({ pkpAddress })).resolves.toEqual(
+ await expect(storageNetworkA.read({ pkpAddress })).resolves.toEqual(
authDataNetworkA
);
- expect(storageNetworkB.read({ pkpAddress })).resolves.toBeNull();
+ await expect(storageNetworkB.read({ pkpAddress })).resolves.toBeNull();
await storageNetworkB.write({
pkpAddress,
authData: authDataNetworkB,
});
- expect(storageNetworkA.read({ pkpAddress })).resolves.toEqual(
+ await expect(storageNetworkA.read({ pkpAddress })).resolves.toEqual(
authDataNetworkA
);
- expect(storageNetworkB.read({ pkpAddress })).resolves.toEqual(
+ await expect(storageNetworkB.read({ pkpAddress })).resolves.toEqual(
authDataNetworkB
);
});
@@ -116,11 +119,13 @@ describe('localStorage', () => {
const authDataNetworkB = { ...authData, credential: 'networkB' };
await storageAppA.write({ pkpAddress, authData });
- expect(storageAppA.read({ pkpAddress })).resolves.toEqual(authData);
- expect(storageAppB.read({ pkpAddress })).resolves.toBeNull();
+ await expect(storageAppA.read({ pkpAddress })).resolves.toEqual(authData);
+ await expect(storageAppB.read({ pkpAddress })).resolves.toBeNull();
await storageAppB.write({ pkpAddress, authData: authDataNetworkB });
- expect(storageAppB.read({ pkpAddress })).resolves.toEqual(authDataNetworkB);
- expect(storageAppA.read({ pkpAddress })).resolves.toEqual(authData);
+ await expect(storageAppB.read({ pkpAddress })).resolves.toEqual(
+ authDataNetworkB
+ );
+ await expect(storageAppA.read({ pkpAddress })).resolves.toEqual(authData);
});
});
diff --git a/packages/auth/src/lib/storage/localStorage.ts b/packages/auth/src/lib/storage/localStorage.ts
index 7af3322b9b..c3fdf9a7f4 100644
--- a/packages/auth/src/lib/storage/localStorage.ts
+++ b/packages/auth/src/lib/storage/localStorage.ts
@@ -12,7 +12,6 @@ interface LocalStorageConfig {
function assertLocalstorageValid(
localStorage: unknown
): asserts localStorage is WindowLocalStorage['localStorage'] {
- console.log('localStorage is...', localStorage);
if (!localStorage) {
throw new Error('localStorage is not available in this environment');
}
diff --git a/packages/constants/babel.config.json b/packages/constants/babel.config.json
deleted file mode 100644
index 158083d278..0000000000
--- a/packages/constants/babel.config.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "presets": [
- [
- "@nx/web/babel",
- {
- "useBuiltIns": "usage"
- }
- ]
- ]
-}
diff --git a/packages/constants/package.json b/packages/constants/package.json
index 0b84b2c77c..7c357ec8c1 100644
--- a/packages/constants/package.json
+++ b/packages/constants/package.json
@@ -12,6 +12,7 @@
"bugs": {
"url": "https://github.com/LIT-Protocol/js-sdk/issues"
},
+ "type": "commonjs",
"publishConfig": {
"access": "public",
"directory": "../../dist/packages/constants"
diff --git a/packages/constants/project.json b/packages/constants/project.json
index c270222f93..715e72efb0 100644
--- a/packages/constants/project.json
+++ b/packages/constants/project.json
@@ -15,12 +15,6 @@
"updateBuildableProjectDepsInPackageJson": true
}
},
- "copyJSONFilesToDist": {
- "executor": "nx:run-commands",
- "options": {
- "command": "mkdir -p dist/packages/constants/web/abis && cp ./packages/constants/src/lib/abis/ERC20.json dist/packages/constants/web/abis/ERC20.json && cp ./packages/constants/src/lib/abis/LIT.json dist/packages/constants/web/abis/LIT.json"
- }
- },
"generateDoc": {
"executor": "nx:run-commands",
"options": {
@@ -34,7 +28,7 @@
"lintFilePatterns": ["packages/constants/**/*.ts"]
}
},
- "testPackage": {
+ "test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/packages/constants"],
"options": {
diff --git a/packages/constants/src/index.ts b/packages/constants/src/index.ts
index 940d84a592..2c72a5d0d2 100644
--- a/packages/constants/src/index.ts
+++ b/packages/constants/src/index.ts
@@ -1,22 +1,14 @@
// ----------- Version -----------
export * from './lib/version';
+// ----------- Environment -----------
+export * from './lib/environment';
+
// ----------- Constants -----------
export * from './lib/constants/constants';
export * from './lib/constants/mappers';
export * from './lib/constants/endpoints';
export * from './lib/constants/curves';
-// ----------- Interfaces -----------
-export * from './lib/interfaces/i-errors';
-
// ----------- Errors -----------
export * from './lib/errors';
-
-// ----------- Utils -----------
-export * from './lib/utils/utils';
-
-// ----------- ABIs -----------
-import * as ABI_ERC20 from './lib/abis/ERC20.json';
-
-export { ABI_ERC20 };
diff --git a/packages/constants/src/lib/abis/ERC20.json b/packages/constants/src/lib/abis/ERC20.json
deleted file mode 100644
index b8347e7d73..0000000000
--- a/packages/constants/src/lib/abis/ERC20.json
+++ /dev/null
@@ -1,224 +0,0 @@
-{
- "abi": [
- {
- "constant": true,
- "inputs": [],
- "name": "name",
- "outputs": [
- {
- "name": "",
- "type": "string"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": false,
- "inputs": [
- {
- "name": "_spender",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "approve",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [],
- "name": "totalSupply",
- "outputs": [
- {
- "name": "",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": false,
- "inputs": [
- {
- "name": "_from",
- "type": "address"
- },
- {
- "name": "_to",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "transferFrom",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [],
- "name": "decimals",
- "outputs": [
- {
- "name": "",
- "type": "uint8"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [
- {
- "name": "_owner",
- "type": "address"
- }
- ],
- "name": "balanceOf",
- "outputs": [
- {
- "name": "balance",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [],
- "name": "symbol",
- "outputs": [
- {
- "name": "",
- "type": "string"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "constant": false,
- "inputs": [
- {
- "name": "_to",
- "type": "address"
- },
- {
- "name": "_value",
- "type": "uint256"
- }
- ],
- "name": "transfer",
- "outputs": [
- {
- "name": "",
- "type": "bool"
- }
- ],
- "payable": false,
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "constant": true,
- "inputs": [
- {
- "name": "_owner",
- "type": "address"
- },
- {
- "name": "_spender",
- "type": "address"
- }
- ],
- "name": "allowance",
- "outputs": [
- {
- "name": "",
- "type": "uint256"
- }
- ],
- "payable": false,
- "stateMutability": "view",
- "type": "function"
- },
- {
- "payable": true,
- "stateMutability": "payable",
- "type": "fallback"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "name": "owner",
- "type": "address"
- },
- {
- "indexed": true,
- "name": "spender",
- "type": "address"
- },
- {
- "indexed": false,
- "name": "value",
- "type": "uint256"
- }
- ],
- "name": "Approval",
- "type": "event"
- },
- {
- "anonymous": false,
- "inputs": [
- {
- "indexed": true,
- "name": "from",
- "type": "address"
- },
- {
- "indexed": true,
- "name": "to",
- "type": "address"
- },
- {
- "indexed": false,
- "name": "value",
- "type": "uint256"
- }
- ],
- "name": "Transfer",
- "type": "event"
- }
- ]
-}
diff --git a/packages/constants/src/lib/constants/constants.spec.ts b/packages/constants/src/lib/constants/constants.spec.ts
index 9f204caeaf..c0ea4154e5 100644
--- a/packages/constants/src/lib/constants/constants.spec.ts
+++ b/packages/constants/src/lib/constants/constants.spec.ts
@@ -1,91 +1,13 @@
-// @ts-nocheck
-import {
- LIT_CHAINS,
- LIT_COSMOS_CHAINS,
- LIT_SVM_CHAINS,
- NETWORK_PUB_KEY,
-} from './constants';
+import { LIT_CHAINS, NETWORK_PUB_KEY } from './constants';
describe('constants', () => {
- const MUST_HAVE_EVM_CHAINS: Array = [
- 'ethereum',
- 'polygon',
- 'fantom',
- 'xdai',
- 'bsc',
- 'arbitrum',
- 'avalanche',
- 'fuji',
- 'harmony',
- 'kovan',
- 'mumbai',
- 'goerli',
- 'ropsten',
- 'rinkeby',
- 'cronos',
- 'optimism',
- 'celo',
- 'aurora',
- 'eluvio',
- 'alfajores',
- 'xdc',
- 'evmos',
- 'evmosTestnet',
- 'bscTestnet',
- 'baseGoerli',
- ];
-
- const MUST_HAVE_SOL_CHAINS = ['solana', 'solanaDevnet', 'solanaTestnet'];
- const MUST_HAVE_COSMOS_CHAINS = [
- 'cosmos',
- 'kyve',
- 'evmosCosmos',
- 'evmosCosmosTestnet',
- ];
-
const networkPubKey =
'9971e835a1fe1a4d78e381eebbe0ddc84fde5119169db816900de796d10187f3c53d65c1202ac083d099a517f34a9b62';
- it(`LIT_CHAINS should have ${MUST_HAVE_EVM_CHAINS.toString()}`, () => {
- let total = 0;
-
- MUST_HAVE_EVM_CHAINS.forEach((chain) => {
- if (Object.keys(LIT_CHAINS).includes(chain)) {
- total++;
- }
- });
-
- expect(total).toEqual(Object.keys(LIT_CHAINS).length);
- });
-
it(`Network public key should be ${networkPubKey}`, () => {
expect(NETWORK_PUB_KEY).toEqual(networkPubKey);
});
- it(`LIT_SVM_CHAINS should have ${MUST_HAVE_SOL_CHAINS}`, () => {
- let total = 0;
-
- MUST_HAVE_SOL_CHAINS.forEach((chain) => {
- if (Object.keys(LIT_SVM_CHAINS).includes(chain)) {
- total++;
- }
- });
-
- expect(total).toEqual(Object.keys(LIT_SVM_CHAINS).length);
- });
-
- it(`LIT_COSMOS_CHAINS should have ${MUST_HAVE_COSMOS_CHAINS}`, () => {
- let total = 0;
-
- MUST_HAVE_COSMOS_CHAINS.forEach((chain) => {
- if (Object.keys(LIT_COSMOS_CHAINS).includes(chain)) {
- total++;
- }
- });
-
- expect(total).toEqual(Object.keys(LIT_COSMOS_CHAINS).length);
- });
-
const ethContract = '0xA54F7579fFb3F98bd8649fF02813F575f9b3d353';
it(`Ethereum contract address should be ${ethContract}`, () => {
diff --git a/packages/constants/src/lib/constants/constants.ts b/packages/constants/src/lib/constants/constants.ts
index b58efeeb53..1935d7d3f9 100644
--- a/packages/constants/src/lib/constants/constants.ts
+++ b/packages/constants/src/lib/constants/constants.ts
@@ -1257,11 +1257,8 @@ export const ALL_LIT_CHAINS = {
* Local storage key constants
*/
export const LOCAL_STORAGE_KEYS = {
- AUTH_COSMOS_SIGNATURE: 'lit-auth-cosmos-signature',
AUTH_SIGNATURE: 'lit-auth-signature',
- AUTH_SOL_SIGNATURE: 'lit-auth-sol-signature',
WEB3_PROVIDER: 'lit-web3-provider',
- KEY_PAIR: 'lit-comms-keypair',
SESSION_KEY: 'lit-session-key',
WALLET_SIGNATURE: 'lit-wallet-sig',
} as const;
@@ -1276,14 +1273,6 @@ export const LIT_NETWORKS: Record = {
[LIT_NETWORK.Custom]: [],
} as const;
-// ========== Either Types ==========
-export const EITHER_TYPE = {
- ERROR: 'ERROR',
- SUCCESS: 'SUCCESS',
-} as const;
-export type EITHER_TYPE_TYPE = ConstantKeys;
-export type EITHER_TYPE_VALUES = ConstantValues;
-
// ========== Supported PKP Auth Method Types ==========
export const AUTH_METHOD_TYPE = {
EthWallet: 1,
diff --git a/packages/constants/src/lib/environment.ts b/packages/constants/src/lib/environment.ts
new file mode 100644
index 0000000000..086b427f30
--- /dev/null
+++ b/packages/constants/src/lib/environment.ts
@@ -0,0 +1,9 @@
+export class Environment {
+ static get isNode(): boolean {
+ return typeof process?.versions?.node !== 'undefined';
+ }
+
+ static get isBrowser(): boolean {
+ return !Environment.isNode;
+ }
+}
diff --git a/packages/constants/src/lib/errors.ts b/packages/constants/src/lib/errors.ts
index 1373866777..8f97de313b 100644
--- a/packages/constants/src/lib/errors.ts
+++ b/packages/constants/src/lib/errors.ts
@@ -208,6 +208,11 @@ export const LIT_ERROR: Record = {
code: 'network_error',
kind: LIT_ERROR_KIND.Unexpected,
},
+ LIT_NETWORK_ERROR: {
+ name: 'LitNetworkError',
+ code: 'lit_network_error',
+ kind: LIT_ERROR_KIND.Unexpected,
+ },
TRANSACTION_ERROR: {
name: 'TransactionError',
code: 'transaction_error',
@@ -300,6 +305,7 @@ export { MultiError };
export const {
AutomationError,
+ CurveTypeNotFoundError,
InitError,
InvalidAccessControlConditions,
InvalidArgumentException,
@@ -310,6 +316,7 @@ export const {
InvalidParamType,
InvalidSignatureError,
InvalidUnifiedConditionType,
+ LitNetworkError,
LitNodeClientBadConfigError,
LitNodeClientNotReadyError,
LocalStorageItemNotFoundException,
@@ -337,5 +344,4 @@ export const {
WasmInitError,
WrongNetworkException,
WrongParamFormat,
- CurveTypeNotFoundError,
} = errorClasses;
diff --git a/packages/constants/src/lib/interfaces/i-errors.ts b/packages/constants/src/lib/interfaces/i-errors.ts
deleted file mode 100644
index 11ccb44c10..0000000000
--- a/packages/constants/src/lib/interfaces/i-errors.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { EITHER_TYPE } from '../constants/constants';
-import { LitError } from '../errors';
-
-/**
- * A standardized way to return either error or success
- */
-export type IEither = IEitherError | IEitherSuccess;
-
-export interface IEitherError {
- type: typeof EITHER_TYPE.ERROR;
- result: LitError;
-}
-
-export interface IEitherSuccess {
- type: typeof EITHER_TYPE.SUCCESS;
- result: T;
-}
diff --git a/packages/constants/src/lib/utils/utils.spec.ts b/packages/constants/src/lib/utils/utils.spec.ts
deleted file mode 100644
index 166b313f0d..0000000000
--- a/packages/constants/src/lib/utils/utils.spec.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { ELeft, ERight } from './utils';
-import { UnknownError } from '../errors';
-
-describe('error handling utils ELeft/Right works', () => {
- const unknownError = new UnknownError({}, 'ERROR');
- const res = ELeft(unknownError);
- const res2 = ERight('ANSWER');
-
- it('returns result on ELeft()', () => {
- expect(res.result).toBe(unknownError);
- });
-
- it('returns type on ELeft()', () => {
- expect(res.type).toBe('ERROR');
- });
-
- it('returns result on ERight()', () => {
- expect(res2.result).toBe('ANSWER');
- });
-
- it('returns type on ERight()', () => {
- expect(res2.type).toBe('SUCCESS');
- });
-});
diff --git a/packages/constants/src/lib/utils/utils.ts b/packages/constants/src/lib/utils/utils.ts
deleted file mode 100644
index 48f98ab987..0000000000
--- a/packages/constants/src/lib/utils/utils.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { EITHER_TYPE } from '../constants/constants';
-import { LitError } from '../errors';
-import { IEitherSuccess, IEitherError } from '../interfaces/i-errors';
-
-/**
- *
- * This method should be used when there's an expected error
- *
- * @param error is the error encountered
- * @returns { IEither }
- */
-export function ELeft(error: LitError): IEitherError {
- return {
- type: EITHER_TYPE.ERROR,
- result: error,
- };
-}
-
-/**
- *
- * This method should be used when there's an expected success outcome
- *
- * @param result is the successful return value
- * @returns
- */
-export function ERight(result: T): IEitherSuccess {
- return {
- type: EITHER_TYPE.SUCCESS,
- result,
- };
-}
diff --git a/packages/constants/tsconfig.lib.json b/packages/constants/tsconfig.lib.json
index a6b1ef35bc..7bfc80f73e 100644
--- a/packages/constants/tsconfig.lib.json
+++ b/packages/constants/tsconfig.lib.json
@@ -3,8 +3,8 @@
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"declaration": true,
- "types": []
+ "types": ["node"]
},
- "include": ["**/*.ts", "src/lib/utils/uint8arrays.ts"],
+ "include": ["**/*.ts"],
"exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
}
diff --git a/packages/contracts-sdk/src/lib/auth-utils.ts b/packages/contracts-sdk/src/lib/auth-utils.ts
index 00893ddd83..5d8efe0a8f 100644
--- a/packages/contracts-sdk/src/lib/auth-utils.ts
+++ b/packages/contracts-sdk/src/lib/auth-utils.ts
@@ -245,7 +245,6 @@ function _parseJWT(jwt: string): StytchToken {
}
const body = Buffer.from(parts[1], 'base64');
const parsedBody: StytchToken = JSON.parse(body.toString('ascii'));
- console.log('JWT body: ', parsedBody);
return parsedBody;
}
diff --git a/packages/contracts-sdk/src/lib/contracts-sdk.ts b/packages/contracts-sdk/src/lib/contracts-sdk.ts
index 5443df28f6..b1f6ab4915 100644
--- a/packages/contracts-sdk/src/lib/contracts-sdk.ts
+++ b/packages/contracts-sdk/src/lib/contracts-sdk.ts
@@ -11,11 +11,13 @@ import { computeAddress } from 'ethers/lib/utils';
import {
AUTH_METHOD_SCOPE_VALUES,
AUTH_METHOD_TYPE_VALUES,
+ Environment,
HTTP,
HTTP_BY_NETWORK,
HTTPS,
InitError,
InvalidArgumentException,
+ LitNetworkError,
LIT_NETWORK,
LIT_NETWORK_VALUES,
METAMASK_CHAIN_INFO_BY_NETWORK,
@@ -23,10 +25,11 @@ import {
ParamsMissingError,
RPC_URL_BY_NETWORK,
TransactionError,
+ UnsupportedMethodError,
WrongNetworkException,
} from '@lit-protocol/constants';
-import { Logger, LogManager } from '@lit-protocol/logger';
-import { derivedAddresses, isBrowser, isNode } from '@lit-protocol/misc';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
+import { getStorageItem, setStorageItem } from '@lit-protocol/misc-browser';
import {
ContractName,
EpochInfo,
@@ -42,6 +45,7 @@ import {
} from '@lit-protocol/types';
import { getAuthIdByAuthMethod, stringToArrayify } from './auth-utils';
+import { derivedAddresses } from './helpers/addresses';
import {
CIDParser,
getBytes32FromMultihash,
@@ -75,6 +79,7 @@ const GAS_LIMIT_ADJUSTMENT = ethers.BigNumber.from(100).add(
// 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 {
+ private readonly _logger: Logger;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
provider: ethers.providers.StaticJsonRpcProvider | any;
rpc: string;
@@ -103,8 +108,6 @@ export class LitContracts {
'PriceFeed',
];
- static logger: Logger = LogManager.Instance.get('contract-sdk');
-
// make the constructor args optional
constructor(args?: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -124,6 +127,10 @@ export class LitContracts {
debug?: boolean;
network?: LIT_NETWORKS_KEYS;
}) {
+ this._logger = getChildLogger({
+ module: 'LitContracts',
+ ...(args?.debug ? { level: 'debug' } : {}),
+ });
// this.provider = args?.provider;
this.customContext = args?.customContext;
this.rpc = args?.rpc;
@@ -145,18 +152,6 @@ export class LitContracts {
}
}
- /**
- * Logs a message to the console.
- *
- * @param {any} [args] An optional value to log with the message.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- log = (...args: any[]) => {
- if (this.debug) {
- LitContracts.logger.debug(...args);
- }
- };
-
connect = async () => {
// =======================================
// SETTING UP PROVIDER
@@ -168,9 +163,9 @@ export class LitContracts {
let wallet;
let SETUP_DONE = false;
if (this.provider) {
- this.log('Using provided provider');
- } else if (isBrowser() && !this.signer) {
- this.log("----- We're in the browser! -----");
+ this._logger.info('Using provided provider');
+ } else if (Environment.isBrowser && !this.signer) {
+ this._logger.info("----- We're in the browser! -----");
const web3Provider = window.ethereum;
@@ -219,8 +214,8 @@ export class LitContracts {
// ----------------------------------------------
// (Node) Setting up Provider
// ----------------------------------------------
- else if (isNode()) {
- this.log("----- We're in node! -----");
+ else if (Environment.isNode) {
+ this._logger.info("----- We're in node! -----");
this.provider = new ethers.providers.StaticJsonRpcProvider({
url: this.rpc,
skipFetchSetup: true,
@@ -231,7 +226,7 @@ export class LitContracts {
// CUSTOM PRIVATE KEY
// ======================================
if (this.privateKey) {
- this.log('Using your own private key');
+ this._logger.info('Using your own private key');
this.signer = new ethers.Wallet(this.privateKey, this.provider);
this.provider = this.signer.provider;
SETUP_DONE = true;
@@ -244,61 +239,72 @@ export class LitContracts {
(!this.privateKey && this.randomPrivateKey) ||
this.options?.storeOrUseStorageKey
) {
- this.log('THIS.SIGNER:', this.signer);
+ this._logger.info({ msg: 'THIS.SIGNER', signer: this.signer });
const STORAGE_KEY = 'lit-contracts-sdk-private-key';
- this.log("Let's see if you have a private key in your local storage!");
+ this._logger.info(
+ "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);
+ storagePrivateKey = getStorageItem(STORAGE_KEY);
} catch (e) {
// swallow
- // this.log('Not a problem.');
+ // this.#logger.info('Not a problem.');
}
// -- (NOT FOUND) no private key found
if (!storagePrivateKey) {
- this.log('Not a problem, we will generate a random private key');
+ this._logger.info(
+ 'Not a problem, we will generate a random private key'
+ );
storagePrivateKey = ethers.utils.hexlify(ethers.utils.randomBytes(32));
}
// -- (FOUND) private key found
else {
- this.log("Found your private key in local storage. Let's use it!");
+ this._logger.info(
+ "Found your private key in local storage. Let's use it!"
+ );
}
this.signer = new ethers.Wallet(storagePrivateKey, this.provider);
- this.log('- Your private key:', storagePrivateKey);
- this.log('- Your address:', await this.signer.getAddress());
- this.log('- this.signer:', this.signer);
- this.log('- this.provider.getSigner():', this.provider.getSigner());
+ this._logger.info({
+ msg: '- Your address',
+ address: await this.signer.getAddress(),
+ });
+ this._logger.info({ msg: '- this.signer', signer: this.signer });
+ this._logger.info({
+ msg: '- this.provider.getSigner()',
+ signer: this.provider.getSigner(),
+ });
// -- (OPTION) store private key in local storage
if (this.options?.storeOrUseStorageKey) {
- this.log(
+ this._logger.info(
"You've set the option to store your private key in local storage."
);
- localStorage.setItem(STORAGE_KEY, storagePrivateKey);
+ setStorageItem(STORAGE_KEY, storagePrivateKey);
}
} else {
// ----------------------------------------
// Ask Metamask to sign
// ----------------------------------------
- if (isBrowser() && wallet && !SETUP_DONE) {
- // this.log('HERE????');
- this.log('this.signer:', this.signer);
+ if (Environment.isBrowser && wallet && !SETUP_DONE) {
+ // this.#logger.info('HERE????');
+ this._logger.info({ msg: 'this.signer', signer: this.signer });
this.signer = wallet.getSigner();
}
}
if (this.signer !== undefined && this.signer !== null) {
if ('litNodeClient' in this.signer && 'rpcProvider' in this.signer) {
- this.log(`
+ this._logger.info(`
// ***********************************************************************************************
// THIS IS A PKP WALLET, USING IT AS A SIGNER AND ITS RPC PROVIDER AS PROVIDER
// ***********************************************************************************************
@@ -309,13 +315,21 @@ export class LitContracts {
}
}
- this.log('Your Signer:', this.signer);
- this.log('Your Provider:', this.provider?.connection);
+ this._logger.info({ msg: 'Your Signer', signer: this.signer });
+ this._logger.info({
+ msg: 'Your Provider',
+ provider: this.provider?.connection,
+ });
if (!this.provider) {
- this.log('No provider found. Will try to use the one from the signer.');
+ this._logger.info(
+ 'No provider found. Will try to use the one from the signer.'
+ );
this.provider = this.signer.provider;
- this.log('Your Provider(from signer):', this.provider?.connection);
+ this._logger.info({
+ msg: 'Your Provider(from signer)',
+ provider: this.provider?.connection,
+ });
}
this.connected = true;
@@ -807,12 +821,7 @@ export class LitContracts {
HTTP; // Fallback to HTTP
// Construct the URL
- const url = `${protocol}${ip}:${port}`;
-
- // Log the constructed URL for debugging
- LitContracts.logger.debug("Validator's URL:", url);
-
- return url;
+ return `${protocol}${ip}:${port}`;
});
}
@@ -868,11 +877,27 @@ export class LitContracts {
const minNodeCountInt = ethers.BigNumber.from(minNodeCount).toNumber();
if (!minNodeCountInt) {
- throw new Error('❌ Minimum validator count is not set');
+ throw new LitNetworkError(
+ {
+ info: {
+ epochInfo,
+ activeValidators: activeUnkickedValidatorStructs.length,
+ minNodeCount: minNodeCountInt,
+ },
+ },
+ '❌ Minimum validator count is not set'
+ );
}
if (activeUnkickedValidatorStructs.length < minNodeCountInt) {
- throw new Error(
+ throw new LitNetworkError(
+ {
+ info: {
+ epochInfo,
+ activeValidators: activeUnkickedValidatorStructs.length,
+ minNodeCount: minNodeCountInt,
+ },
+ },
`❌ Active validator set does not meet the consensus. Required: ${minNodeCountInt} but got: ${activeUnkickedValidatorStructs.length}`
);
}
@@ -1136,13 +1161,13 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
}
const tokenId = events[0].topics[1];
- this.log('tokenId:', tokenId);
+ this._logger.info({ msg: 'tokenId', tokenId });
let tries = 0;
const maxAttempts = 10;
let publicKey = '';
while (tries < maxAttempts) {
publicKey = await pkpNftContract['getPubkey'](tokenId);
- this.log('pkp pub key: ', publicKey);
+ this._logger.info({ msg: 'pkp pub key', publicKey });
if (publicKey !== '0x') {
break;
}
@@ -1377,7 +1402,6 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
* const CID = require('multiformats/cid')
* const ipfsId = 'QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW'
* const bytes32 = getBytes32FromMultihash(ipfsId, CID)
- * console.log(bytes32)
*
* @returns {IPFSHash}
*/
@@ -1451,7 +1475,9 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
tokens.push(token);
} catch (e) {
- this.log(`[getTokensByAddress] Ended search on index: ${i}`);
+ this._logger.info(
+ `[getTokensByAddress] Ended search on index: ${i}`
+ );
break;
}
}
@@ -1512,7 +1538,9 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
tokens.push(token);
} catch (e) {
- this.log(`[getTokensByAddress] Ended search on index: ${i}`);
+ this._logger.info(
+ `[getTokensByAddress] Ended search on index: ${i}`
+ );
break;
}
}
@@ -1599,12 +1627,12 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
}
if (this.isPKP) {
- this.log(
+ this._logger.info(
"This is a PKP wallet, so we'll use the PKP wallet to sign the tx"
);
}
- this.log('...signing and sending tx');
+ this._logger.info('...signing and sending tx');
const sentTx = await this._callWithAdjustedOverrides(
pkpNftContract,
@@ -1613,22 +1641,22 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
{ value: mintCost, ...param }
);
- this.log('sentTx:', sentTx);
+ this._logger.info({ msg: 'sentTx', sentTx });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res: any = await sentTx.wait();
- this.log('res:', res);
+ this._logger.info({ msg: 'res', res });
const events = 'events' in res ? res.events : res.logs;
const tokenIdFromEvent = events[0].topics[1];
- this.log('tokenIdFromEvent:', tokenIdFromEvent);
+ this._logger.info({ msg: 'tokenIdFromEvent', tokenIdFromEvent });
let tries = 0;
const maxAttempts = 10;
let publicKey = '';
while (tries < maxAttempts) {
publicKey = await pkpNftContract['getPubkey'](tokenIdFromEvent);
- this.log('pkp pub key: ', publicKey);
+ this._logger.info({ msg: 'pkp pub key', publicKey });
if (publicKey !== '0x') {
break;
}
@@ -1638,7 +1666,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
});
}
- this.log('public key from token id', publicKey);
+ this._logger.info({ msg: 'public key from token id', publicKey });
if (publicKey.startsWith('0x')) {
publicKey = publicKey.slice(2);
}
@@ -1686,7 +1714,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
const tokenId = events[1].topics[1];
return { tx, res: txRec, tokenId };
} catch (e: unknown) {
- this.log(`[claimAndMint] error: ${(e as Error).message}`);
+ this._logger.info(`[claimAndMint] error: ${(e as Error).message}`);
throw new TransactionError(
{
info: {
@@ -1791,7 +1819,10 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
);
}
- this.log('[getPermittedAddresses] input:', tokenId);
+ this._logger.info({
+ msg: '[getPermittedAddresses] input',
+ tokenId,
+ });
let addresses: string[] = [];
@@ -1811,7 +1842,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
break;
}
} catch (e: unknown) {
- this.log(
+ this._logger.info(
`[getPermittedAddresses] error:`,
(e as Error).message
);
@@ -1878,10 +1909,10 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
break;
}
} catch (e: unknown) {
- this.log(
- `[getPermittedActions] error:`,
- (e as Error).message
- );
+ this._logger.info({
+ msg: `[getPermittedActions] error:`,
+ message: (e as Error).message,
+ });
tries++;
}
}
@@ -1929,11 +1960,14 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
);
}
- this.log('[isPermittedAction] input:', pkpId);
- this.log('[isPermittedAction] input:', ipfsId);
+ this._logger.info({ msg: '[isPermittedAction] input', pkpId });
+ this._logger.info({ msg: '[isPermittedAction] input', ipfsId });
const ipfsHash = this.utils.getBytesFromMultihash(ipfsId);
- this.log('[isPermittedAction] converted:', ipfsHash);
+ this._logger.info({
+ msg: '[isPermittedAction] converted',
+ ipfsHash,
+ });
const bool = await pkpPermissionsContract['isPermittedAction'](
pkpId,
@@ -1990,21 +2024,36 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
);
}
- this.log('[addPermittedAction] input:', pkpId);
+ this._logger.info({ msg: '[addPermittedAction] input', pkpId });
const pubKey = await pubkeyRouterContract['getPubkey'](pkpId);
- this.log('[addPermittedAction] converted:', pubKey);
+ this._logger.info({
+ msg: '[addPermittedAction] converted',
+ pubKey,
+ });
const pubKeyHash = ethers.utils.keccak256(pubKey);
- this.log('[addPermittedAction] converted:', pubKeyHash);
+ this._logger.info({
+ msg: '[addPermittedAction] converted',
+ pubKeyHash,
+ });
const tokenId = ethers.BigNumber.from(pubKeyHash);
- this.log('[addPermittedAction] converted:', tokenId);
+ this._logger.info({
+ msg: '[addPermittedAction] converted',
+ tokenId,
+ });
- this.log('[addPermittedAction] input:', ipfsId);
+ this._logger.info({
+ msg: '[addPermittedAction] input',
+ ipfsId,
+ });
const ipfsIdBytes = this.utils.getBytesFromMultihash(ipfsId);
- this.log('[addPermittedAction] converted:', ipfsIdBytes);
+ this._logger.info({
+ msg: '[addPermittedAction] converted',
+ ipfsIdBytes,
+ });
const tx = await this._callWithAdjustedOverrides(
pkpPermissionsContract,
@@ -2012,7 +2061,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
[tokenId, ipfsIdBytes, [1]]
);
- this.log('[addPermittedAction] output:', tx);
+ this._logger.info({ msg: '[addPermittedAction] output', tx });
return tx;
},
@@ -2057,10 +2106,14 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
);
}
- this.log('[addPermittedAddress] input:', pkpId);
- this.log('[addPermittedAddress] input:', ownerAddress);
-
- this.log('[addPermittedAddress] input:', pkpId);
+ this._logger.info({
+ msg: '[addPermittedAddress] input',
+ pkpId,
+ });
+ this._logger.info({
+ msg: '[addPermittedAddress] input',
+ ownerAddress,
+ });
const tx = await this._callWithAdjustedOverrides(
pkpPermissionsContract,
@@ -2068,7 +2121,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
[pkpId, ownerAddress, [1]]
);
- this.log('[addPermittedAddress] output:', tx);
+ this._logger.info({ msg: '[addPermittedAddress] output', tx });
return tx;
},
@@ -2112,11 +2165,20 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
);
}
- this.log('[revokePermittedAction] input:', pkpId);
- this.log('[revokePermittedAction] input:', ipfsId);
+ this._logger.info({
+ msg: '[revokePermittedAction] input',
+ pkpId,
+ });
+ this._logger.info({
+ msg: '[revokePermittedAction] input',
+ ipfsId,
+ });
const ipfsHash = this.utils.getBytesFromMultihash(ipfsId);
- this.log('[revokePermittedAction] converted:', ipfsHash);
+ this._logger.info({
+ msg: '[revokePermittedAction] converted',
+ ipfsHash,
+ });
const tx = await this._callWithAdjustedOverrides(
pkpPermissionsContract,
@@ -2124,7 +2186,7 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
[pkpId, ipfsHash]
);
- this.log('[revokePermittedAction] output:', tx);
+ this._logger.info({ msg: '[revokePermittedAction] output', tx });
return tx;
},
@@ -2144,9 +2206,9 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
* @return { Promise }
*/
// getIpfsIds: async (solidityIpfsId: string): Promise => {
- // this.log('[getIpfsIds] input:', solidityIpfsId);
+ // this.#logger.info({ msg: '[getIpfsIds] input', solidityIpfsId });
// const ipfsId = this.utils.getMultihashFromBytes(solidityIpfsId);
- // this.log('[getIpfsIds] output:', ipfsId);
+ // this.#logger.info({ msg: '[getIpfsIds] output', ipfsId });
// return ipfsId;
// },
},
@@ -2230,7 +2292,14 @@ https://developer.litprotocol.com/v3/sdk/wallets/auth-methods/#auth-method-scope
): Promise> {
// Check if the method exists on the contract
if (!(method in contract.functions)) {
- throw new Error(
+ throw new UnsupportedMethodError(
+ {
+ info: {
+ network: this.network,
+ contract,
+ method,
+ },
+ },
`Method ${String(method)} does not exist on the contract`
);
}
diff --git a/packages/misc/src/lib/addresses.spec.ts b/packages/contracts-sdk/src/lib/helpers/addresses.spec.ts
similarity index 100%
rename from packages/misc/src/lib/addresses.spec.ts
rename to packages/contracts-sdk/src/lib/helpers/addresses.spec.ts
diff --git a/packages/misc/src/lib/addresses.ts b/packages/contracts-sdk/src/lib/helpers/addresses.ts
similarity index 76%
rename from packages/misc/src/lib/addresses.ts
rename to packages/contracts-sdk/src/lib/helpers/addresses.ts
index 12b6dea8de..34f778328c 100644
--- a/packages/misc/src/lib/addresses.ts
+++ b/packages/contracts-sdk/src/lib/helpers/addresses.ts
@@ -11,77 +11,11 @@ import {
NoWalletException,
ParamsMissingError,
} from '@lit-protocol/constants';
+import { publicKeyCompress } from '@lit-protocol/crypto';
+import { logger } from '@lit-protocol/logger';
+import { getStorageItem, setStorageItem } from '@lit-protocol/misc-browser';
import { DerivedAddresses } from '@lit-protocol/types';
-/**
- * Converts a public key between compressed and uncompressed formats.
- *
- * @param publicKey - Public key as a Buffer (33 bytes compressed or 65 bytes uncompressed)
- * @param compressed - Boolean flag indicating whether the output should be compressed
- * @returns Converted public key as a Buffer
- */
-export function publicKeyConvert(
- publicKey: Buffer,
- compressed: boolean = true
-): Buffer {
- if (compressed) {
- // Compress the public key (if it's not already compressed)
- if (publicKey.length === 65 && publicKey[0] === 0x04) {
- const x = publicKey.subarray(1, 33);
- const y = publicKey.subarray(33, 65);
- const prefix = y[y.length - 1] % 2 === 0 ? 0x02 : 0x03;
- return Buffer.concat([Buffer.from([prefix]), x]);
- }
- } else {
- // Decompress the public key
- if (
- publicKey.length === 33 &&
- (publicKey[0] === 0x02 || publicKey[0] === 0x03)
- ) {
- const x = publicKey.subarray(1);
- const y = decompressY(publicKey[0], x);
- return Buffer.concat([Buffer.from([0x04]), x, y]);
- }
- }
- // Return the original if no conversion is needed
- return publicKey;
-}
-
-/**
- * Decompresses the y-coordinate of a compressed public key.
- *
- * @param prefix - The first byte of the compressed public key (0x02 or 0x03)
- * @param x - The x-coordinate of the public key
- * @returns The decompressed y-coordinate as a Buffer
- */
-function decompressY(prefix: number, x: Buffer): Buffer {
- const p = BigInt(
- '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
- );
- const a = BigInt('0');
- const b = BigInt('7');
-
- const xBigInt = BigInt('0x' + x.toString('hex'));
- const rhs = (xBigInt ** 3n + a * xBigInt + b) % p;
- const yBigInt = modSqrt(rhs, p);
-
- const isEven = yBigInt % 2n === 0n;
- const y = isEven === (prefix === 0x02) ? yBigInt : p - yBigInt;
-
- return Buffer.from(y.toString(16).padStart(64, '0'), 'hex');
-}
-
-/**
- * Computes the modular square root of a number.
- *
- * @param a - The number to find the square root of
- * @param p - The modulus
- * @returns The square root modulo p
- */
-function modSqrt(a: bigint, p: bigint): bigint {
- return a ** ((p + 1n) / 4n) % p;
-}
-
/**
* Derives a Bitcoin address (P2PKH) from a public key.
*
@@ -133,7 +67,7 @@ function deriveCosmosAddress(
// If the Ethereum public key is uncompressed (130 characters), compress it
if (pubKeyBuffer.length === 65 && pubKeyBuffer[0] === 0x04) {
- pubKeyBuffer = Buffer.from(publicKeyConvert(pubKeyBuffer, true));
+ pubKeyBuffer = Buffer.from(publicKeyCompress(pubKeyBuffer));
}
// Hash the compressed public key with SHA-256
@@ -245,13 +179,17 @@ export const derivedAddresses = async (
const CACHE_KEY = 'lit-cached-pkps';
let cachedPkpJSON;
try {
- const cachedPkp = localStorage.getItem(CACHE_KEY);
+ const cachedPkp = getStorageItem(CACHE_KEY);
if (cachedPkp) {
cachedPkpJSON = JSON.parse(cachedPkp);
publicKey = cachedPkpJSON[pkpTokenId];
}
} catch (e) {
- console.error(e);
+ logger.error({
+ function: 'derivedAddresses',
+ msg: `Could not get ${CACHE_KEY} from storage. Continuing...`,
+ error: e,
+ });
}
if (!publicKey) {
@@ -287,18 +225,19 @@ export const derivedAddresses = async (
if (options.cacheContractCall) {
// trying to store key value pair in local storage
try {
- const cachedPkp = localStorage.getItem(CACHE_KEY);
- if (cachedPkp) {
- const cachedPkpJSON = JSON.parse(cachedPkp);
- cachedPkpJSON[pkpTokenId] = publicKey;
- localStorage.setItem(CACHE_KEY, JSON.stringify(cachedPkpJSON));
- } else {
- const cachedPkpJSON: Record = {};
- cachedPkpJSON[pkpTokenId] = publicKey;
- localStorage.setItem(CACHE_KEY, JSON.stringify(cachedPkpJSON));
- }
+ const cachedPkp = getStorageItem(CACHE_KEY);
+ const cachedPkpJSON: Record = cachedPkp
+ ? JSON.parse(cachedPkp)
+ : {};
+
+ cachedPkpJSON[pkpTokenId] = publicKey;
+ setStorageItem(CACHE_KEY, JSON.stringify(cachedPkpJSON));
} catch (e) {
- console.error(e);
+ logger.error({
+ function: 'derivedAddresses',
+ msg: `Could not get ${CACHE_KEY} from storage. Continuing...`,
+ error: e,
+ });
}
}
}
diff --git a/packages/contracts-sdk/src/lib/helpers/getBytes32FromMultihash.ts b/packages/contracts-sdk/src/lib/helpers/getBytes32FromMultihash.ts
index 40e3ddc199..8ac5d63b56 100644
--- a/packages/contracts-sdk/src/lib/helpers/getBytes32FromMultihash.ts
+++ b/packages/contracts-sdk/src/lib/helpers/getBytes32FromMultihash.ts
@@ -30,9 +30,6 @@ export interface CIDParser {
* const CID = require('multiformats/cid')
* const ipfsId = 'QmZKLGf3vgYsboM7WVUS9X56cJSdLzQVacNp841wmEDRkW'
* const {digest, hashFunction, size} = getBytes32FromMultihash(ipfsId, CID)
- * console.log(digest) // string
- * console.log(hashFunction) // number
- * console.log(size) // number
*
* @returns {IPFSHash}
*/
diff --git a/packages/contracts-sdk/src/lib/price-feed-info-manager.ts b/packages/contracts-sdk/src/lib/price-feed-info-manager.ts
index 9c3bf6c0da..39dd0ef07b 100644
--- a/packages/contracts-sdk/src/lib/price-feed-info-manager.ts
+++ b/packages/contracts-sdk/src/lib/price-feed-info-manager.ts
@@ -77,20 +77,6 @@ async function fetchPriceFeedInfo({
}
});
- // console.log(
- // 'getPriceFeedInfo()',
- // util.inspect(
- // {
- // epochId,
- // minNodeCount,
- // networkPrices: {
- // mapByAddress: networkPriceMap,
- // },
- // },
- // { depth: 4 }
- // )
- // );
-
return {
epochId,
minNodeCount,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 96715e1682..c6f1566eb9 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,2 +1,3 @@
+export * from './lib/helpers/endpoint-version';
+export * from './lib/helpers/most-common-value';
export * from './lib/lit-core';
-export * from './lib/endpoint-version';
diff --git a/packages/core/src/lib/endpoint-version.ts b/packages/core/src/lib/helpers/endpoint-version.ts
similarity index 71%
rename from packages/core/src/lib/endpoint-version.ts
rename to packages/core/src/lib/helpers/endpoint-version.ts
index 543d154eee..b2825bff85 100644
--- a/packages/core/src/lib/endpoint-version.ts
+++ b/packages/core/src/lib/helpers/endpoint-version.ts
@@ -1,3 +1,4 @@
+import { NetworkError } from '@lit-protocol/constants';
import { LitEndpoint } from '@lit-protocol/types';
/**
@@ -17,7 +18,15 @@ export const composeLitUrl = (params: {
try {
new URL(params.url);
} catch (error) {
- throw new Error(`[composeLitUrl] Invalid URL: "${params.url}"`);
+ throw new NetworkError(
+ {
+ info: {
+ url: params.url,
+ endpoint: params.endpoint,
+ },
+ },
+ `[composeLitUrl] Invalid URL: "${params.url}"`
+ );
}
const version = params.endpoint.version;
diff --git a/packages/core/src/lib/helpers/most-common-value.test.ts b/packages/core/src/lib/helpers/most-common-value.test.ts
new file mode 100644
index 0000000000..02df45ecf6
--- /dev/null
+++ b/packages/core/src/lib/helpers/most-common-value.test.ts
@@ -0,0 +1,19 @@
+import { mostCommonValue } from './most-common-value';
+
+describe('mostCommonValue', () => {
+ it('should get the most common string in an array', () => {
+ const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8];
+
+ const mostOccured = mostCommonValue(arr);
+
+ expect(mostOccured).toBe(8);
+ });
+
+ it('should get the last element of the array if every element only appears once', () => {
+ const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
+
+ const mostOccured = mostCommonValue(arr);
+
+ expect(mostOccured).toBe(0);
+ });
+});
diff --git a/packages/core/src/lib/helpers/most-common-value.ts b/packages/core/src/lib/helpers/most-common-value.ts
new file mode 100644
index 0000000000..060dab6878
--- /dev/null
+++ b/packages/core/src/lib/helpers/most-common-value.ts
@@ -0,0 +1,17 @@
+/**
+ *
+ * Find the element that occurs the most in an array
+ *
+ * @template T
+ * @param { T[] } arr
+ * @returns { T } the element that appeared the most
+ */
+export const mostCommonValue = (arr: T[]): T | undefined => {
+ return arr
+ .sort(
+ (a: T, b: T) =>
+ arr.filter((v: T) => v === a).length -
+ arr.filter((v: T) => v === b).length
+ )
+ .pop();
+};
diff --git a/packages/core/src/lib/lit-core.spec.ts b/packages/core/src/lib/lit-core.spec.ts
index b44c455656..3b1082c16f 100644
--- a/packages/core/src/lib/lit-core.spec.ts
+++ b/packages/core/src/lib/lit-core.spec.ts
@@ -1,12 +1,22 @@
import { InvalidEthBlockhash } from '@lit-protocol/constants';
+const logMock = jest.fn();
+
+jest.mock('pino', () => {
+ return {
+ pino: jest.fn(() => ({
+ info: logMock,
+ error: logMock,
+ })),
+ };
+});
+
import { LitCore } from './lit-core';
describe('LitCore', () => {
let core: LitCore;
describe('getLatestBlockhash', () => {
- let originalFetch: typeof fetch;
let originalDateNow: typeof Date.now;
const mockBlockhashUrl =
'https://block-indexer-url.com/get_most_recent_valid_block';
@@ -16,12 +26,11 @@ describe('LitCore', () => {
litNetwork: 'custom',
});
core['_blockHashUrl'] = mockBlockhashUrl;
- originalFetch = fetch;
originalDateNow = Date.now;
+ Date.now = jest.fn().mockReturnValue(1000000);
});
afterEach(() => {
- global.fetch = originalFetch;
Date.now = originalDateNow;
jest.clearAllMocks();
});
diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts
index 7ee0479e72..ff7e003e3a 100644
--- a/packages/core/src/lib/lit-core.ts
+++ b/packages/core/src/lib/lit-core.ts
@@ -2,6 +2,7 @@ import { ethers } from 'ethers';
import {
CENTRALISATION_BY_NETWORK,
+ Environment,
HTTP,
HTTPS,
InitError,
@@ -16,7 +17,6 @@ import {
LIT_NETWORK,
LIT_NETWORKS,
LitNodeClientNotReadyError,
- LOG_LEVEL,
NetworkError,
NodeError,
RPC_URL_BY_NETWORK,
@@ -27,18 +27,7 @@ import {
} from '@lit-protocol/constants';
import { LitContracts } from '@lit-protocol/contracts-sdk';
import { checkSevSnpAttestation, computeHDPubKey } from '@lit-protocol/crypto';
-import {
- bootstrapLogManager,
- isBrowser,
- isNode,
- log,
- logError,
- logErrorWithRequestId,
- logWithRequestId,
- mostCommonString,
- sendRequest,
- setMiscLitConfig,
-} from '@lit-protocol/misc';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import {
AuthSig,
BlockHashErrorResponse,
@@ -53,7 +42,8 @@ import {
SuccessNodePromises,
} from '@lit-protocol/types';
-import { composeLitUrl } from './endpoint-version';
+import { composeLitUrl } from './helpers/endpoint-version';
+import { mostCommonValue } from './helpers/most-common-value';
import {
CoreNodeConfig,
EpochCache,
@@ -118,6 +108,7 @@ export type LitNodeClientConfigWithDefaults = Required<
};
export class LitCore {
+ private readonly _coreLogger: Logger;
config: LitNodeClientConfigWithDefaults = {
alertWhenUnauthorized: false,
debug: true,
@@ -178,12 +169,10 @@ export class LitCore {
};
}
- // -- set global variables
- setMiscLitConfig(this.config);
- bootstrapLogManager(
- 'core',
- this.config.debug ? LOG_LEVEL.DEBUG : LOG_LEVEL.OFF
- );
+ this._coreLogger = getChildLogger({
+ module: 'LitCore',
+ ...(this.config.debug ? { level: 'debug' } : {}),
+ });
// -- configure local storage if not present
// LitNodeClientNodejs is a base for LitNodeClient
@@ -191,7 +180,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(
+ this._coreLogger.info(
'localstorage api not found, injecting persistence instance found in config'
);
// using Object defineProperty in order to set a property previously defined as readonly.
@@ -200,25 +189,16 @@ export class LitCore {
value: this.config.storageProvider?.provider,
});
} else if (
- isNode() &&
+ Environment.isNode &&
!globalThis.localStorage &&
!this.config.storageProvider?.provider
) {
- log(
+ this._coreLogger.info(
'Looks like you are running in NodeJS and did not provide a storage provider, your sessions will not be cached'
);
}
}
- // ========== Logger utilities ==========
- getLogsForRequestId = (id: string): string[] => {
- return globalThis.logManager.getLogsForId(id);
- };
-
- getRequestIds = (): Set => {
- return globalThis.logManager.LoggerIds;
- };
-
/**
* Retrieves the validator data including staking contract, epoch, minNodeCount, and bootstrapUrls.
* @returns An object containing the validator data.
@@ -262,10 +242,19 @@ export class LitCore {
);
}
- log('[_getValidatorData] epochInfo: ', epochInfo);
- log('[_getValidatorData] minNodeCount: ', minNodeCount);
- log('[_getValidatorData] Bootstrap urls: ', bootstrapUrls);
- log('[_getValidatorData] stakingContract: ', stakingContract.address);
+ this._coreLogger.info({ msg: '[_getValidatorData] epochInfo', epochInfo });
+ this._coreLogger.info({
+ msg: '[_getValidatorData] minNodeCount',
+ minNodeCount,
+ });
+ this._coreLogger.info({
+ msg: '[_getValidatorData] Bootstrap urls',
+ bootstrapUrls,
+ });
+ this._coreLogger.info({
+ msg: '[_getValidatorData] stakingContract',
+ address: stakingContract.address,
+ });
return {
stakingContract,
@@ -289,7 +278,7 @@ export class LitCore {
private async _handleStakingContractStateChange(
state: STAKING_STATES_VALUES
) {
- log(`New state detected: "${state}"`);
+ this._coreLogger.info(`New state detected: "${state}"`);
const validatorData = await this._getValidatorData();
@@ -303,7 +292,7 @@ export class LitCore {
if (CENTRALISATION_BY_NETWORK[this.config.litNetwork] !== 'centralised') {
// We don't need to handle node urls changing on centralised networks, since their validator sets are static
try {
- log(
+ this._coreLogger.info(
'State found to be new validator set locked, checking validator set'
);
const existingNodeUrls: string[] = [...this.config.bootstrapUrls];
@@ -322,11 +311,10 @@ export class LitCore {
The sdk should be able to understand its current execution environment and wait on an active
network request to the previous epoch's node set before changing over.
*/
- log(
- 'Active validator sets changed, new validators ',
+ this._coreLogger.info({
+ msg: 'Active validator sets changed, new validators. Check delta. Starting node connection',
delta,
- 'starting node connection'
- );
+ });
}
await this.connect();
@@ -335,10 +323,10 @@ export class LitCore {
// But for now, our every-30-second network sync will fix things in at most 30s from now.
// this.ready = false; Should we assume core is invalid if we encountered errors refreshing from an epoch change?
const { message = '' } = err as Error;
- logError(
- 'Error while attempting to reconnect to nodes after epoch transition:',
- message
- );
+ this._coreLogger.error({
+ msg: 'Error while attempting to reconnect to nodes after epoch transition',
+ message,
+ });
}
}
}
@@ -359,10 +347,10 @@ export class LitCore {
}
if (this._stakingContract) {
- log(
- 'listening for state change on staking contract: ',
- this._stakingContract.address
- );
+ this._coreLogger.info({
+ msg: 'listening for state change on staking contract',
+ address: this._stakingContract.address,
+ });
// Stash a function instance, because its identity must be consistent for '.off()' usage to work later
this._stakingContractListener = (state: STAKING_STATES_VALUES) => {
@@ -400,8 +388,6 @@ export class LitCore {
this.ready = false;
this._stopListeningForNewEpoch();
- // this._stopNetworkPolling();
- setMiscLitConfig(undefined);
}
_stopListeningForNewEpoch() {
@@ -490,7 +476,7 @@ export class LitCore {
{}
);
if (this.config.litNetwork === LIT_NETWORK.Custom) {
- log('using custom contracts: ', logAddresses);
+ this._coreLogger.info({ msg: 'using custom contracts', logAddresses });
}
}
@@ -517,8 +503,11 @@ export class LitCore {
this.ready = true;
- log(`🔥 lit is ready. "litNodeClient" variable is ready to use globally.`);
- log('current network config', {
+ this._coreLogger.info(
+ `🔥 lit is ready. "litNodeClient" variable is ready to use globally.`
+ );
+ this._coreLogger.info({
+ msg: 'current network config',
networkPubkey: this.networkPubKey,
networkPubKeySet: this.networkPubKeySet,
hdRootPubkeys: this.hdRootPubkeys,
@@ -527,7 +516,7 @@ export class LitCore {
});
// browser only
- if (isBrowser()) {
+ if (Environment.isBrowser) {
document.dispatchEvent(new Event('lit-ready'));
}
}
@@ -562,25 +551,30 @@ export class LitCore {
// node, even though its keys may be "ERR".
// Should we really track servers with ERR as keys?
if (
- keys.serverPubKey === 'ERR' ||
- keys.subnetPubKey === 'ERR' ||
- keys.networkPubKey === 'ERR' ||
- keys.networkPubKeySet === 'ERR'
+ [
+ keys.serverPubKey,
+ keys.subnetPubKey,
+ keys.networkPubKey,
+ keys.networkPubKeySet,
+ ].includes('ERR')
) {
- logErrorWithRequestId(
+ this._coreLogger.error({
requestId,
- 'Error connecting to node. Detected "ERR" in keys',
+ msg: 'Error connecting to node. Detected "ERR" in keys',
url,
- keys
- );
+ keys,
+ });
}
- log(`Handshake with ${url} returned keys: `, keys);
+ this._coreLogger.info({
+ msg: `Handshake with ${url} returned keys: `,
+ keys,
+ });
if (!keys.latestBlockhash) {
- logErrorWithRequestId(
+ this._coreLogger.error({
requestId,
- `Error getting latest blockhash from the node ${url}.`
- );
+ msg: `Error getting latest blockhash from the node ${url}.`,
+ });
}
// We force SEV checks on some networks even if the caller attempts to construct the client with them disabled
@@ -599,12 +593,12 @@ export class LitCore {
}
// actually verify the attestation by checking the signature against AMD certs
- log('Checking attestation against amd certs...');
+ this._coreLogger.info('Checking attestation against amd certs...');
try {
// ensure we won't try to use a node with an invalid attestation response
await checkSevSnpAttestation(attestation, challenge, url);
- log(`Lit Node Attestation verified for ${url}`);
+ this._coreLogger.info(`Lit Node Attestation verified for ${url}`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
throw new InvalidNodeAttestation(
@@ -617,7 +611,7 @@ export class LitCore {
);
}
} else if (this.config.litNetwork === LIT_NETWORK.Custom) {
- log(
+ this._coreLogger.info(
`Node attestation SEV verification is disabled. You must explicitly set "checkNodeAttestation" to true when using 'custom' network`
);
}
@@ -654,12 +648,7 @@ export class LitCore {
this.config.bootstrapUrls.length
} nodes. Please check your network connection and try again. Note that you can control this timeout with the connectTimeout config option which takes milliseconds.`;
- try {
- throw new InitError({}, msg);
- } catch (e) {
- logErrorWithRequestId(requestId, e);
- reject(e);
- }
+ reject(new InitError({ info: { requestId } }, msg));
}, this.config.connectTimeout);
}),
Promise.all(
@@ -690,17 +679,17 @@ export class LitCore {
serverKeys: Record;
requestId: string;
}): CoreNodeConfig {
- const latestBlockhash = mostCommonString(
+ const latestBlockhash = mostCommonValue(
Object.values(serverKeys).map(
(keysFromSingleNode) => keysFromSingleNode.latestBlockhash
)
);
if (!latestBlockhash) {
- logErrorWithRequestId(
+ this._coreLogger.error({
requestId,
- 'Error getting latest blockhash from the nodes.'
- );
+ msg: 'Error getting latest blockhash from the nodes.',
+ });
throw new InvalidEthBlockhash(
{
@@ -715,22 +704,22 @@ export class LitCore {
// pick the most common public keys for the subnet and network from the bunch, in case some evil node returned a bad key
return {
- subnetPubKey: mostCommonString(
+ subnetPubKey: mostCommonValue(
Object.values(serverKeys).map(
(keysFromSingleNode) => keysFromSingleNode.subnetPubKey
)
)!,
- networkPubKey: mostCommonString(
+ networkPubKey: mostCommonValue(
Object.values(serverKeys).map(
(keysFromSingleNode) => keysFromSingleNode.networkPubKey
)
)!,
- networkPubKeySet: mostCommonString(
+ networkPubKeySet: mostCommonValue(
Object.values(serverKeys).map(
(keysFromSingleNode) => keysFromSingleNode.networkPubKeySet
)
)!,
- hdRootPubkeys: mostCommonString(
+ hdRootPubkeys: mostCommonValue(
Object.values(serverKeys).map(
(keysFromSingleNode) => keysFromSingleNode.hdRootPubkeys
)
@@ -760,7 +749,7 @@ export class LitCore {
testResult,
};
} catch (error) {
- logError(`RPC URL failed: ${url}`);
+ this._coreLogger.error(`RPC URL failed: ${url}`);
}
}
return null;
@@ -781,15 +770,14 @@ export class LitCore {
this.lastBlockHashRetrieved &&
currentTime - this.lastBlockHashRetrieved < blockHashValidityDuration
) {
- log('Blockhash is still valid. No need to sync.');
+ this._coreLogger.info('Blockhash is still valid. No need to sync.');
return;
}
- log(
- 'Syncing state for new blockhash ',
- 'current blockhash: ',
- this.latestBlockhash
- );
+ this._coreLogger.info({
+ msg: 'Syncing state for new blockhash',
+ currentBlockhash: this.latestBlockhash,
+ });
try {
// This fetches from the lit propagation service so nodes will always have it
@@ -821,18 +809,20 @@ export class LitCore {
this.latestBlockhash = blockHashBody.blockhash;
this.lastBlockHashRetrieved = parseInt(timestamp) * 1000;
- log('Done syncing state new blockhash: ', this.latestBlockhash);
+ this._coreLogger.info({
+ msg: 'Done syncing state new blockhash',
+ latestBlockhash: this.latestBlockhash,
+ });
} catch (error: unknown) {
const err = error as BlockHashErrorResponse | Error;
- logError(
- 'Error while attempting to fetch new latestBlockhash:',
- err instanceof Error ? err.message : err.messages,
- 'Reason: ',
- err instanceof Error ? err : err.reason
- );
+ this._coreLogger.error({
+ msg: 'Error while attempting to fetch new latestBlockhash',
+ errorMessage: err instanceof Error ? err.message : err.messages,
+ reason: err instanceof Error ? err : err.reason,
+ });
- log(
+ this._coreLogger.info(
'Attempting to fetch blockhash manually using ethers with fallback RPC URLs...'
);
const { testResult } =
@@ -842,19 +832,23 @@ export class LitCore {
)) || {};
if (!testResult || !testResult.hash) {
- logError('All fallback RPC URLs failed. Unable to retrieve blockhash.');
+ this._coreLogger.error(
+ 'All fallback RPC URLs failed. Unable to retrieve blockhash.'
+ );
return;
}
try {
this.latestBlockhash = testResult.hash;
this.lastBlockHashRetrieved = testResult.timestamp;
- log(
- 'Successfully retrieved blockhash manually: ',
- this.latestBlockhash
- );
+ this._coreLogger.info({
+ msg: 'Successfully retrieved blockhash manually',
+ latestBlockhash: this.latestBlockhash,
+ });
} catch (ethersError) {
- logError('Failed to manually retrieve blockhash using ethers');
+ this._coreLogger.error(
+ 'Failed to manually retrieve blockhash using ethers'
+ );
}
}
}
@@ -898,7 +892,7 @@ export class LitCore {
endpoint: LIT_ENDPOINT.HANDSHAKE,
});
- log(`handshakeWithNode ${urlWithPath}`);
+ this._coreLogger.info(`handshakeWithNode ${urlWithPath}`);
const data = {
clientPublicKey: 'test',
@@ -923,7 +917,7 @@ export class LitCore {
}
if (!epochInfo) {
- log(
+ this._coreLogger.info(
'epochinfo not found. Not a problem, fetching current epoch state from staking contract'
);
try {
@@ -974,6 +968,41 @@ export class LitCore {
}
// ==================== SENDING COMMAND ====================
+ private async _sendRequest(
+ url: string,
+ req: RequestInit,
+ requestId: string
+ ): Promise {
+ try {
+ const response = await fetch(url, req);
+ const isJson = response.headers
+ .get('content-type')
+ ?.includes('application/json');
+
+ const data = isJson ? await response.json() : null;
+
+ if (!response.ok) {
+ // get error message from body or default to response status
+ const error = data || response.status;
+ return Promise.reject(error);
+ }
+
+ return data;
+ } catch (e) {
+ throw new NetworkError(
+ {
+ info: {
+ url,
+ req,
+ requestId,
+ },
+ cause: e,
+ },
+ `Error sending request to ${url}`
+ );
+ }
+ }
+
/**
*
* Send a command to nodes
@@ -998,11 +1027,11 @@ export class LitCore {
delete data.sessionSigs;
}
- logWithRequestId(
+ this._coreLogger.info({
requestId,
- `sendCommandToNode with url ${url} and data`,
- data
- );
+ msg: `sendCommandToNode with url ${url} and data`,
+ data,
+ });
const req: RequestInit = {
method: 'POST',
@@ -1016,7 +1045,7 @@ export class LitCore {
body: JSON.stringify(data),
};
- return sendRequest(url, req, requestId);
+ return this._sendRequest(url, req, requestId);
};
/**
@@ -1137,9 +1166,6 @@ export class LitCore {
minNodeCount
);
- // console.log(`successes: ${JSON.stringify(successes, null, 2)}`)
- // console.log(`errors: ${JSON.stringify(errors, null, 2)}`)
-
// -- case: success (when success responses are more than minNodeCount)
if (successes.length >= minNodeCount) {
return {
@@ -1168,13 +1194,13 @@ export class LitCore {
// -- case: if we're here, then we did not succeed. time to handle and report errors.
const mostCommonError = JSON.parse(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- mostCommonString(errors.map((r: any) => JSON.stringify(r)))!
+ mostCommonValue(errors.map((r: any) => JSON.stringify(r)))!
);
- logErrorWithRequestId(
- requestId || '',
- `most common error: ${JSON.stringify(mostCommonError)}`
- );
+ this._coreLogger.error({
+ requestId,
+ msg: `most common error: ${JSON.stringify(mostCommonError)}`,
+ });
return {
success: false,
@@ -1202,7 +1228,7 @@ export class LitCore {
res.error.errorCode === 'not_authorized') &&
this.config.alertWhenUnauthorized
) {
- log('You are not authorized to access this content');
+ this._coreLogger.info('You are not authorized to access this content');
}
throw new NodeError(
@@ -1241,7 +1267,9 @@ export class LitCore {
sigType: LIT_CURVE_VALUES = LIT_CURVE.EcdsaCaitSith
): Promise => {
if (!this.hdRootPubkeys) {
- logError('root public keys not found, have you connected to the nodes?');
+ this._coreLogger.error(
+ 'root public keys not found, have you connected to the nodes?'
+ );
throw new LitNodeClientNotReadyError(
{},
'root public keys not found, have you connected to the nodes?'
diff --git a/packages/core/src/lib/types.ts b/packages/core/src/lib/types.ts
index b93544addb..bdd7413182 100644
--- a/packages/core/src/lib/types.ts
+++ b/packages/core/src/lib/types.ts
@@ -1,6 +1,7 @@
-import { NodeAttestation } from '@lit-protocol/types';
import { ethers } from 'ethers';
+import { NodeAttestation } from '@lit-protocol/types';
+
export interface SendNodeCommand {
url: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/packages/crypto/src/lib/crypto.spec.ts b/packages/crypto/src/lib/crypto.spec.ts
index 8dd8980e7a..2898dc7e33 100644
--- a/packages/crypto/src/lib/crypto.spec.ts
+++ b/packages/crypto/src/lib/crypto.spec.ts
@@ -1,9 +1,50 @@
-import * as ethers from 'ethers';
+import { ed25519 } from '@noble/curves/ed25519';
+import { ethers } from 'ethers';
import { joinSignature } from 'ethers/lib/utils';
import { SigShare } from '@lit-protocol/types';
-import { combineEcdsaShares } from './crypto';
+import {
+ combineEcdsaShares,
+ generateSessionKeyPair,
+ publicKeyCompress,
+} from './crypto';
+
+describe('generateSessionKeyPair', () => {
+ it('generates a valid key pair where secretKey contains the publicKey', () => {
+ const sessionKeyPair = generateSessionKeyPair();
+
+ const publicKeyBytes = ethers.utils.arrayify(
+ '0x' + sessionKeyPair.publicKey
+ );
+ const secretKeyBytes = ethers.utils.arrayify(
+ '0x' + sessionKeyPair.secretKey
+ );
+
+ expect(secretKeyBytes.length).toBe(64);
+ expect(publicKeyBytes.length).toBe(32);
+
+ const derivedPublicKeyFromSecret = secretKeyBytes.slice(32);
+ expect(derivedPublicKeyFromSecret).toEqual(publicKeyBytes);
+ });
+
+ it('derives public key from secret key', () => {
+ const sessionKeyPair = generateSessionKeyPair();
+
+ const publicKeyBytes = ethers.utils.arrayify(
+ '0x' + sessionKeyPair.publicKey
+ );
+ const secretKeyBytes = ethers.utils.arrayify(
+ '0x' + sessionKeyPair.secretKey
+ );
+
+ const privateKeySeed = secretKeyBytes.slice(0, 32);
+
+ const derivedPublicKey = ed25519.getPublicKey(privateKeySeed);
+
+ expect(derivedPublicKey).toEqual(publicKeyBytes);
+ });
+});
describe('combine ECDSA Shares', () => {
it('Should recombine ECDSA signature shares', async () => {
@@ -67,3 +108,42 @@ describe('combine ECDSA Shares', () => {
expect(recoveredAddr).toEqual(addr);
});
});
+
+describe('publicKeyCompress', () => {
+ const COMPRESSED_PUBLIC_KEY_HEX =
+ '03bc0a563a9ddaf097ef31c3e936dda312acdbe2504953f0ea4ecb94ee737237df';
+ const COMPRESSED_PUBLIC_KEY = Buffer.from(COMPRESSED_PUBLIC_KEY_HEX, 'hex');
+
+ const UNCOMPRESSED_PUBLIC_KEY_HEX =
+ '04bc0a563a9ddaf097ef31c3e936dda312acdbe2504953f0ea4ecb94ee737237dfa2be4f2e38de7540ae64cf362b897d0f93567adc23ce0abc997c18edd269d73b';
+ const UNCOMPRESSED_PUBLIC_KEY = Buffer.from(
+ UNCOMPRESSED_PUBLIC_KEY_HEX,
+ 'hex'
+ );
+
+ it('should return the same compressed key when already compressed', () => {
+ const result = publicKeyCompress(COMPRESSED_PUBLIC_KEY);
+ expect(result).toEqual(COMPRESSED_PUBLIC_KEY);
+ });
+
+ it('should compress an uncompressed public key correctly', () => {
+ const result = publicKeyCompress(UNCOMPRESSED_PUBLIC_KEY);
+ expect(result).toEqual(COMPRESSED_PUBLIC_KEY);
+ });
+
+ it('should throw an error for invalid key length', () => {
+ const invalidKey = Buffer.from('1234567890abcdef', 'hex'); // 8 bytes only
+ expect(() => publicKeyCompress(invalidKey)).toThrow(
+ 'Invalid public key length. Expected 33 (compressed) or 65 (uncompressed) bytes.'
+ );
+ });
+
+ it('should throw an error if uncompressed key does not start with 0x04', () => {
+ // Create a 65-byte buffer with an invalid prefix (not 0x04)
+ const invalidUncompressed = Buffer.alloc(65, 0);
+ invalidUncompressed[0] = 0x05;
+ expect(() => publicKeyCompress(invalidUncompressed)).toThrow(
+ 'Invalid uncompressed public key format: does not start with 0x04.'
+ );
+ });
+});
diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts
index 54c46e5f97..613cfabf4d 100644
--- a/packages/crypto/src/lib/crypto.ts
+++ b/packages/crypto/src/lib/crypto.ts
@@ -1,7 +1,9 @@
+import { ed25519 } from '@noble/curves/ed25519';
import { joinSignature, splitSignature } from 'ethers/lib/utils';
import {
InvalidParamType,
+ InvalidSignatureError,
LIT_CURVE,
LIT_CURVE_VALUES,
NetworkError,
@@ -9,13 +11,9 @@ import {
UnknownError,
UnknownSignatureError,
} from '@lit-protocol/constants';
-import { log } from '@lit-protocol/misc';
-import { nacl } from '@lit-protocol/nacl';
+import { logger } from '@lit-protocol/logger';
+import { getStorageItem, setStorageItem } from '@lit-protocol/misc-browser';
import { NodeAttestation, SessionKeyPair, SigShare } from '@lit-protocol/types';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
import {
blsCombine,
blsDecrypt,
@@ -144,7 +142,13 @@ export const combineSignatureShares = async (
const signature = await blsCombine(sigShares);
if (signature.length !== 192) {
- throw new Error(
+ throw new InvalidSignatureError(
+ {
+ info: {
+ signature,
+ shares,
+ },
+ },
`Signature length is not 192. Got ${signature.length} instead.`
);
}
@@ -300,16 +304,63 @@ export const computeHDPubKey = async (
* @returns { SessionKeyPair } sessionKeyPair
*/
export const generateSessionKeyPair = (): SessionKeyPair => {
- const keyPair = nacl.sign.keyPair();
+ const privateKey = ed25519.utils.randomPrivateKey();
+ const publicKey = ed25519.getPublicKey(privateKey);
+ const combinedSecretKey = new Uint8Array(
+ privateKey.length + publicKey.length
+ );
+ combinedSecretKey.set(privateKey, 0);
+ combinedSecretKey.set(publicKey, privateKey.length);
const sessionKeyPair: SessionKeyPair = {
- publicKey: uint8arrayToString(keyPair.publicKey, 'base16'),
- secretKey: uint8arrayToString(keyPair.secretKey, 'base16'),
+ publicKey: Buffer.from(publicKey).toString('hex'),
+ secretKey: Buffer.from(combinedSecretKey).toString('hex'), // TODO check if concatenated public key is needed
};
return sessionKeyPair;
};
+/**
+ * Converts a public key between compressed and uncompressed formats.
+ *
+ * @param publicKey - Public key as a Buffer (33 bytes compressed or 65 bytes uncompressed)
+ * @returns Converted public key as a Buffer
+ */
+export function publicKeyCompress(publicKey: Buffer): Buffer {
+ // Validate the public key length is either 33 (compressed) or 65 (uncompressed)
+ if (publicKey.length !== 33 && publicKey.length !== 65) {
+ throw new InvalidSignatureError(
+ {
+ info: {
+ publicKey,
+ },
+ },
+ 'Invalid public key length. Expected 33 (compressed) or 65 (uncompressed) bytes.'
+ );
+ }
+
+ // If the key is already compressed (33 bytes), return it unchanged.
+ if (publicKey.length === 33) {
+ return publicKey;
+ }
+
+ if (publicKey[0] !== 0x04) {
+ throw new InvalidSignatureError(
+ {
+ info: {
+ publicKey,
+ },
+ },
+ 'Invalid uncompressed public key format: does not start with 0x04.'
+ );
+ }
+
+ const x = publicKey.subarray(1, 33);
+ const y = publicKey.subarray(33, 65);
+ const prefix = y[y.length - 1] % 2 === 0 ? 0x02 : 0x03;
+ return Buffer.concat([Buffer.from([prefix]), x]);
+}
+
async function doDecrypt(
ciphertextBase64: string,
shares: BlsSignatureShareJsonString[]
@@ -334,7 +385,7 @@ async function doDecrypt(
async function getAmdCert(url: string): Promise {
const proxyUrl = `${LIT_CORS_PROXY}/${url}`;
- log(
+ logger.info(
`[getAmdCert] Fetching AMD cert using proxy URL ${proxyUrl} to manage CORS restrictions and to avoid being rate limited by AMD.`
);
@@ -356,18 +407,26 @@ async function getAmdCert(url: string): Promise {
try {
return await fetchAsUint8Array(proxyUrl);
- } catch (e) {
- log(`[getAmdCert] Failed to fetch AMD cert from proxy:`, e);
+ } catch (error) {
+ logger.error({
+ function: 'getAmdCert',
+ msg: `Failed to fetch AMD cert from proxy`,
+ error,
+ });
}
// Try direct fetch only if proxy fails
- log('[getAmdCert] Attempting to fetch directly without proxy.');
+ logger.info('Attempting to fetch directly without proxy.');
try {
return await fetchAsUint8Array(url);
- } catch (e) {
- log('[getAmdCert] Direct fetch also failed:', e);
- throw e; // Re-throw to signal that both methods failed
+ } catch (error) {
+ logger.error({
+ function: 'getAmdCert',
+ msg: 'Direct fetch also failed',
+ error,
+ });
+ throw error; // Re-throw to signal that both methods failed
}
}
@@ -468,13 +527,13 @@ export const checkSevSnpAttestation = async (
const vcekUrl = await sevSnpGetVcekUrl(report);
// use local storage if we have one available
if (globalThis.localStorage) {
- log('Using local storage for certificate caching');
- vcekCert = localStorage.getItem(vcekUrl);
+ logger.info('Using local storage for certificate caching');
+ vcekCert = getStorageItem(vcekUrl);
if (vcekCert) {
- vcekCert = uint8arrayFromString(vcekCert, 'base64');
+ vcekCert = Buffer.from(vcekCert, 'base64');
} else {
vcekCert = await getAmdCert(vcekUrl);
- localStorage.setItem(vcekUrl, uint8arrayToString(vcekCert, 'base64'));
+ setStorageItem(vcekUrl, Buffer.from(vcekCert).toString('base64'));
}
} else {
const cache = ((
@@ -500,8 +559,3 @@ export const checkSevSnpAttestation = async (
// pass base64 encoded report to wasm wrapper
return sevSnpVerify(report, data, signatures, challenge, vcekCert);
};
-
-declare global {
- // eslint-disable-next-line no-var, @typescript-eslint/no-explicit-any
- var LitNodeClient: any;
-}
diff --git a/packages/encryption/.babelrc b/packages/encryption/.babelrc
deleted file mode 100644
index 158083d278..0000000000
--- a/packages/encryption/.babelrc
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "presets": [
- [
- "@nx/web/babel",
- {
- "useBuiltIns": "usage"
- }
- ]
- ]
-}
diff --git a/packages/encryption/.eslintrc.json b/packages/encryption/.eslintrc.json
deleted file mode 100644
index 9d9c0db55b..0000000000
--- a/packages/encryption/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/packages/encryption/README.md b/packages/encryption/README.md
deleted file mode 100644
index 82cd8d9b38..0000000000
--- a/packages/encryption/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Quick Start
-
-This submodule provides encryption and decryption of contents (string, file, etc.) respectively using a symmetric key, with the encrypted content returned as a Blob and the symmetric key as a Uint8Array
-
-### node.js / browser
-
-```
-yarn add @lit-protocol/encryption
-```
diff --git a/packages/encryption/jest.config.ts b/packages/encryption/jest.config.ts
deleted file mode 100644
index 1787e58530..0000000000
--- a/packages/encryption/jest.config.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/* eslint-disable */
-export default {
- displayName: 'encryption',
- preset: '../../jest.preset.js',
- globals: {
- 'ts-jest': {
- tsconfig: '/tsconfig.spec.json',
- },
- },
- transform: {
- '^.+\\.[t]s$': 'ts-jest',
- },
- moduleFileExtensions: ['ts', 'js', 'html'],
- coverageDirectory: '../../coverage/packages/encryption',
- setupFilesAfterEnv: ['../../jest.setup.js'],
-};
diff --git a/packages/encryption/package.json b/packages/encryption/package.json
deleted file mode 100644
index 0c7e2461a7..0000000000
--- a/packages/encryption/package.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "name": "@lit-protocol/encryption",
- "license": "MIT",
- "homepage": "https://github.com/Lit-Protocol/js-sdk",
- "repository": {
- "type": "git",
- "url": "https://github.com/LIT-Protocol/js-sdk"
- },
- "keywords": [
- "library"
- ],
- "bugs": {
- "url": "https://github.com/LIT-Protocol/js-sdk/issues"
- },
- "type": "commonjs",
- "publishConfig": {
- "access": "public",
- "directory": "../../dist/packages/encryption"
- },
- "gitHead": "0d7334c2c55f448e91fe32f29edc5db8f5e09e4b",
- "tags": [
- "universal"
- ],
- "browser": {
- "crypto": false,
- "stream": false
- },
- "version": "8.0.0-alpha.0",
- "main": "./dist/src/index.js",
- "typings": "./dist/src/index.d.ts"
-}
diff --git a/packages/encryption/project.json b/packages/encryption/project.json
deleted file mode 100644
index cf2972ffee..0000000000
--- a/packages/encryption/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "encryption",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/encryption/src",
- "projectType": "library",
- "targets": {
- "build": {
- "executor": "@nx/js:tsc",
- "outputs": ["{options.outputPath}"],
- "options": {
- "outputPath": "dist/packages/encryption",
- "main": "packages/encryption/src/index.ts",
- "tsConfig": "packages/encryption/tsconfig.lib.json",
- "assets": ["packages/encryption/*.md"],
- "updateBuildableProjectDepsInPackageJson": true
- }
- },
- "lint": {
- "executor": "@nx/linter:eslint",
- "outputs": ["{options.outputFile}"],
- "options": {
- "lintFilePatterns": ["packages/encryption/**/*.ts"]
- }
- },
- "test": {
- "executor": "@nx/jest:jest",
- "outputs": ["{workspaceRoot}/coverage/packages/encryption"],
- "options": {
- "jestConfig": "packages/encryption/jest.config.ts",
- "passWithNoTests": true
- }
- },
- "testWatch": {
- "executor": "@nx/jest:jest",
- "outputs": ["{workspaceRoot}/coverage/packages/encryption"],
- "options": {
- "jestConfig": "packages/encryption/jest.config.ts",
- "passWithNoTests": true,
- "watch": true
- }
- }
- },
- "tags": []
-}
diff --git a/packages/encryption/src/index.ts b/packages/encryption/src/index.ts
deleted file mode 100644
index 23436519e2..0000000000
--- a/packages/encryption/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './lib/encryption';
diff --git a/packages/encryption/src/lib/encryption.spec.ts b/packages/encryption/src/lib/encryption.spec.ts
deleted file mode 100644
index 978d752295..0000000000
--- a/packages/encryption/src/lib/encryption.spec.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { isValidBooleanExpression } from '@lit-protocol/misc';
-import { AccsDefaultParams } from '@lit-protocol/types';
-
-const conditionA: AccsDefaultParams = {
- contractAddress: '',
- standardContractType: '',
- chain: 'ethereum',
- method: 'eth_getBalance',
- parameters: [':userAddress', 'latest'],
- returnValueTest: {
- comparator: '>=',
- value: '10000000000000',
- },
-};
-
-const conditionB: AccsDefaultParams = {
- contractAddress: '0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2',
- standardContractType: 'ERC20',
- chain: 'ethereum',
- method: 'balanceOf',
- parameters: [':userAddress'],
- returnValueTest: {
- comparator: '>',
- value: '0',
- },
-};
-
-const groupValid: any = [conditionA, { operator: 'or' }, conditionB];
-
-const groupInvalid: any = [
- conditionA,
- { operator: 'or' },
- conditionB,
- { operator: 'and' },
-];
-
-describe('encryption', () => {
- it('should pass single access control condition', () => {
- expect(isValidBooleanExpression([conditionA])).toBeTruthy();
- });
- it('should pass boolean access control condition', () => {
- expect(
- isValidBooleanExpression([conditionA, { operator: 'or' }, conditionB])
- ).toBeTruthy();
- });
- it('should fail trailing boolean operator', () => {
- expect(
- isValidBooleanExpression([
- conditionA,
- { operator: 'or' },
- conditionB,
- { operator: 'and' },
- ])
- ).toBeFalsy();
- });
- it('should fail consecutive boolean operators', () => {
- expect(
- isValidBooleanExpression([
- conditionA,
- { operator: 'or' },
- { operator: 'and' },
- conditionB,
- ])
- ).toBeFalsy();
- });
- it('should fail only boolean operator', () => {
- expect(isValidBooleanExpression([{ operator: 'or' }])).toBeFalsy();
- });
- it('should fail consecutive boolean conditions', () => {
- expect(isValidBooleanExpression([conditionA, conditionB])).toBeFalsy();
- });
- it('should pass boolean condition and group', () => {
- expect(
- isValidBooleanExpression([conditionA, { operator: 'or' }, groupValid])
- ).toBeTruthy();
- });
- it('should pass boolean group and condition', () => {
- expect(
- isValidBooleanExpression([groupValid, { operator: 'and' }, conditionA])
- ).toBeTruthy();
- });
- it('should pass boolean group and group', () => {
- expect(
- isValidBooleanExpression([groupValid, { operator: 'and' }, groupValid])
- ).toBeTruthy();
- });
- it('should pass group only', () => {
- expect(isValidBooleanExpression([groupValid])).toBeTruthy();
- });
- it('should fail invalid group only', () => {
- expect(isValidBooleanExpression([groupInvalid])).toBeFalsy();
- });
- it('should fail trailing boolean operator with group', () => {
- expect(
- isValidBooleanExpression([groupValid, { operator: 'and' }])
- ).toBeFalsy();
- });
- it('should fail consecutive boolean operators with group', () => {
- expect(
- isValidBooleanExpression([
- groupValid,
- { operator: 'and' },
- { operator: 'or' },
- groupValid,
- ])
- ).toBeFalsy();
- });
- it('should fail boolean with invalid group', () => {
- expect(
- isValidBooleanExpression([groupValid, { operator: 'and' }, groupInvalid])
- ).toBeFalsy();
- });
- it('should fail boolean with invalid group and valid condition', () => {
- expect(
- isValidBooleanExpression([groupInvalid, { operator: 'or' }, conditionB])
- ).toBeFalsy();
- });
- it('should pass boolean condition after group', () => {
- expect(
- isValidBooleanExpression([
- conditionB,
- { operator: 'or' },
- groupValid,
- { operator: 'and' },
- conditionA,
- ])
- ).toBeTruthy();
- });
-});
diff --git a/packages/encryption/src/lib/encryption.ts b/packages/encryption/src/lib/encryption.ts
deleted file mode 100644
index b7377f24b6..0000000000
--- a/packages/encryption/src/lib/encryption.ts
+++ /dev/null
@@ -1,413 +0,0 @@
-import { EITHER_TYPE, InvalidParamType } from '@lit-protocol/constants';
-import { safeParams } from '@lit-protocol/misc';
-import {
- DecryptRequest,
- EncryptFileRequest,
- EncryptResponse,
- EncryptUint8ArrayRequest,
- EncryptStringRequest,
- ILitNodeClient,
- EncryptToJsonPayload,
- EncryptToJsonProps,
- DecryptFromJsonProps,
-} from '@lit-protocol/types';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
-
-/**
- * Encrypt a string or file using the LIT network public key and serialise all the metadata required to decrypt
- * i.e. accessControlConditions, evmContractConditions, solRpcConditions, unifiedAccessControlConditions & chain to JSON
- *
- * Useful for encrypting/decrypting data in IPFS or other storage without compressing it in a file.
- *
- * @param params { EncryptToJsonProps } - The params required to encrypt either a file or string and serialise it to JSON
- *
- * @returns { Promise } - JSON serialised string of the encrypted data and associated metadata necessary to decrypt it later
- *
- */
-export const encryptToJson = async (
- params: EncryptToJsonProps
-): Promise => {
- const {
- accessControlConditions,
- evmContractConditions,
- solRpcConditions,
- unifiedAccessControlConditions,
- chain,
- string,
- file,
- litNodeClient,
- } = params;
-
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'encryptToJson',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'encryptToJson',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- if (string !== undefined) {
- const { ciphertext, dataToEncryptHash } = await encryptString(
- {
- ...params,
- dataToEncrypt: string,
- },
- litNodeClient
- );
-
- return JSON.stringify({
- ciphertext,
- dataToEncryptHash,
- accessControlConditions,
- evmContractConditions,
- solRpcConditions,
- unifiedAccessControlConditions,
- chain,
- dataType: 'string',
- } as EncryptToJsonPayload);
- } else if (file) {
- const { ciphertext, dataToEncryptHash } = await encryptFile(
- { ...params, file },
- litNodeClient
- );
-
- return JSON.stringify({
- ciphertext,
- dataToEncryptHash,
- accessControlConditions,
- evmContractConditions,
- solRpcConditions,
- unifiedAccessControlConditions,
- chain,
- dataType: 'file',
- } as EncryptToJsonPayload);
- } else {
- throw new InvalidParamType(
- {
- info: {
- params,
- },
- },
- 'You must provide either "file" or "string"'
- );
- }
-};
-
-/**
- *
- * Decrypt & return a previously encrypted string (as a string) or file (as a Uint8Array) using the metadata included
- * in the parsed JSON data
- *
- * @param params { DecryptFromJsonProps } - The params required to decrypt a parsed JSON blob containing appropriate metadata
- *
- * @returns { Promise } - The decrypted `string` or file (as a `Uint8Array`) depending on `dataType` property in the parsed JSON provided
- *
- */
-export async function decryptFromJson(
- params: DecryptFromJsonProps
-): Promise<
- ReturnType | ReturnType
-> {
- const { authContext, parsedJsonData, litNodeClient } = params;
-
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'decryptFromJson',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'decryptFromJson',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- if (parsedJsonData.dataType === 'string') {
- return decryptToString(
- {
- accessControlConditions: parsedJsonData.accessControlConditions,
- evmContractConditions: parsedJsonData.evmContractConditions,
- solRpcConditions: parsedJsonData.solRpcConditions,
- unifiedAccessControlConditions:
- parsedJsonData.unifiedAccessControlConditions,
- ciphertext: parsedJsonData.ciphertext,
- dataToEncryptHash: parsedJsonData.dataToEncryptHash,
- chain: parsedJsonData.chain,
- authContext,
- },
- litNodeClient
- );
- } else if (parsedJsonData.dataType === 'file') {
- return decryptToFile(
- {
- accessControlConditions: parsedJsonData.accessControlConditions,
- evmContractConditions: parsedJsonData.evmContractConditions,
- solRpcConditions: parsedJsonData.solRpcConditions,
- unifiedAccessControlConditions:
- parsedJsonData.unifiedAccessControlConditions,
- ciphertext: parsedJsonData.ciphertext,
- dataToEncryptHash: parsedJsonData.dataToEncryptHash,
- chain: parsedJsonData.chain,
- authContext,
- },
- litNodeClient
- );
- } else {
- throw new InvalidParamType(
- {
- info: {
- dataType: parsedJsonData.dataType,
- params,
- },
- },
- 'dataType of %s is not valid. Must be "string" or "file".',
- parsedJsonData.dataType
- );
- }
-}
-
-// ---------- Local Helpers ----------
-
-/** Encrypt a uint8array. This is used to encrypt any uint8array that is to be locked via the Lit Protocol.
- * @param { EncryptUint8ArrayRequest } params - The params required to encrypt a uint8array
- * @param params.dataToEncrypt - (optional) The uint8array to encrypt
- * @param params.accessControlConditions - (optional) The access control conditions
- * @param params.evmContractConditions - (optional) The EVM contract conditions
- * @param params.solRpcConditions - (optional) The Solana RPC conditions
- * @param params.unifiedAccessControlConditions - The unified access control conditions
- * @param { ILitNodeClient } litNodeClient - The Lit Node Client
- *
- * @returns { Promise } - The encrypted uint8array and the hash of the data that was encrypted
- */
-export const encryptUint8Array = async (
- params: EncryptUint8ArrayRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'encryptUint8Array',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- },
- },
- 'Invalid params'
- );
-
- return litNodeClient.encrypt({
- ...params,
- });
-};
-
-/**
- * Decrypt a cyphertext into a Uint8Array that was encrypted with the encryptUint8Array function.
- *
- * @param { DecryptRequest } params - The params required to decrypt a string
- * @param { ILitNodeClient } litNodeClient - The Lit Node Client
- *
- * @returns { Promise } - The decrypted `Uint8Array`
- */
-export const decryptToUint8Array = async (
- params: DecryptRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'decrypt',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'decryptToUint8Array',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- const { decryptedData } = await litNodeClient.decrypt(params);
-
- return decryptedData;
-};
-
-/**
- *
- * Encrypt a string. This is used to encrypt any string that is to be locked via the Lit Protocol.
- *
- * @param { EncryptStringRequest } params - The params required to encrypt a string
- * @param params.dataToEncrypt - (optional) The string to encrypt
- * @param params.accessControlConditions - (optional) The access control conditions
- * @param params.evmContractConditions - (optional) The EVM contract conditions
- * @param params.solRpcConditions - (optional) The Solana RPC conditions
- * @param params.unifiedAccessControlConditions - The unified access control conditions
- * @param { ILitNodeClient } litNodeClient - The Lit Node Client
- *
- * @returns { Promise } - The encrypted string and the hash of the string
- */
-export const encryptString = async (
- params: EncryptStringRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'encryptString',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'encryptString',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- return litNodeClient.encrypt({
- ...params,
- dataToEncrypt: uint8arrayFromString(params.dataToEncrypt, 'utf8'),
- });
-};
-
-/**
- *
- * Decrypt ciphertext into a string that was encrypted with the encryptString function.
- *
- * @param { DecryptRequest } params - The params required to decrypt a string
- * @param { ILitNodeClient } litNodeClient - The Lit Node Client
-
- * @returns { Promise } - The decrypted string
- */
-export const decryptToString = async (
- params: DecryptRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'decrypt',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'decryptToString',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- const { decryptedData } = await litNodeClient.decrypt(params);
-
- return uint8arrayToString(decryptedData, 'utf8');
-};
-
-/**
- *
- * Encrypt a file without doing any compression or packing. This is useful for large files. A 1gb file can be encrypted in only 2 seconds, for example.
- *
- * @param { EncryptFileRequest } params - The params required to encrypt a file
- * @param { ILitNodeClient } litNodeClient - The lit node client to use to encrypt the file
- *
- * @returns { Promise } - The encrypted file and the hash of the file
- */
-export const encryptFile = async (
- params: EncryptFileRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'encryptFile',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'encryptFile',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- // encrypt the file
- const fileAsArrayBuffer = await params.file.arrayBuffer();
-
- return litNodeClient.encrypt({
- ...params,
- dataToEncrypt: new Uint8Array(fileAsArrayBuffer),
- });
-};
-
-/**
- *
- * Decrypt a file that was encrypted with the encryptFile function, without doing any uncompressing or unpacking. This is useful for large files. A 1gb file can be decrypted in only 1 second, for example.
- *
- * @param { DecryptRequest } params - The params required to decrypt a file
- * @param { ILitNodeClient } litNodeClient - The lit node client to use to decrypt the file
- *
- * @returns { Promise } - The decrypted file
- */
-export const decryptToFile = async (
- params: DecryptRequest,
- litNodeClient: ILitNodeClient
-): Promise => {
- // -- validate
- const paramsIsSafe = safeParams({
- functionName: 'decrypt',
- params,
- });
-
- if (paramsIsSafe.type === EITHER_TYPE.ERROR)
- throw new InvalidParamType(
- {
- info: {
- params,
- function: 'decryptToFile',
- },
- cause: paramsIsSafe.result,
- },
- 'Invalid params'
- );
-
- const { decryptedData } = await litNodeClient.decrypt(params);
-
- return decryptedData;
-};
diff --git a/packages/encryption/tsconfig.json b/packages/encryption/tsconfig.json
deleted file mode 100644
index f5b85657a8..0000000000
--- a/packages/encryption/tsconfig.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "module": "commonjs",
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitOverride": true,
- "noPropertyAccessFromIndexSignature": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true
- },
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.lib.json"
- },
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/packages/encryption/tsconfig.lib.json b/packages/encryption/tsconfig.lib.json
deleted file mode 100644
index e85ef50f65..0000000000
--- a/packages/encryption/tsconfig.lib.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "declaration": true,
- "types": []
- },
- "include": ["**/*.ts"],
- "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
-}
diff --git a/packages/encryption/tsconfig.spec.json b/packages/encryption/tsconfig.spec.json
deleted file mode 100644
index a2f7dd30d7..0000000000
--- a/packages/encryption/tsconfig.spec.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "module": "commonjs",
- "types": ["jest", "node"],
- "allowJs": true
- },
- "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
-}
diff --git a/packages/event-listener/README.md b/packages/event-listener/README.md
index a6a4ab0d2a..7bbb29e992 100644
--- a/packages/event-listener/README.md
+++ b/packages/event-listener/README.md
@@ -254,6 +254,27 @@ async function bridgeBaseSepoliaUSDCToEthereumSepolia() {
const ethPrivateKey = '0xTHE_PKP_AUTHORIZED_SIGNER_PRIVATE_KEY';
const stateMachine = StateMachine.fromDefinition({
+ // Extend the action respository with a custom action we will define later. For example to send notification to the machine owner on transactions
+ actionRepository: {
+ notify: class NotificationAction extends Action {
+ constructor({
+ stateMachine,
+ customParam,
+ }: {
+ stateMachine: StateMachine;
+ customParam: string;
+ }) {
+ super({
+ debug,
+ function: async () => {
+ const transferData = stateMachine.getFromContext('transfer');
+ console.log('customParam', customParam);
+ console.log('transferData', transferData);
+ },
+ });
+ }
+ },
+ },
privateKey: ethPrivateKey, // Used only for authorization here, minting was done previously
context: {
// We can prepopulate the context, for example setting the pkp here instead of using state.usePkp later
@@ -371,6 +392,11 @@ async function bridgeBaseSepoliaUSDCToEthereumSepolia() {
},
],
},
+ {
+ // Our custom action to notify about the just executed transfer transaction
+ key: 'notify',
+ customParam: 'OUR_CUSTOM_PARAM',
+ },
],
// Going back to waitForFunds to suspend machine if we need more sepolia eth or sepolia USDC
transitions: [{ toState: 'waitForFunds' }],
diff --git a/packages/event-listener/src/index.ts b/packages/event-listener/src/index.ts
index 12fc9ac474..a4dbd4f99e 100644
--- a/packages/event-listener/src/index.ts
+++ b/packages/event-listener/src/index.ts
@@ -1,3 +1,4 @@
+export * from './lib/actions';
export * from './lib/listeners';
export * from './lib/states';
export * from './lib/state-machine';
diff --git a/packages/event-listener/src/lib/actions/index.ts b/packages/event-listener/src/lib/actions/index.ts
index 9291631380..bbe79ead1b 100644
--- a/packages/event-listener/src/lib/actions/index.ts
+++ b/packages/event-listener/src/lib/actions/index.ts
@@ -1,5 +1,18 @@
+import { LitActionAction } from './lit-action';
+import { LogContextAction } from './log-context';
+import { MintPkpAction } from './mint-pkp';
+import { TransactionAction } from './transaction';
+import { ActionConstructor } from '../types';
+
export * from './action';
export * from './lit-action';
export * from './log-context';
export * from './mint-pkp';
export * from './transaction';
+
+export const ACTION_REPOSITORY: Record = {
+ context: LogContextAction,
+ litAction: LitActionAction,
+ transaction: TransactionAction,
+ usePkp: MintPkpAction,
+};
diff --git a/packages/event-listener/src/lib/actions/log-context.ts b/packages/event-listener/src/lib/actions/log-context.ts
index 4196d3e74c..3f383bfd17 100644
--- a/packages/event-listener/src/lib/actions/log-context.ts
+++ b/packages/event-listener/src/lib/actions/log-context.ts
@@ -1,3 +1,5 @@
+import { logger } from '@lit-protocol/logger';
+
import { Action } from './action';
import { StateMachine } from '../state-machine';
@@ -10,10 +12,10 @@ interface LogContextActionParams {
export class LogContextAction extends Action {
constructor(params: LogContextActionParams) {
const logContextFunction = async () => {
- console.log(
- `State Machine context: `,
- params.stateMachine.getFromContext(params.path)
- );
+ logger.info({
+ msg: `State Machine context`,
+ context: params.stateMachine.getFromContext(params.path),
+ });
};
super({
diff --git a/packages/event-listener/src/lib/actions/mint-pkp.ts b/packages/event-listener/src/lib/actions/mint-pkp.ts
index 353b6f79c7..5085a5169d 100644
--- a/packages/event-listener/src/lib/actions/mint-pkp.ts
+++ b/packages/event-listener/src/lib/actions/mint-pkp.ts
@@ -1,3 +1,5 @@
+import { logger } from '@lit-protocol/logger';
+
import { Action } from './action';
import { StateMachine } from '../state-machine';
@@ -12,7 +14,7 @@ export class MintPkpAction extends Action {
const mintingReceipt =
await params.stateMachine.litContracts.pkpNftContractUtils.write.mint();
const pkp = mintingReceipt.pkp;
- params.debug && console.log(`Minted PKP: ${pkp}`);
+ params.debug && logger.info(`Minted PKP: ${pkp}`);
params.stateMachine.setToContext('activePkp', pkp);
};
diff --git a/packages/event-listener/src/lib/listeners/fetch.ts b/packages/event-listener/src/lib/listeners/fetch.ts
index 681cd94bba..74e1c1d06d 100644
--- a/packages/event-listener/src/lib/listeners/fetch.ts
+++ b/packages/event-listener/src/lib/listeners/fetch.ts
@@ -1,3 +1,5 @@
+import { logger } from '@lit-protocol/logger';
+
import { Listener } from './listener';
interface FetchListenerConfig {
@@ -32,7 +34,7 @@ export class FetchListener extends Listener {
this.emit(value);
}
} catch (error) {
- console.error('FetchListener error:', error);
+ logger.error({ msg: 'FetchListener error:', error });
}
}, pollInterval);
},
diff --git a/packages/event-listener/src/lib/state-machine.ts b/packages/event-listener/src/lib/state-machine.ts
index 049f75f19e..e91571ce7f 100644
--- a/packages/event-listener/src/lib/state-machine.ts
+++ b/packages/event-listener/src/lib/state-machine.ts
@@ -7,14 +7,9 @@ import {
} from '@lit-protocol/constants';
import { LitContracts } from '@lit-protocol/contracts-sdk';
import { LitNodeClient } from '@lit-protocol/lit-node-client';
+import { logger } from '@lit-protocol/logger';
-import {
- Action,
- LitActionAction,
- LogContextAction,
- MintPkpAction,
- TransactionAction,
-} from './actions';
+import { Action, ACTION_REPOSITORY } from './actions';
import { MachineContext } from './context/machine-context';
import {
ContractEventData,
@@ -26,6 +21,7 @@ import {
import { State, StateParams } from './states';
import { CheckFn, Transition } from './transitions';
import {
+ ActionConstructor,
ActionDefinition,
BaseStateMachineParams,
ContextOrLiteral,
@@ -59,6 +55,7 @@ export class StateMachine {
public id: string;
public status: MachineStatus = 'stopped';
+ private readonly actionsRepository: Record;
private states = new Map();
private transitions = new Map>();
private currentState?: State;
@@ -73,6 +70,10 @@ export class StateMachine {
...params.context,
});
+ this.actionsRepository = {
+ ...ACTION_REPOSITORY,
+ ...params.actionRepository,
+ };
this.litNodeClient = params.litNodeClient;
this.litContracts = params.litContracts;
this.privateKey = params.privateKey;
@@ -124,6 +125,10 @@ export class StateMachine {
litContracts: litContractsInstance,
privateKey,
onError,
+ actionRepository: {
+ ...ACTION_REPOSITORY,
+ ...machineConfig.actionRepository,
+ },
});
const stateTransitions = [] as TransitionDefinition[];
@@ -382,17 +387,17 @@ export class StateMachine {
// Aggregate (AND) all listener checks to a single function result
transitionConfig.check = async (values) => {
this.debug &&
- console.log(
- `${transitionDefinition.fromState} -> ${transitionDefinition.toState} values`,
- values
- );
+ logger.info({
+ msg: `${transitionDefinition.fromState} -> ${transitionDefinition.toState} values`,
+ values,
+ });
return Promise.all(checks.map((check) => check(values))).then(
(results) => {
this.debug &&
- console.log(
- `${transitionDefinition.fromState} -> ${transitionDefinition.toState} results`,
- results
- );
+ logger.info({
+ msg: `${transitionDefinition.fromState} -> ${transitionDefinition.toState} results`,
+ results,
+ });
return results.every((result) => result);
}
);
@@ -410,7 +415,7 @@ export class StateMachine {
initialState: string,
onStop?: voidAsyncFunction
): Promise {
- this.debug && console.log('Starting state machine...');
+ this.debug && logger.info('Starting state machine...');
await Promise.all([
this.litContracts.connect(),
@@ -421,7 +426,7 @@ export class StateMachine {
await this.enterState(initialState);
this.status = 'running';
- this.debug && console.log('State machine started');
+ this.debug && logger.info('State machine started');
}
/**
@@ -470,20 +475,21 @@ export class StateMachine {
* Stops the state machine by exiting the current state and not moving to another one.
*/
public async stopMachine(): Promise {
- this.debug && console.log('Stopping state machine...');
+ this.debug && logger.info('Stopping state machine...');
this.status = 'stopped';
await this.exitCurrentState();
await this.onStopCallback?.();
- this.debug && console.log('State machine stopped');
+ this.debug && logger.info('State machine stopped');
}
/**
* Stops listening on the current state's transitions and exits the current state.
*/
private async exitCurrentState(): Promise {
- this.debug && console.log('exitCurrentState', this.currentState?.key);
+ this.debug &&
+ logger.info({ msg: 'exitCurrentState', state: this.currentState?.key });
const currentTransitions =
this.transitions.get(this.currentState?.key ?? '') ??
@@ -514,7 +520,7 @@ export class StateMachine {
`State ${stateKey} not found`
);
}
- this.debug && console.log('enterState', state.key);
+ this.debug && logger.info({ msg: 'enterState', state: state.key });
await state.enter();
const nextTransitions =
this.transitions.get(state.key) ?? new Map();
@@ -542,7 +548,7 @@ export class StateMachine {
);
}
if (this.currentState === nextState) {
- console.warn(
+ logger.warn(
`State ${stateKey} is already active. Skipping state change.`
);
return;
@@ -569,66 +575,18 @@ export class StateMachine {
): voidAsyncFunction {
const actions = [] as Action[];
- actionDefinitions.forEach((action) => {
- switch (action.key) {
- case 'context':
- if (typeof action.log?.path === 'string') {
- actions.push(
- new LogContextAction({
- debug: this.debug,
- stateMachine: this,
- path: action.log.path,
- })
- );
- }
- break;
- case 'litAction':
- actions.push(
- new LitActionAction({
- debug: this.debug,
- stateMachine: this,
- ...action,
- })
- );
- break;
- case 'transaction':
- actions.push(
- new TransactionAction({
- debug: this.debug,
- stateMachine: this,
- ...action,
- })
- );
- break;
- case 'usePkp':
- if ('pkp' in action) {
- this.context.set(
- 'activePkp',
- this.resolveContextPathOrLiteral(action.pkp)
- );
- } else if ('mint' in action) {
- const mintPkpAction = new MintPkpAction({
- debug: this.debug,
- stateMachine: this,
- });
- actions.push(mintPkpAction);
- }
- if (this.debug) {
- const activePkp = this.context.get('activePkp');
- console.log(`Machine configured to use pkp ${activePkp}`);
- }
- break;
- default:
- throw new AutomationError(
- {
- info: {
- action,
- },
- },
- `Unknown action. Check error info.`
- );
+ for (const action of actionDefinitions) {
+ const ActionCtor = this.actionsRepository[action.key];
+ if (!ActionCtor) {
+ throw new AutomationError(
+ { info: { action } },
+ `Action key "${action.key}" not found in action repository`
+ );
}
- });
+ actions.push(
+ new ActionCtor({ debug: this.debug, stateMachine: this, ...action })
+ );
+ }
return async () => {
await Promise.all(actions.map((action) => action.run())).catch((err) => {
@@ -665,7 +623,7 @@ export class StateMachine {
}
// Throwing when stopping could hide above error
- this.stopMachine().catch(console.error);
+ this.stopMachine().catch((error) => logger.error({ error }));
}
}
diff --git a/packages/event-listener/src/lib/states/state.ts b/packages/event-listener/src/lib/states/state.ts
index b9501c62ba..7b712d261b 100644
--- a/packages/event-listener/src/lib/states/state.ts
+++ b/packages/event-listener/src/lib/states/state.ts
@@ -1,3 +1,5 @@
+import { logger } from '@lit-protocol/logger';
+
import { voidAsyncFunction } from '../types';
export interface BaseStateParams {
@@ -29,7 +31,7 @@ export class State {
* Executes the onEnter action for the state.
*/
async enter() {
- this.debug && console.log(`enter ${this.key}`);
+ this.debug && logger.info(`enter ${this.key}`);
await this.onEnter?.();
}
@@ -37,7 +39,7 @@ export class State {
* Executes the onExit action for the state.
*/
async exit() {
- this.debug && console.log(`exit ${this.key}`);
+ this.debug && logger.info(`exit ${this.key}`);
await this.onExit?.();
}
}
diff --git a/packages/event-listener/src/lib/transitions/transition.ts b/packages/event-listener/src/lib/transitions/transition.ts
index 8b7ed60b1c..0306f5db67 100644
--- a/packages/event-listener/src/lib/transitions/transition.ts
+++ b/packages/event-listener/src/lib/transitions/transition.ts
@@ -1,3 +1,5 @@
+import { logger } from '@lit-protocol/logger';
+
import { Listener } from '../listeners';
import { onError } from '../types';
@@ -75,13 +77,13 @@ export class Transition {
*/
async startListening() {
try {
- this.debug && console.log('startListening');
+ this.debug && logger.info('startListening');
await Promise.all(this.listeners.map((listener) => listener.start()));
if (!this.listeners.length) {
// If the transition does not have any listeners it will never emit. Therefore, we "match" automatically on next event loop
setTimeout(() => {
- this.debug && console.log('Transition without listeners: auto match');
+ this.debug && logger.info('Transition without listeners: auto match');
this.onMatch([]);
}, 0);
}
@@ -99,7 +101,7 @@ export class Transition {
*/
async stopListening() {
try {
- this.debug && console.log('stopListening');
+ this.debug && logger.info('stopListening');
this.queue.length = 0; // Flush the queue as there might be more value arrays to check
await Promise.all(this.listeners.map((listener) => listener.stop()));
} catch (e) {
@@ -129,10 +131,10 @@ export class Transition {
const isMatch = this.check ? await this.check(currentValues) : true;
if (isMatch) {
- this.debug && console.log('match', currentValues);
+ this.debug && logger.info({ msg: 'match', values: currentValues });
await this.onMatch?.(currentValues);
} else {
- this.debug && console.log('mismatch', currentValues);
+ this.debug && logger.info({ msg: 'mismatch', values: currentValues });
await this.onMismatch?.(currentValues);
}
}
diff --git a/packages/event-listener/src/lib/types.ts b/packages/event-listener/src/lib/types.ts
index 1ec982857c..cf19f2d8d0 100644
--- a/packages/event-listener/src/lib/types.ts
+++ b/packages/event-listener/src/lib/types.ts
@@ -3,6 +3,7 @@ import { ethers } from 'ethers';
import { LitContracts } from '@lit-protocol/contracts-sdk';
import { LitNodeClient } from '@lit-protocol/lit-node-client';
+import { Action, ActionParams } from './actions/action';
import { BaseTransitionParams } from './transitions';
export type Address = `0x${string}`;
@@ -35,6 +36,13 @@ export interface UpdatesContext {
}
// Action Types
+export type ActionConstructor = new (params: any) => Action;
+
+export interface RawActionDefinition {
+ key: string;
+ [actionProperty: string]: unknown;
+}
+
export interface LitActionActionDefinition {
key: 'litAction';
code?: ContextOrLiteral;
@@ -96,6 +104,7 @@ export interface UseCapacityNFTActionDefinition {
}
export type ActionDefinition =
+ | RawActionDefinition
| ContextActionDefinition
| LitActionActionDefinition
| MintCapacityNFTActionDefinition
@@ -176,6 +185,7 @@ export interface TransitionParams
// Machine Types
export interface BaseStateMachineParams {
+ actionRepository?: Record;
context?: Record;
debug?: boolean;
litContracts: LitContracts;
diff --git a/packages/event-listener/src/lib/utils/chain.ts b/packages/event-listener/src/lib/utils/chain.ts
index 91025ee327..dc94bd4a6c 100644
--- a/packages/event-listener/src/lib/utils/chain.ts
+++ b/packages/event-listener/src/lib/utils/chain.ts
@@ -1,18 +1,36 @@
import { ethers } from 'ethers';
-import { LIT_EVM_CHAINS } from '@lit-protocol/constants';
+import {
+ LIT_EVM_CHAINS,
+ InvalidArgumentException,
+ UnsupportedChainException,
+} from '@lit-protocol/constants';
export function getEvmChain(evmChainId: ethers.BigNumberish) {
const evmChainIdNumber = ethers.BigNumber.from(evmChainId).toNumber();
if (evmChainIdNumber === 0) {
- throw new Error('EVM chainId cannot be 0');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ evmChainId: evmChainIdNumber,
+ },
+ },
+ 'EVM chainId cannot be 0'
+ );
}
const chain = Object.values(LIT_EVM_CHAINS).find(
(chain) => chain.chainId === evmChainIdNumber
);
if (!chain) {
- throw new Error(`EVM chain with chainId ${evmChainId} not found`);
+ throw new UnsupportedChainException(
+ {
+ info: {
+ evmChainId: evmChainIdNumber,
+ },
+ },
+ `EVM chain with chainId ${evmChainId} not found`
+ );
}
return chain;
diff --git a/packages/event-listener/src/lib/utils/erc20.ts b/packages/event-listener/src/lib/utils/erc20.ts
index b1e04abd37..61bc76ab05 100644
--- a/packages/event-listener/src/lib/utils/erc20.ts
+++ b/packages/event-listener/src/lib/utils/erc20.ts
@@ -1,5 +1,7 @@
import { ethers } from 'ethers';
+import { InvalidArgumentException } from '@lit-protocol/constants';
+
import { Address, BalanceTransitionDefinition } from '../types';
export const ERC20ABI = [
@@ -69,7 +71,15 @@ export function getBalanceTransitionCheck(
case '>':
return addressBalance.gt(targetAmount);
default:
- throw new Error(`Unrecognized comparator ${comparator}`);
+ throw new InvalidArgumentException(
+ {
+ info: {
+ comparator,
+ balance,
+ },
+ },
+ `Unrecognized comparator ${comparator}`
+ );
}
};
diff --git a/packages/lit-node-client/src/index.ts b/packages/lit-node-client/src/index.ts
index 038e4480e7..b98ea523c1 100644
--- a/packages/lit-node-client/src/index.ts
+++ b/packages/lit-node-client/src/index.ts
@@ -8,12 +8,4 @@ export {
humanizeAccessControlConditions,
} from '@lit-protocol/access-control-conditions';
-export {
- base64StringToBlob,
- blobToBase64String,
-} from '@lit-protocol/misc-browser';
-
-export {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
+export { validateSessionSig } from './lib/helpers/session-sigs-validator';
diff --git a/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.test.ts b/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.test.ts
new file mode 100644
index 0000000000..bd27d12437
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.test.ts
@@ -0,0 +1,159 @@
+import { assembleMostCommonResponse } from './assemble-most-common-response';
+
+describe('assembleMostCommonResponse', () => {
+ it('should return an empty object when given an empty array', () => {
+ const responses: object[] = [];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({});
+ });
+
+ it('should return the correct most common values for simple objects', () => {
+ const responses = [
+ { color: 'red', size: 'large' },
+ { color: 'blue', size: 'medium' },
+ { color: 'red', size: 'large' },
+ { color: 'red', size: 'small' },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ color: 'red', size: 'large' });
+ });
+
+ it('should handle objects with different keys', () => {
+ const responses = [
+ { name: 'Alice', age: 30 },
+ { name: 'Bob', city: 'New York' },
+ { name: 'Alice', city: 'Los Angeles' },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ name: 'Alice', age: 30, city: 'Los Angeles' });
+ });
+
+ it('should handle nested objects correctly', () => {
+ const responses = [
+ {
+ address: { city: 'New York', country: 'USA' },
+ status: 'active',
+ },
+ {
+ address: { city: 'Los Angeles', country: 'USA' },
+ status: 'inactive',
+ },
+ {
+ address: { city: 'New York', country: 'Canada' },
+ status: 'active',
+ },
+ {
+ address: { city: 'New York', country: 'USA' },
+ status: 'active',
+ },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({
+ address: { city: 'New York', country: 'USA' },
+ status: 'active',
+ });
+ });
+
+ it('should handle undefined and empty string values', () => {
+ const responses = [
+ { name: 'Alice', value: undefined },
+ { name: 'Bob', value: 'test' },
+ { name: 'Alice', value: '' },
+ { name: 'Alice', value: 'test' },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ name: 'Alice', value: 'test' });
+ });
+
+ it('should handle undefined and empty string values in nested object', () => {
+ const responses = [
+ { person: { name: 'Alice', value: undefined } },
+ { person: { name: 'Bob', value: 'test' } },
+ { person: { name: 'Alice', value: '' } },
+ { person: { name: 'Alice', value: 'test' } },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ person: { name: 'Alice', value: 'test' } });
+ });
+
+ it('should return undefined if all values are undefined or empty string', () => {
+ const responses = [
+ { name: 'Alice', value: undefined },
+ { name: 'Bob', value: '' },
+ { name: 'Alice', value: undefined },
+ { name: 'Alice', value: '' },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ name: 'Alice', value: undefined });
+ });
+
+ it('should handle nested object with different depth', () => {
+ const responses = [
+ { data: { level1: { level2: 'value1' } } },
+ { data: { level1: 'value2' } },
+ { data: { level1: { level2: 'value1' } } },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ data: { level1: { level2: 'value1' } } });
+ });
+
+ it('should handle arrays of different types', () => {
+ const responses = [
+ { name: 'Alice', tags: ['tag1', 'tag2'] },
+ { name: 'Bob', tags: ['tag2', 'tag3'] },
+ { name: 'Alice', tags: ['tag1', 'tag2'] },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ name: 'Alice', tags: ['tag1', 'tag2'] });
+ });
+ it('should handle arrays with mixed value types', () => {
+ const responses = [
+ {
+ name: 'Alice',
+ value: 10,
+ other: true,
+ values: [1, 2, '3'],
+ },
+ {
+ name: 'Bob',
+ value: 10,
+ other: false,
+ values: [2, 3, '4'],
+ },
+ {
+ name: 'Alice',
+ value: 10,
+ other: true,
+ values: [1, 2, '3'],
+ },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({
+ name: 'Alice',
+ value: 10,
+ other: true,
+ values: [1, 2, '3'],
+ });
+ });
+
+ it('should handle ties by choosing the last encountered value', () => {
+ const responses = [
+ { color: 'red', size: 'small' },
+ { color: 'blue', size: 'large' },
+ { color: 'red', size: 'large' },
+ { color: 'blue', size: 'small' },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ color: 'blue', size: 'small' });
+ });
+ it('should handle ties in nested objects by choosing the last encountered value', () => {
+ const responses = [
+ { data: { color: 'red', size: 'small' } },
+ { data: { color: 'blue', size: 'large' } },
+ { data: { color: 'red', size: 'large' } },
+ { data: { color: 'blue', size: 'small' } },
+ ];
+ const result = assembleMostCommonResponse(responses);
+ expect(result).toEqual({ data: { color: 'blue', size: 'small' } });
+ });
+});
diff --git a/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.ts b/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.ts
new file mode 100644
index 0000000000..f710df35bd
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/assemble-most-common-response.ts
@@ -0,0 +1,37 @@
+import { mostCommonValue } from '@lit-protocol/core';
+
+export const assembleMostCommonResponse = (responses: object[]): object => {
+ const result: Record = {};
+
+ // Aggregate all values for each key across all responses
+ const keys = new Set(responses.flatMap(Object.keys));
+
+ for (const key of keys) {
+ const values = responses.map(
+ (response: Record) => response[key]
+ );
+
+ // Filter out undefined first and unmatching type values after before processing
+ const definedValues = values.filter(
+ (value) => value !== undefined && value !== ''
+ );
+ const valuesType = mostCommonValue(
+ definedValues.map((value) => typeof value)
+ );
+ const filteredValues = values.filter(
+ (value) => typeof value === valuesType
+ );
+
+ if (filteredValues.length === 0) {
+ result[key] = undefined; // or set a default value if needed
+ } else if (valuesType === 'object' && !Array.isArray(filteredValues[0])) {
+ // Recursive case for objects
+ result[key] = assembleMostCommonResponse(filteredValues);
+ } else {
+ // Most common element from filtered values
+ result[key] = mostCommonValue(filteredValues);
+ }
+ }
+
+ return result;
+};
diff --git a/packages/lit-node-client/src/lib/helpers/encode-code.ts b/packages/lit-node-client/src/lib/helpers/encode-code.ts
index 1b45f2c58a..a8090b82d7 100644
--- a/packages/lit-node-client/src/lib/helpers/encode-code.ts
+++ b/packages/lit-node-client/src/lib/helpers/encode-code.ts
@@ -1,8 +1,3 @@
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
-
/**
* Encodes the given code string into base64 format.
*
@@ -10,8 +5,5 @@ import {
* @returns The encoded code string in base64 format.
*/
export const encodeCode = (code: string) => {
- const _uint8Array = uint8arrayFromString(code, 'utf8');
- const encodedJs = uint8arrayToString(_uint8Array, 'base64');
-
- return encodedJs;
+ return Buffer.from(code, 'utf8').toString('base64');
};
diff --git a/packages/lit-node-client/src/lib/helpers/get-bls-signatures.ts b/packages/lit-node-client/src/lib/helpers/get-bls-signatures.ts
index dcfdcecc1e..3d8ce64ed1 100644
--- a/packages/lit-node-client/src/lib/helpers/get-bls-signatures.ts
+++ b/packages/lit-node-client/src/lib/helpers/get-bls-signatures.ts
@@ -1,4 +1,4 @@
-import { log } from '@lit-protocol/misc';
+import { InvalidArgumentException } from '@lit-protocol/constants';
import { BlsResponseData, BlsSignatureShare } from '@lit-protocol/types';
/**
@@ -11,7 +11,14 @@ export function getBlsSignatures(
responseData: BlsResponseData[]
): BlsSignatureShare[] {
if (!responseData) {
- throw new Error('[getBlsSignatures] No data provided');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ responseData,
+ },
+ },
+ '[getBlsSignatures] No data provided'
+ );
}
const signatureShares = responseData.map((s) => ({
@@ -21,10 +28,15 @@ export function getBlsSignatures(
},
}));
- log(`[getBlsSignatures] signatureShares:`, signatureShares);
-
if (!signatureShares || signatureShares.length <= 0) {
- throw new Error('[getBlsSignatures] No signature shares provided');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signatureShares,
+ },
+ },
+ '[getBlsSignatures] No signature shares provided'
+ );
}
return signatureShares;
diff --git a/packages/lit-node-client/src/lib/helpers/get-claims.ts b/packages/lit-node-client/src/lib/helpers/get-claims.ts
index 8bc984efe4..56eb8a0392 100644
--- a/packages/lit-node-client/src/lib/helpers/get-claims.ts
+++ b/packages/lit-node-client/src/lib/helpers/get-claims.ts
@@ -1,6 +1,7 @@
-import { Signature } from '@lit-protocol/types';
import { ethers } from 'ethers';
+import { Signature } from '@lit-protocol/types';
+
/**
* Retrieves the claims from an array of objects and organizes them into a record.
* Each claim is associated with its corresponding signatures and derived key ID.
diff --git a/packages/lit-node-client/src/lib/helpers/get-max-prices-for-node-product.ts b/packages/lit-node-client/src/lib/helpers/get-max-prices-for-node-product.ts
index e0e8c5bfb3..f657edfe78 100644
--- a/packages/lit-node-client/src/lib/helpers/get-max-prices-for-node-product.ts
+++ b/packages/lit-node-client/src/lib/helpers/get-max-prices-for-node-product.ts
@@ -55,8 +55,6 @@ export function getMaxPricesForNodeProduct({
* our request to fail if the price on some of the nodes is higher than we think it was, as long as it's not
* drastically different than we expect it to be
*/
- // console.log('totalBaseCost:', totalBaseCost);
- // console.log('userMaxPrice:', userMaxPrice);
const excessBalance = userMaxPrice - totalBaseCost;
// Map matching the keys from `nodePrices`, but w/ the per-node maxPrice computed based on `userMaxPrice`
diff --git a/packages/lit-node-client/src/lib/helpers/get-signatures.test.ts b/packages/lit-node-client/src/lib/helpers/get-signatures.test.ts
index a0177e3227..d776abf761 100644
--- a/packages/lit-node-client/src/lib/helpers/get-signatures.test.ts
+++ b/packages/lit-node-client/src/lib/helpers/get-signatures.test.ts
@@ -1,7 +1,4 @@
-import {
- EcdsaSignedMessageShareParsed,
- SigResponse,
-} from '@lit-protocol/types';
+import { EcdsaSignedMessageShareParsed } from '@lit-protocol/types';
import { getSignatures } from './get-signatures';
@@ -51,8 +48,6 @@ describe('getSignatures', () => {
requestId,
});
- console.log('signatures:', signatures);
-
expect(signatures).toHaveProperty('publicKey');
expect(signatures).toHaveProperty('r');
expect(signatures).toHaveProperty('recid');
diff --git a/packages/lit-node-client/src/lib/helpers/get-signatures.ts b/packages/lit-node-client/src/lib/helpers/get-signatures.ts
index 77941e63b5..bb50181fe5 100644
--- a/packages/lit-node-client/src/lib/helpers/get-signatures.ts
+++ b/packages/lit-node-client/src/lib/helpers/get-signatures.ts
@@ -1,24 +1,18 @@
-import { joinSignature } from 'ethers/lib/utils';
-
import {
CURVE_GROUP_BY_CURVE_TYPE,
LIT_CURVE_VALUES,
+ InvalidArgumentException,
NoValidShares,
ParamNullError,
- UnknownSignatureError,
UnknownSignatureType,
CurveTypeNotFoundError,
} from '@lit-protocol/constants';
+import { mostCommonValue } from '@lit-protocol/core';
import { combineEcdsaShares } from '@lit-protocol/crypto';
-import {
- logErrorWithRequestId,
- logWithRequestId,
- mostCommonString,
-} from '@lit-protocol/misc';
+import { logger } from '@lit-protocol/logger';
import {
EcdsaSignedMessageShareParsed,
SigResponse,
- SigShare,
} from '@lit-protocol/types';
/**
@@ -42,7 +36,8 @@ export const getSignatures = async (params: {
signedMessageShares: EcdsaSignedMessageShareParsed[];
requestId: string;
}): Promise => {
- let { networkPubKeySet, threshold, signedMessageShares, requestId } = params;
+ const { networkPubKeySet, threshold, signedMessageShares, requestId } =
+ params;
if (networkPubKeySet === null) {
throw new ParamNullError(
@@ -56,10 +51,11 @@ export const getSignatures = async (params: {
}
if (signedMessageShares.length < threshold) {
- logErrorWithRequestId(
+ logger.error({
+ function: 'getSignatures',
requestId,
- `not enough nodes to get the signatures. Expected ${threshold}, got ${signedMessageShares.length}`
- );
+ msg: `not enough nodes to get the signatures. Expected ${threshold}, got ${signedMessageShares.length}`,
+ });
throw new NoValidShares(
{
@@ -105,15 +101,24 @@ export const getSignatures = async (params: {
// -- combine
const combinedSignature = await combineEcdsaShares(signedMessageShares);
- const _publicKey = mostCommonString(
+ const _publicKey = mostCommonValue(
signedMessageShares.map((s) => s.publicKey)
);
- const _dataSigned = mostCommonString(
+ const _dataSigned = mostCommonValue(
signedMessageShares.map((s) => s.dataSigned)
);
if (!_publicKey || !_dataSigned) {
- throw new Error('No valid publicKey or dataSigned found');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ requestId,
+ publicKey: _publicKey,
+ dataSigned: _dataSigned,
+ },
+ },
+ 'No valid publicKey or dataSigned found'
+ );
}
const sigResponse: SigResponse = {
diff --git a/packages/lit-node-client/src/lib/helpers/hex.test.ts b/packages/lit-node-client/src/lib/helpers/hex.test.ts
new file mode 100644
index 0000000000..b857529b1d
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/hex.test.ts
@@ -0,0 +1,55 @@
+import { numberToHex, hexPrefixed, removeHexPrefix } from './hex';
+
+describe('Hex Helpers', () => {
+ describe('numberToHex', () => {
+ it('should convert a number to a hex string prefixed with 0x', () => {
+ expect(numberToHex(255)).toBe('0xff');
+ });
+
+ it('should convert zero correctly', () => {
+ expect(numberToHex(0)).toBe('0x0');
+ });
+
+ it('should convert a larger number correctly', () => {
+ expect(numberToHex(4095)).toBe('0xfff');
+ });
+ });
+
+ describe('hexPrefixed', () => {
+ it('should return the string unchanged if it already has 0x prefix', () => {
+ expect(hexPrefixed('0xabcdef')).toBe('0xabcdef');
+ });
+
+ it('should add 0x prefix if not present', () => {
+ expect(hexPrefixed('abcdef')).toBe('0xabcdef');
+ });
+
+ it('should add 0x prefix to an empty string', () => {
+ expect(hexPrefixed('')).toBe('0x');
+ });
+ });
+
+ describe('removeHexPrefix', () => {
+ it('should remove the hex prefix from a string that starts with 0x', () => {
+ const input = '0xabcdef';
+ const expectedOutput = 'abcdef';
+ expect(removeHexPrefix(input)).toBe(expectedOutput);
+ });
+
+ it('should return the string unchanged if no 0x prefix is present', () => {
+ const input = 'abcdef';
+ const expectedOutput = 'abcdef';
+ expect(removeHexPrefix(input)).toBe(expectedOutput);
+ });
+
+ it('should not remove prefix if it is uppercase 0X (not valid)', () => {
+ // The helper checks only for lowercase '0x'
+ const input = '0XABCDEF';
+ expect(removeHexPrefix(input)).toBe('0XABCDEF');
+ });
+
+ it('should handle an empty string', () => {
+ expect(removeHexPrefix('')).toBe('');
+ });
+ });
+});
diff --git a/packages/lit-node-client/src/lib/helpers/hex.ts b/packages/lit-node-client/src/lib/helpers/hex.ts
new file mode 100644
index 0000000000..e451013de8
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/hex.ts
@@ -0,0 +1,38 @@
+import { Hex } from '@lit-protocol/types';
+
+/**
+ *
+ * Convert number to hex
+ * @param { number } v
+ * @return { string } hex value prefixed with 0x
+ */
+export const numberToHex = (v: number): Hex => {
+ return `0x${v.toString(16)}`;
+};
+
+/**
+ * Adds a '0x' prefix to a string if it doesn't already have one.
+ * @param str - The input string.
+ * @returns The input string with a '0x' prefix.
+ */
+export const hexPrefixed = (str: string): Hex => {
+ if (str.startsWith('0x')) {
+ return str as Hex;
+ }
+
+ return ('0x' + str) as Hex;
+};
+
+/**
+ * Removes the '0x' prefix from a hexadecimal string if it exists.
+ *
+ * @param str - The input string.
+ * @returns The input string with the '0x' prefix removed, if present.
+ */
+export const removeHexPrefix = (str: string) => {
+ if (str.startsWith('0x')) {
+ return str.slice(2);
+ }
+
+ return str;
+};
diff --git a/packages/lit-node-client/src/lib/helpers/mint-claim-callback.ts b/packages/lit-node-client/src/lib/helpers/mint-claim-callback.ts
new file mode 100644
index 0000000000..494787764b
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/mint-claim-callback.ts
@@ -0,0 +1,95 @@
+import {
+ InvalidArgumentException,
+ LIT_NETWORK,
+ LIT_NETWORK_VALUES,
+ NetworkError,
+ RELAYER_URL_BY_NETWORK,
+ WrongNetworkException,
+} from '@lit-protocol/constants';
+import { logger } from '@lit-protocol/logger';
+import {
+ ClaimResult,
+ MintCallback,
+ RelayClaimProcessor,
+} from '@lit-protocol/types';
+
+/**
+ * Checks if the given LIT_NETWORK value is supported.
+ * @param litNetwork - The Lit Network value to check.
+ * @throws {Error} - Throws an error if the Lit Network value is not supported.
+ */
+export function isSupportedLitNetwork(
+ litNetwork: LIT_NETWORK_VALUES
+): asserts litNetwork is LIT_NETWORK_VALUES {
+ const supportedNetworks = Object.values(LIT_NETWORK);
+
+ if (!supportedNetworks.includes(litNetwork)) {
+ throw new WrongNetworkException(
+ {
+ info: {
+ litNetwork,
+ supportedNetworks,
+ },
+ },
+ `Unsupported LitNetwork! (${supportedNetworks.join('|')}) are supported.`
+ );
+ }
+}
+
+export const defaultMintClaimCallback: MintCallback<
+ RelayClaimProcessor
+> = async (
+ params: ClaimResult,
+ network: LIT_NETWORK_VALUES = LIT_NETWORK.NagaDev
+): Promise => {
+ isSupportedLitNetwork(network);
+
+ const AUTH_CLAIM_PATH = '/auth/claim';
+
+ const relayUrl: string = params.relayUrl || RELAYER_URL_BY_NETWORK[network];
+
+ if (!relayUrl) {
+ throw new InvalidArgumentException(
+ {
+ info: {
+ network,
+ relayUrl,
+ },
+ },
+ 'No relayUrl provided and no default relayUrl found for network'
+ );
+ }
+
+ const relayUrlWithPath = relayUrl + AUTH_CLAIM_PATH;
+
+ const response = await fetch(relayUrlWithPath, {
+ method: 'POST',
+ body: JSON.stringify(params),
+ headers: {
+ 'api-key': params.relayApiKey
+ ? params.relayApiKey
+ : '67e55044-10b1-426f-9247-bb680e5fe0c8_relayer',
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (response.status < 200 || response.status >= 400) {
+ const errResp = (await response.json()) ?? '';
+ const errStmt = `An error occurred requesting "/auth/claim" endpoint ${JSON.stringify(
+ errResp
+ )}`;
+ logger.warn(errStmt);
+ throw new NetworkError(
+ {
+ info: {
+ response,
+ errResp,
+ },
+ },
+ `An error occurred requesting "/auth/claim" endpoint`
+ );
+ }
+
+ const body = await response.json();
+ return body.requestId;
+};
diff --git a/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.test.ts b/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.test.ts
new file mode 100644
index 0000000000..0d720c3390
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.test.ts
@@ -0,0 +1,78 @@
+import { normalizeAndStringify } from './normalize-and-stringify';
+
+describe('normalizeAndStringify', () => {
+ it('should return a non-JSON string unchanged', () => {
+ const input = 'Hello, world!';
+ expect(normalizeAndStringify(input)).toBe(input);
+ });
+
+ it('should parse and stringify a valid JSON object', () => {
+ const input = '{"a": "b"}';
+ // JSON.stringify removes spaces so the output will be: {"a":"b"}
+ expect(normalizeAndStringify(input)).toBe('{"a":"b"}');
+ });
+
+ it('should parse and stringify a valid JSON array', () => {
+ const input = '[1, 2, 3]';
+ expect(normalizeAndStringify(input)).toBe('[1,2,3]');
+ });
+
+ it('should normalize an overly escaped JSON object', () => {
+ // The input string is overly escaped.
+ // The literal here represents: {\"a\":\"b\"}
+ const input = '{\\"a\\":\\"b\\"}';
+ expect(normalizeAndStringify(input)).toBe('{"a":"b"}');
+ });
+
+ it('should normalize an overly escaped JSON array', () => {
+ // The literal represents: [\"a\",\"b\"]
+ const input = '[\\"a\\",\\"b\\"]';
+ expect(normalizeAndStringify(input)).toBe('["a","b"]');
+ });
+
+ it('should return a malformed JSON string as is', () => {
+ // Even though it starts with '{', it's not valid JSON and cannot be normalized.
+ const input = '{not a json}';
+ expect(normalizeAndStringify(input)).toBe(input);
+ });
+
+ it('should return an empty string unchanged', () => {
+ const input = '';
+ expect(normalizeAndStringify(input)).toBe('');
+ });
+
+ it('should recursively normalize multiple levels of escaping', () => {
+ // This input is escaped twice:
+ // The literal represents: {\\\"a\\\":\\\"b\\\"}
+ // After one unescape, it becomes: {\"a\":\"b\"} which is still not valid JSON,
+ // so it needs a second unescape to yield valid JSON {"a":"b"}.
+ const input = '{\\\\\\"a\\\\\\":\\\\\\"b\\\\\\"}';
+ expect(normalizeAndStringify(input)).toBe('{"a":"b"}');
+ });
+
+ describe('double escaped JSON string', () => {
+ test('A doubly escaped JSON string', () => {
+ const doublyEscapedJson = '{\\"key\\": \\"value\\"}';
+ expect(normalizeAndStringify(doublyEscapedJson)).toBe('{"key":"value"}');
+ });
+
+ test('A triply escaped JSON string', () => {
+ const triplyEscapedJson = '{\\\\\\"key\\\\\\": \\\\\\"value\\\\\\"}';
+ expect(normalizeAndStringify(triplyEscapedJson)).toBe('{"key":"value"}');
+ });
+
+ test('A correctly escaped JSON string (for comparison)', () => {
+ const correctlyEscapedJson = '{"key":"value"}';
+ expect(normalizeAndStringify(correctlyEscapedJson)).toBe(
+ '{"key":"value"}'
+ );
+ });
+
+ test('regular siwe message', () => {
+ const regularString =
+ 'litprotocol.com wants you to sign in with your Ethereum account:\\n0x3edB...';
+
+ expect(normalizeAndStringify(regularString)).toBe(regularString);
+ });
+ });
+});
diff --git a/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.ts b/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.ts
new file mode 100644
index 0000000000..a10312b2e6
--- /dev/null
+++ b/packages/lit-node-client/src/lib/helpers/normalize-and-stringify.ts
@@ -0,0 +1,37 @@
+/**
+ * Attempts to normalize a string by unescaping it until it can be parsed as a JSON object,
+ * then stringifies it exactly once. If the input is a regular string that does not represent
+ * a JSON object or array, the function will return it as is without modification.
+ * This function is designed to handle cases where strings might be excessively escaped due
+ * to multiple layers of encoding, ensuring that JSON data is stored in a consistent and
+ * predictable format, and regular strings are left unchanged.
+ *
+ * @param input The potentially excessively escaped string.
+ * @return A string that is either the JSON.stringify version of the original JSON object
+ * or the original string if it does not represent a JSON object or array.
+ */
+export function normalizeAndStringify(input: string): string {
+ try {
+ // Directly return the string if it's not in a JSON format
+ if (!input.startsWith('{') && !input.startsWith('[')) {
+ return input;
+ }
+
+ // Attempt to parse the input as JSON
+ const parsed = JSON.parse(input);
+
+ // If parsing succeeds, return the stringified version of the parsed JSON
+ return JSON.stringify(parsed);
+ } catch (error) {
+ // If parsing fails, it might be due to extra escaping
+ const unescaped = input.replace(/\\(.)/g, '$1');
+
+ // If unescaping doesn't change the string, return it as is
+ if (input === unescaped) {
+ return input;
+ }
+
+ // Otherwise, recursively call the function with the unescaped string
+ return normalizeAndStringify(unescaped);
+ }
+}
diff --git a/packages/lit-node-client/src/lib/helpers/parse-as-json-or-string.ts b/packages/lit-node-client/src/lib/helpers/parse-as-json-or-string.ts
index c980d2fea7..790f6f2b1b 100644
--- a/packages/lit-node-client/src/lib/helpers/parse-as-json-or-string.ts
+++ b/packages/lit-node-client/src/lib/helpers/parse-as-json-or-string.ts
@@ -1,4 +1,4 @@
-import { log } from '@lit-protocol/misc';
+import { logger } from '@lit-protocol/logger';
/**
* Parses a response string into a JS object.
@@ -12,10 +12,11 @@ export const parseAsJsonOrString = (
try {
return JSON.parse(responseString);
} catch (e) {
- log(
- '[parseResponses] Error parsing response as json. Swallowing and returning as string.',
- responseString
- );
+ logger.warn({
+ function: 'parseAsJsonOrString',
+ msg: 'Error parsing response as json. Swallowing and returning as string.',
+ responseString,
+ });
return responseString;
}
};
diff --git a/packages/lit-node-client/src/lib/helpers/parse-pkp-sign-response.ts b/packages/lit-node-client/src/lib/helpers/parse-pkp-sign-response.ts
index 1261842705..9d594a7b0f 100644
--- a/packages/lit-node-client/src/lib/helpers/parse-pkp-sign-response.ts
+++ b/packages/lit-node-client/src/lib/helpers/parse-pkp-sign-response.ts
@@ -1,3 +1,4 @@
+import { InvalidArgumentException } from '@lit-protocol/constants';
import {
EcdsaSignedMessageShareParsed,
PKPSignEndpointResponse,
@@ -76,7 +77,14 @@ export const parsePkpSignResponse = (
: signatureShare;
if (!resolvedShare || typeof resolvedShare !== 'object') {
- throw new Error('Invalid signatureShare structure.');
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signatureShare,
+ },
+ },
+ 'Invalid signatureShare structure.'
+ );
}
const camelCaseShare = convertKeysToCamelCase(resolvedShare);
diff --git a/packages/lit-node-client/src/lib/helpers/process-lit-action-response-strategy.ts b/packages/lit-node-client/src/lib/helpers/process-lit-action-response-strategy.ts
index 4d725ffeda..34f9117921 100644
--- a/packages/lit-node-client/src/lib/helpers/process-lit-action-response-strategy.ts
+++ b/packages/lit-node-client/src/lib/helpers/process-lit-action-response-strategy.ts
@@ -1,20 +1,16 @@
-import {
- LitActionResponseStrategy,
- ResponseStrategy,
- NodeShare,
-} from '@lit-protocol/types';
-import { log, logError } from '@lit-protocol/misc';
+import { logger } from '@lit-protocol/logger';
+import { LitActionResponseStrategy, NodeShare } from '@lit-protocol/types';
/**
* Finds the most and least common object within an of objects array
- * @param responses any[]
- * @returns an object which contains both the least and most occuring item in the array
+ * @param responses T[]
+ * @returns an object which contains both the least and most occurring T items in the array
*/
-const _findFrequency = (responses: string[]): { min: any; max: any } => {
+const _findFrequency = (responses: T[]): { min: T; max: T } => {
const sorted = responses.sort(
- (a: any, b: any) =>
- responses.filter((v: any) => v === a).length -
- responses.filter((v: any) => v === b).length
+ (a, b) =>
+ responses.filter((v) => v === a).length -
+ responses.filter((v) => v === b).length
);
return { min: sorted[0], max: sorted[sorted?.length - 1] };
@@ -23,7 +19,7 @@ const _findFrequency = (responses: string[]): { min: any; max: any } => {
export const processLitActionResponseStrategy = (
responses: NodeShare[],
strategy: LitActionResponseStrategy
-): any => {
+) => {
const executionResponses = responses.map((nodeResp) => {
return nodeResp.response;
});
@@ -38,33 +34,34 @@ export const processLitActionResponseStrategy = (
strategy?.customFilter(executionResponses);
return customResponseFilterResult;
} else {
- logError(
+ logger.error(
'Custom filter specified for response strategy but none found. using most common'
);
}
} catch (e) {
- logError(
- 'Error while executing custom response filter, defaulting to most common',
- (e as Error).toString()
- );
+ logger.error({
+ function: 'processLitActionResponseStrategy',
+ msg: 'Error while executing custom response filter, defaulting to most common',
+ error: (e as Error).toString(),
+ });
}
}
- let respFrequency = _findFrequency(copiedExecutionResponses);
+ const respFrequency = _findFrequency(copiedExecutionResponses);
if (strategy?.strategy === 'leastCommon') {
- log(
+ logger.info(
'strategy found to be most common, taking most common response from execution results'
);
return respFrequency.min;
} else if (strategy?.strategy === 'mostCommon') {
- log(
+ logger.info(
'strategy found to be most common, taking most common response from execution results'
);
return respFrequency.max;
} else {
- log(
+ logger.info(
'no strategy found, using least common response object from execution results'
);
- respFrequency.min;
+ return respFrequency.min;
}
};
diff --git a/packages/misc/src/lib/helper/session-sigs-reader.test.ts b/packages/lit-node-client/src/lib/helpers/session-sigs-reader.test.ts
similarity index 100%
rename from packages/misc/src/lib/helper/session-sigs-reader.test.ts
rename to packages/lit-node-client/src/lib/helpers/session-sigs-reader.test.ts
diff --git a/packages/misc/src/lib/helper/session-sigs-reader.ts b/packages/lit-node-client/src/lib/helpers/session-sigs-reader.ts
similarity index 85%
rename from packages/misc/src/lib/helper/session-sigs-reader.ts
rename to packages/lit-node-client/src/lib/helpers/session-sigs-reader.ts
index 6b8c63e95b..99c66792fd 100644
--- a/packages/misc/src/lib/helper/session-sigs-reader.ts
+++ b/packages/lit-node-client/src/lib/helpers/session-sigs-reader.ts
@@ -1,3 +1,6 @@
+import { InvalidArgumentException } from '@lit-protocol/constants';
+import { logger } from '@lit-protocol/logger';
+
import { parseSignedMessage } from './session-sigs-validator';
function formatDuration(start: Date, end: Date): string {
@@ -33,7 +36,7 @@ function formatStatus(expirationDate: Date, currentDate: Date): string {
/**
* Convert this format:
* {"lit-ratelimitincrease://25364":{"Auth/Auth":[{"nft_id":["25364"]}]}}
- * to human readable format
+ * to human-readable format
*/
function humanReadableAtt(obj: any, indentLevel: number = 0): string {
const indent = ' '.repeat(indentLevel * 2);
@@ -73,7 +76,15 @@ export function formatSessionSigs(
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
- throw new Error(`Invalid JSON format for signedMessage: ${errorMessage}`);
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signedMessage,
+ firstNodeSignedMessage: firstNode.signedMessage,
+ },
+ },
+ `Invalid JSON format for signedMessage: ${errorMessage}`
+ );
}
const currentDate = new Date(currentTime);
@@ -88,7 +99,14 @@ export function formatSessionSigs(
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
- throw new Error(`Error parsing issuedAt or expiration: ${errorMessage}`);
+ throw new InvalidArgumentException(
+ {
+ info: {
+ signedMessage,
+ },
+ },
+ `Error parsing issuedAt or expiration: ${errorMessage}`
+ );
}
result += '* Outer expiration:\n';
@@ -111,7 +129,11 @@ export function formatSessionSigs(
attenuation = humanReadableAtt(jsonRecap.att, 6);
} catch (e) {
// swallow error
- console.log('Error parsing attenuation::', e);
+ logger.info({
+ function: 'formatSessionSigs',
+ msg: 'Error parsing attenuation',
+ error: e,
+ });
}
const capIssuedAt = new Date(parsedCapMessage['Issued At'] || '');
diff --git a/packages/misc/src/lib/helper/session-sigs-validator.spec.ts b/packages/lit-node-client/src/lib/helpers/session-sigs-validator.spec.ts
similarity index 99%
rename from packages/misc/src/lib/helper/session-sigs-validator.spec.ts
rename to packages/lit-node-client/src/lib/helpers/session-sigs-validator.spec.ts
index ddc906323c..24a7c1680a 100644
--- a/packages/misc/src/lib/helper/session-sigs-validator.spec.ts
+++ b/packages/lit-node-client/src/lib/helpers/session-sigs-validator.spec.ts
@@ -1,4 +1,5 @@
import { AuthSig } from '@lit-protocol/types';
+
import { validateSessionSigs } from './session-sigs-validator';
describe('validateSessionSigs', () => {
diff --git a/packages/misc/src/lib/helper/session-sigs-validator.ts b/packages/lit-node-client/src/lib/helpers/session-sigs-validator.ts
similarity index 100%
rename from packages/misc/src/lib/helper/session-sigs-validator.ts
rename to packages/lit-node-client/src/lib/helpers/session-sigs-validator.ts
diff --git a/packages/lit-node-client/src/lib/helpers/validate-bls-session-sig.ts b/packages/lit-node-client/src/lib/helpers/validate-bls-session-sig.ts
index 55b5f0cd41..0c7641c75d 100644
--- a/packages/lit-node-client/src/lib/helpers/validate-bls-session-sig.ts
+++ b/packages/lit-node-client/src/lib/helpers/validate-bls-session-sig.ts
@@ -1,12 +1,9 @@
-import { log } from '@lit-protocol/misc';
-import { AuthSig } from '@lit-protocol/types';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
import { ethers } from 'ethers';
import { SiweError, SiweErrorType, SiweMessage } from 'siwe';
+import { InvalidArgumentException } from '@lit-protocol/constants';
+import { AuthSig } from '@lit-protocol/types';
+
const LIT_SESSION_SIGNED_MESSAGE_PREFIX = 'lit_session:';
/**
@@ -29,8 +26,8 @@ export const blsSessionSigVerify = async (
authSig: AuthSig,
authSigSiweMessage: SiweMessage
): Promise => {
- let sigJson = JSON.parse(authSig.sig);
- // we do not nessesarly need to use ethers here but was a quick way
+ const sigJson = JSON.parse(authSig.sig);
+ // we do not necessarily need to use ethers here but was a quick way
// to get verification working.
const eip191Hash = ethers.utils.hashMessage(authSig.signedMessage);
const prefixedStr =
@@ -43,7 +40,12 @@ export const blsSessionSigVerify = async (
const checkTime = new Date();
if (!authSigSiweMessage.expirationTime || !authSigSiweMessage.issuedAt) {
- throw new Error(
+ throw new InvalidArgumentException(
+ {
+ info: {
+ authSigSiweMessage,
+ },
+ },
'Invalid SIWE message. Missing expirationTime or issuedAt.'
);
}
diff --git a/packages/lit-node-client/src/lib/lit-node-client.spec.ts b/packages/lit-node-client/src/lib/lit-node-client.spec.ts
index 0dc666844d..d8c64b332a 100644
--- a/packages/lit-node-client/src/lib/lit-node-client.spec.ts
+++ b/packages/lit-node-client/src/lib/lit-node-client.spec.ts
@@ -1,34 +1,27 @@
-// @ts-nocheck
-
-// This will prevent it logging the following
-// [Lit-JS-SDK v2.2.39] ✅ [BLS SDK] wasmExports loaded
-// [Lit-JS-SDK v2.2.39] ✅ [ECDSA SDK NodeJS] wasmECDSA loaded.
-global.jestTesting = true;
-
import { LIT_NETWORK } from '@lit-protocol/constants';
-import { LitNodeClientNodeJs } from './lit-node-client';
+import { LitNodeClient } from './lit-node-client';
-const isClass = (v) => {
+const isClass = (v: unknown) => {
return typeof v === 'function' && /^\s*class\s+/.test(v.toString());
};
-describe('LitNodeClientNodeJs', () => {
+describe('LitNodeClient', () => {
// --start;
- it('imported { LitNodeClientNodeJs } is a class', async () => {
- expect(isClass(LitNodeClientNodeJs)).toBe(true);
+ it('imported { LitNodeClient } is a class', async () => {
+ expect(isClass(LitNodeClient)).toBe(true);
});
- it('should be able to instantiate a new LitNodeClientNodeJs to custom', async () => {
- const litNodeClient = new LitNodeClientNodeJs({
+ it('should be able to instantiate a new LitNodeClient to custom', async () => {
+ const litNodeClient = new LitNodeClient({
litNetwork: LIT_NETWORK.Custom,
});
expect(litNodeClient).toBeDefined();
});
- it('should be able to instantiate a new LitNodeClientNodeJs to naga dev', async () => {
- const litNodeClient = new LitNodeClientNodeJs({
+ it('should be able to instantiate a new LitNodeClient to naga dev', async () => {
+ const litNodeClient = new LitNodeClient({
litNetwork: LIT_NETWORK.NagaDev,
});
expect(litNodeClient).toBeDefined();
@@ -38,7 +31,7 @@ describe('LitNodeClientNodeJs', () => {
const tmp = globalThis.localStorage;
Object.defineProperty(globalThis, 'localStorage', { value: undefined });
const ls = require('node-localstorage').LocalStorage;
- const litNodeClient = new LitNodeClientNodeJs({
+ const litNodeClient = new LitNodeClient({
litNetwork: LIT_NETWORK.Custom,
storageProvider: {
provider: new ls('./storage.test.db'),
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 6f36fffe8f..1f8f13bf36 100644
--- a/packages/lit-node-client/src/lib/lit-node-client.ts
+++ b/packages/lit-node-client/src/lib/lit-node-client.ts
@@ -1,11 +1,11 @@
import { computeAddress } from '@ethersproject/transactions';
+import { ed25519 } from '@noble/curves/ed25519';
import { ethers } from 'ethers';
import { SiweMessage } from 'siwe';
import {
getFormattedAccessControlConditions,
getHashedAccessControlConditions,
- validateAccessControlConditions,
} from '@lit-protocol/access-control-conditions';
import {
createSiweMessage,
@@ -15,11 +15,9 @@ import {
generateAuthSig,
generateSessionCapabilityObjectWithWildcards,
LitAccessControlConditionResource,
- LitResourceAbilityRequest,
} from '@lit-protocol/auth-helpers';
import {
AUTH_METHOD_TYPE,
- EITHER_TYPE,
FALLBACK_IPFS_GATEWAYS,
GLOBAL_OVERWRITE_IPFS_CODE_BY_NETWORK,
InvalidArgumentException,
@@ -29,8 +27,10 @@ import {
LIT_CURVE,
LIT_CURVE_TYPE,
LIT_ENDPOINT,
+ LitNetworkError,
LitNodeClientNotReadyError,
LOCAL_STORAGE_KEYS,
+ NetworkError,
ParamNullError,
ParamsMissingError,
PRODUCT_IDS,
@@ -40,7 +40,7 @@ import {
WalletSignatureNotFoundError,
} from '@lit-protocol/constants';
import { getNodePrices } from '@lit-protocol/contracts-sdk';
-import { composeLitUrl, LitCore } from '@lit-protocol/core';
+import { composeLitUrl, mostCommonValue, LitCore } from '@lit-protocol/core';
import {
combineSignatureShares,
encrypt,
@@ -48,26 +48,18 @@ import {
verifyAndDecryptWithSignatureShares,
verifySignature,
} from '@lit-protocol/crypto';
-import {
- defaultMintClaimCallback,
- findMostCommonResponse,
- formatSessionSigs,
- hexPrefixed,
- log,
- logErrorWithRequestId,
- logWithRequestId,
- mostCommonString,
- normalizeAndStringify,
- removeHexPrefix,
- safeParams,
- validateSessionSigs,
-} from '@lit-protocol/misc';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import {
getStorageItem,
removeStorageItem,
setStorageItem,
} from '@lit-protocol/misc-browser';
-import { nacl } from '@lit-protocol/nacl';
+import {
+ applySchemaWithValidation,
+ DecryptRequestSchema,
+ EncryptRequestSchema,
+ JsonExecutionSdkParamsBaseSchema,
+} from '@lit-protocol/schemas';
import {
AuthCallback,
AuthCallbackParams,
@@ -98,6 +90,7 @@ import {
JsonSignSessionKeyRequestV1,
JsonSignSessionKeyRequestV2,
LitNodeClientConfig,
+ LitResourceAbilityRequest,
NodeBlsSigningShare,
NodeCommandResponse,
NodeSet,
@@ -114,11 +107,8 @@ import {
SuccessNodePromises,
} from '@lit-protocol/types';
import { AuthMethod } from '@lit-protocol/types';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
+import { assembleMostCommonResponse } from './helpers/assemble-most-common-response';
import { encodeCode } from './helpers/encode-code';
import { getBlsSignatures } from './helpers/get-bls-signatures';
import { getClaims } from './helpers/get-claims';
@@ -126,15 +116,21 @@ import { getClaimsList } from './helpers/get-claims-list';
import { getExpiration } from './helpers/get-expiration';
import { getMaxPricesForNodeProduct } from './helpers/get-max-prices-for-node-product';
import { getSignatures } from './helpers/get-signatures';
+import { hexPrefixed, removeHexPrefix } from './helpers/hex';
+import { defaultMintClaimCallback } from './helpers/mint-claim-callback';
+import { normalizeAndStringify } from './helpers/normalize-and-stringify';
import { normalizeArray } from './helpers/normalize-array';
import { normalizeJsParams } from './helpers/normalize-params';
import { parseAsJsonOrString } from './helpers/parse-as-json-or-string';
import { parsePkpSignResponse } from './helpers/parse-pkp-sign-response';
import { processLitActionResponseStrategy } from './helpers/process-lit-action-response-strategy';
import { removeDoubleQuotes } from './helpers/remove-double-quotes';
+import { formatSessionSigs } from './helpers/session-sigs-reader';
+import { validateSessionSigs } from './helpers/session-sigs-validator';
import { blsSessionSigVerify } from './helpers/validate-bls-session-sig';
export class LitNodeClient extends LitCore implements ILitNodeClient {
+ private readonly _litNodeLogger: Logger;
/** Tracks the total max price a user is willing to pay for each supported product type
* This must be distributed across all nodes; each node will get a percentage of this price
*
@@ -156,6 +152,11 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
super(args);
+ this._litNodeLogger = getChildLogger({
+ module: 'LitNodeClient',
+ ...(this.config.debug ? { level: 'debug' } : {}),
+ });
+
if (args !== undefined && args !== null && 'defaultAuthCallback' in args) {
this.defaultAuthCallback = args.defaultAuthCallback;
}
@@ -194,7 +195,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
// Useful log for debugging
if (!params.delegateeAddresses || params.delegateeAddresses.length === 0) {
- log(
+ this._litNodeLogger.info(
`[createCapacityDelegationAuthSig] 'delegateeAddresses' is an empty array. It means that no body can use it. However, if the 'delegateeAddresses' field is omitted, It means that the capability will not restrict access based on delegatee list, but it may still enforce other restrictions such as usage limits (uses) and specific NFT IDs (nft_id).`
);
}
@@ -241,33 +242,30 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
*/
private _getSessionKey = (): SessionKeyPair => {
const storageKey = LOCAL_STORAGE_KEYS.SESSION_KEY;
- const storedSessionKeyOrError = getStorageItem(storageKey);
-
- if (
- storedSessionKeyOrError.type === EITHER_TYPE.ERROR ||
- !storedSessionKeyOrError.result ||
- storedSessionKeyOrError.result === ''
- ) {
- console.warn(
- `Storage key "${storageKey}" is missing. Not a problem. Continue...`
- );
- // Generate new one
- const newSessionKey = generateSessionKeyPair();
+ try {
+ const storedSessionKeyString = getStorageItem(storageKey);
+ return JSON.parse(storedSessionKeyString);
+ } catch (e) {
+ this._litNodeLogger.warn({
+ msg: `Couldn't get session key from local storage key "${storageKey}". Not a problem. Continue...`,
+ error: e,
+ });
+ }
- // (TRY) to set to local storage
- try {
- localStorage.setItem(storageKey, JSON.stringify(newSessionKey));
- } catch (e) {
- log(
- `[getSessionKey] Localstorage not available.Not a problem. Continue...`
- );
- }
+ this._litNodeLogger.info('Generating new session key...');
+ // Generate new one
+ const newSessionKey = generateSessionKeyPair();
- return newSessionKey;
- } else {
- return JSON.parse(storedSessionKeyOrError.result as string);
+ try {
+ setStorageItem(storageKey, JSON.stringify(newSessionKey));
+ } catch (e) {
+ this._litNodeLogger.info(
+ `Localstorage not available. Not a problem. Continue...`
+ );
}
+
+ return newSessionKey;
};
/**
@@ -287,32 +285,31 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
jsParams,
sessionKey,
}: GetWalletSigProps): Promise => {
- let walletSig: AuthSig;
+ let walletSig: AuthSig | undefined;
const storageKey = LOCAL_STORAGE_KEYS.WALLET_SIGNATURE;
- const storedWalletSigOrError = getStorageItem(storageKey);
-
- // browser: 2 > 2.1 > 3
- // nodejs: 1. > 1.1
// -- (TRY) to get it in the local storage
// -- IF NOT: Generates one
- log(`getWalletSig - flow starts
- storageKey: ${storageKey}
- storedWalletSigOrError: ${JSON.stringify(storedWalletSigOrError)}
- `);
+ this._litNodeLogger.info(
+ `getWalletSig - fetching from storageKey: ${storageKey}`
+ );
- if (
- storedWalletSigOrError.type === EITHER_TYPE.ERROR ||
- !storedWalletSigOrError.result ||
- storedWalletSigOrError.result == ''
- ) {
- log('getWalletSig - flow 1');
- console.warn(
- `Storage key "${storageKey}" is missing. Not a problem. Continue...`
- );
+ try {
+ const walletSigString = getStorageItem(storageKey);
+ walletSig = JSON.parse(walletSigString);
+ } catch (e) {
+ this._litNodeLogger.warn({
+ msg: `Could not get wallet sig from storage key "${storageKey}"`,
+ error: e,
+ });
+ }
+
+ if (!walletSig) {
if (authNeededCallback) {
- log('getWalletSig - flow 1.1');
+ this._litNodeLogger.info(
+ 'getWalletSig - generating with authNeededCallback'
+ );
const body = {
chain,
@@ -335,20 +332,13 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
...(jsParams && { jsParams }),
};
- log('callback body:', body);
+ this._litNodeLogger.info({ msg: 'callback body', body });
walletSig = await authNeededCallback(body);
- } else {
- log('getWalletSig - flow 1.2');
- if (!this.defaultAuthCallback) {
- log('getWalletSig - flow 1.2.1');
- throw new ParamsMissingError(
- {},
- 'No authNeededCallback nor default auth callback provided'
- );
- }
-
- log('getWalletSig - flow 1.2.2');
+ } else if (this.defaultAuthCallback) {
+ this._litNodeLogger.info(
+ 'getWalletSig - generating with defaultAuthCallback'
+ );
walletSig = await this.defaultAuthCallback({
chain,
statement: sessionCapabilityObject.statement,
@@ -360,34 +350,28 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
uri: sessionKeyUri,
nonce,
});
+ } else {
+ throw new ParamsMissingError(
+ {},
+ 'getWalletSig - No authNeededCallback nor default auth callback provided'
+ );
}
- log('getWalletSig - flow 1.3');
+ // If localStorage, authNeededCallback or defaultAuthCallback didn't fail, walletSig is defined by it
+ this._litNodeLogger.info({ msg: 'getWalletSig - walletSig', walletSig });
// (TRY) to set walletSig to local storage
- const storeNewWalletSigOrError = setStorageItem(
- storageKey,
- JSON.stringify(walletSig)
- );
- if (storeNewWalletSigOrError.type === 'ERROR') {
- log('getWalletSig - flow 1.4');
- console.warn(
- `Unable to store walletSig in local storage. Not a problem. Continue...`
- );
- }
- } else {
- log('getWalletSig - flow 2');
try {
- walletSig = JSON.parse(storedWalletSigOrError.result as string);
- log('getWalletSig - flow 2.1');
+ setStorageItem(storageKey, JSON.stringify(walletSig));
} catch (e) {
- console.warn('Error parsing walletSig', e);
- log('getWalletSig - flow 2.2');
+ this._litNodeLogger.warn({
+ msg: `Unable to store walletSig in local storage. Not a problem. Continue...`,
+ error: e,
+ });
}
}
- log('getWalletSig - flow 3');
- return walletSig!;
+ return walletSig;
};
private _authCallbackAndUpdateStorageItem = async ({
@@ -412,25 +396,28 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
}
// (TRY) to set walletSig to local storage
- const storeNewWalletSigOrError = setStorageItem(
- LOCAL_STORAGE_KEYS.WALLET_SIGNATURE,
- JSON.stringify(authSig)
- );
- if (storeNewWalletSigOrError.type === EITHER_TYPE.SUCCESS) {
+ try {
+ setStorageItem(
+ LOCAL_STORAGE_KEYS.WALLET_SIGNATURE,
+ JSON.stringify(authSig)
+ );
return authSig;
+ } catch (e) {
+ // Setting local storage failed, try to remove the item key.
+ this._litNodeLogger.warn({
+ msg: `Unable to store walletSig in local storage. Not a problem. Continuing to remove item key...`,
+ error: e,
+ });
}
- // Setting local storage failed, try to remove the item key.
- console.warn(
- `Unable to store walletSig in local storage. Not a problem. Continuing to remove item key...`
- );
- const removeWalletSigOrError = removeStorageItem(
- LOCAL_STORAGE_KEYS.WALLET_SIGNATURE
- );
- if (removeWalletSigOrError.type === EITHER_TYPE.ERROR) {
- console.warn(
- `Unable to remove walletSig in local storage. Not a problem. Continuing...`
- );
+ try {
+ removeStorageItem(LOCAL_STORAGE_KEYS.WALLET_SIGNATURE);
+ } catch (e) {
+ // Ignore error and continue
+ this._litNodeLogger.warn({
+ msg: `Unable to remove walletSig in local storage. Not a problem. Continuing...`,
+ error: e,
+ });
}
return authSig;
@@ -464,7 +451,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
{ suppressExceptions: false }
);
} catch (e) {
- log(`Error while verifying BLS signature: `, e);
+ this._litNodeLogger.error({
+ msg: `Error while verifying BLS signature: `,
+ e,
+ });
return true;
}
} else if (authSig.algo === `LIT_BLS`) {
@@ -476,7 +466,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
authSigSiweMessage
);
} catch (e) {
- log(`Error while verifying bls signature: `, e);
+ this._litNodeLogger.error({
+ msg: `Error while verifying bls signature: `,
+ e,
+ });
return true;
}
} else {
@@ -495,7 +488,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
// make sure the sig is for the correct session key
if (authSigSiweMessage.uri !== sessionKeyUri) {
- log('Need retry because uri does not match');
+ this._litNodeLogger.info('Need retry because uri does not match');
return true;
}
@@ -504,7 +497,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
!authSigSiweMessage.resources ||
authSigSiweMessage.resources.length === 0
) {
- log('Need retry because empty resources');
+ this._litNodeLogger.info('Need retry because empty resources');
return true;
}
@@ -523,7 +516,8 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
resourceAbilityRequest.ability
)
) {
- log('Need retry because capabilities do not match', {
+ this._litNodeLogger.info({
+ msg: 'Need retry because capabilities do not match',
authSigSessionCapabilityObject,
resourceAbilityRequest,
});
@@ -566,7 +560,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
? [gatewayUrl, ...FALLBACK_IPFS_GATEWAYS]
: FALLBACK_IPFS_GATEWAYS;
- log(
+ this._litNodeLogger.info(
`Attempting to fetch code for IPFS ID: ${ipfsId} using fallback IPFS gateways`
);
@@ -575,7 +569,15 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const response = await fetch(`${url}${ipfsId}`);
if (!response.ok) {
- throw new Error(
+ throw new NetworkError(
+ {
+ info: {
+ ipfsId,
+ gatewayUrl: url,
+ responseStatus: response.status,
+ responseStatusText: response.statusText,
+ },
+ },
`Failed to fetch code from IPFS gateway ${url}: ${response.status} ${response.statusText}`
);
}
@@ -585,12 +587,22 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
return codeBase64;
} catch (error) {
- console.error(`Error fetching code from IPFS gateway ${url}`);
+ this._litNodeLogger.error(
+ `Error fetching code from IPFS gateway ${url}`
+ );
// Continue to the next gateway in the array
}
}
- throw new Error('All IPFS gateways failed to fetch the code.');
+ throw new NetworkError(
+ {
+ info: {
+ ipfsId,
+ gatewayUrl,
+ },
+ },
+ 'All IPFS gateways failed to fetch the code.'
+ );
}
private async executeJsNodeRequest(
@@ -618,6 +630,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
return this.generatePromise(urlWithPath, reqBody, requestId);
}
+
/**
*
* Execute JS on the nodes and combine and return any resulting signatures
@@ -631,6 +644,12 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
params: JsonExecutionSdkParams
): Promise => {
// ========== Validate Params ==========
+ const _params = applySchemaWithValidation(
+ 'executeJs',
+ params,
+ JsonExecutionSdkParamsBaseSchema
+ );
+
if (!this.ready) {
const message =
'[executeJs] LitNodeClient is not ready. Please call await litNodeClient.connect() first.';
@@ -638,44 +657,30 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
throw new LitNodeClientNotReadyError({}, message);
}
- const paramsIsSafe = safeParams({
- functionName: 'executeJs',
- params: params,
- });
-
- if (!paramsIsSafe) {
- throw new InvalidParamType(
- {
- info: {
- params,
- },
- },
- 'executeJs params are not valid'
- );
- }
-
// Format the params
let formattedParams: JsonExecutionSdkParams = {
- ...params,
- ...(params.jsParams && { jsParams: normalizeJsParams(params.jsParams) }),
- ...(params.code && { code: encodeCode(params.code) }),
+ ..._params,
+ ...(_params.jsParams && {
+ jsParams: normalizeJsParams(_params.jsParams),
+ }),
+ ...(_params.code && { code: encodeCode(_params.code) }),
};
// Check if IPFS options are provided and if the code should be fetched from IPFS and overwrite the current code.
// This will fetch the code from the specified IPFS gateway using the provided ipfsId,
// and update the params with the fetched code, removing the ipfsId afterward.
const overwriteCode =
- params.ipfsOptions?.overwriteCode ||
+ _params.ipfsOptions?.overwriteCode ||
GLOBAL_OVERWRITE_IPFS_CODE_BY_NETWORK[this.config.litNetwork];
- if (overwriteCode && params.ipfsId) {
+ if (overwriteCode && _params.ipfsId) {
const code = await this._getFallbackIpfsCode(
- params.ipfsOptions?.gatewayUrl,
- params.ipfsId
+ _params.ipfsOptions?.gatewayUrl,
+ _params.ipfsId
);
formattedParams = {
- ...params,
+ ..._params,
code: code,
ipfsId: undefined,
};
@@ -685,15 +690,15 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const userMaxPrices = await this.getMaxPricesForNodeProduct({
product: 'LIT_ACTION',
- userMaxPrice: params.userMaxPrice,
+ userMaxPrice: _params.userMaxPrice,
});
- const targetNodePrices = params.useSingleNode
+ const targetNodePrices = _params.useSingleNode
? userMaxPrices.slice(0, 1)
: userMaxPrices;
const sessionSigs = await this._getSessionSigs({
- ...params.authContext,
+ ..._params.authContext,
userMaxPrices: targetNodePrices,
});
@@ -716,7 +721,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const res = await this._handleNodePromises(
nodePromises,
requestId,
- params.useSingleNode ? 1 : this._getThreshold()
+ _params.useSingleNode ? 1 : this._getThreshold()
);
// -- case: promises rejected
@@ -727,20 +732,19 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
// -- case: promises success (TODO: check the keys of "values")
const responseData = (res as SuccessNodePromises).values;
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- 'executeJs responseData from node : ',
- JSON.stringify(responseData, null, 2)
- );
+ responseData,
+ });
// -- find the responseData that has the most common response
- const mostCommonResponse = findMostCommonResponse(
+ const mostCommonResponse = assembleMostCommonResponse(
responseData
) as NodeShare;
const responseFromStrategy = processLitActionResponseStrategy(
responseData,
- params.responseStrategy ?? { strategy: 'leastCommon' }
+ _params.responseStrategy ?? { strategy: 'leastCommon' }
);
mostCommonResponse.response = responseFromStrategy;
@@ -771,11 +775,11 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
return removeDoubleQuotes(r.signedData);
});
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- 'signatures shares to combine: ',
- signedDataList
- );
+ msg: 'signatures shares to combine',
+ signedDataList,
+ });
// Flatten the signedDataList by moving the data within the `sig` (or any other key user may choose) object to the top level.
// The specific key name (`sig`) is irrelevant, as the contents of the object are always lifted directly.
@@ -789,7 +793,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const parsedResponse = parseAsJsonOrString(mostCommonResponse.response);
// -- 3. combine logs
- const mostCommonLogs: string = mostCommonString(
+ const mostCommonLogs: string = mostCommonValue(
responseData.map(
(r: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -810,7 +814,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
[key]: await getSignatures({
requestId,
networkPubKeySet: this.networkPubKeySet,
- threshold: params.useSingleNode ? 1 : this._getThreshold(),
+ threshold: _params.useSingleNode ? 1 : this._getThreshold(),
signedMessageShares: flattenedSignedMessageShares,
}),
}
@@ -820,7 +824,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
logs: mostCommonLogs,
};
- log('returnVal:', returnVal);
+ this._litNodeLogger.info({ msg: 'returnVal', returnVal });
return returnVal;
};
@@ -926,7 +930,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
signingScheme: 'EcdsaK256Sha256',
};
- logWithRequestId(requestId, 'reqBody:', reqBody);
+ this._litNodeLogger.info({ requestId, reqBody });
const urlWithPath = composeLitUrl({
url,
@@ -951,11 +955,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const responseData = (res as SuccessNodePromises)
.values;
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- 'pkpSign responseData',
- JSON.stringify(responseData)
- );
+ responseData,
+ });
// clean up the response data (as there are double quotes & snake cases in the response)
const signedMessageShares = parsePkpSignResponse(responseData);
@@ -968,11 +971,11 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
signedMessageShares: signedMessageShares,
});
- logWithRequestId(requestId, `signature combination`, signatures);
+ this._litNodeLogger.info({ requestId, signatures });
return signatures;
} catch (e) {
- console.error('Error getting signature', e);
+ this._litNodeLogger.error({ msg: 'Error getting signature', error: e });
throw e;
}
};
@@ -995,6 +998,12 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
*/
encrypt = async (params: EncryptSdkParams): Promise => {
// ========== Validate Params ==========
+ const _params = applySchemaWithValidation(
+ 'encrypt',
+ params,
+ EncryptRequestSchema
+ );
+
// -- validate if it's ready
if (!this.ready) {
throw new LitNodeClientNotReadyError(
@@ -1008,29 +1017,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
throw new LitNodeClientNotReadyError({}, 'subnetPubKey cannot be null');
}
- const paramsIsSafe = safeParams({
- functionName: 'encrypt',
- params,
- });
-
- if (!paramsIsSafe) {
- throw new InvalidArgumentException(
- {
- info: {
- params,
- },
- },
- 'You must provide either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions'
- );
- }
-
- // ========== Validate Access Control Conditions Schema ==========
- await validateAccessControlConditions(params);
-
// ========== Hashing Access Control Conditions =========
// hash the access control conditions
const hashOfConditions: ArrayBuffer | undefined =
- await getHashedAccessControlConditions(params);
+ await getHashedAccessControlConditions(_params);
if (!hashOfConditions) {
throw new InvalidArgumentException(
@@ -1043,10 +1033,9 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
);
}
- const hashOfConditionsStr = uint8arrayToString(
- new Uint8Array(hashOfConditions),
- 'base16'
- );
+ const hashOfConditionsStr = Buffer.from(
+ new Uint8Array(hashOfConditions)
+ ).toString('hex');
// ========== Hashing Private Data ==========
// hash the private data
@@ -1054,10 +1043,9 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
'SHA-256',
params.dataToEncrypt
);
- const hashOfPrivateDataStr = uint8arrayToString(
- new Uint8Array(hashOfPrivateData),
- 'base16'
- );
+ const hashOfPrivateDataStr = Buffer.from(
+ new Uint8Array(hashOfPrivateData)
+ ).toString('hex');
// ========== Assemble identity parameter ==========
const identityParam = this._getIdentityParamForEncryption(
@@ -1069,7 +1057,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const ciphertext = await encrypt(
this.subnetPubKey,
params.dataToEncrypt,
- uint8arrayFromString(identityParam, 'utf8')
+ Buffer.from(identityParam, 'utf8')
);
return { ciphertext, dataToEncryptHash: hashOfPrivateDataStr };
@@ -1081,10 +1069,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
*
*/
decrypt = async (params: DecryptRequest): Promise => {
- const { authContext, authSig, chain, ciphertext, dataToEncryptHash } =
- params;
+ // -- validate params
+ const { authContext, chain, ciphertext, dataToEncryptHash, userMaxPrice } =
+ applySchemaWithValidation('decrypt', params, DecryptRequestSchema);
- // ========== Validate Params ==========
// -- validate if it's ready
if (!this.ready) {
throw new LitNodeClientNotReadyError(
@@ -1098,22 +1086,6 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
throw new LitNodeClientNotReadyError({}, 'subnetPubKey cannot be null');
}
- const paramsIsSafe = safeParams({
- functionName: 'decrypt',
- params,
- });
-
- if (!paramsIsSafe) {
- throw new InvalidArgumentException(
- {
- info: {
- params,
- },
- },
- 'Parameter validation failed.'
- );
- }
-
// ========== Hashing Access Control Conditions =========
// hash the access control conditions
const hashOfConditions: ArrayBuffer | undefined =
@@ -1130,10 +1102,9 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
);
}
- const hashOfConditionsStr = uint8arrayToString(
- new Uint8Array(hashOfConditions),
- 'base16'
- );
+ const hashOfConditionsStr = Buffer.from(
+ new Uint8Array(hashOfConditions)
+ ).toString('hex');
// ========== Formatting Access Control Conditions =========
const {
@@ -1161,31 +1132,17 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
dataToEncryptHash
);
- log('identityParam', identityParam);
+ this._litNodeLogger.info({ msg: 'identityParam', identityParam });
- let sessionSigs: SessionSigsMap = {};
const userMaxPrices = await this.getMaxPricesForNodeProduct({
product: 'DECRYPTION',
- userMaxPrice: params.userMaxPrice,
+ userMaxPrice,
});
- if (!authSig) {
- if (!authContext) {
- throw new InvalidArgumentException(
- {
- info: {
- params,
- },
- },
- 'Missing auth context; you must provide either authSig or authContext.'
- );
- }
-
- sessionSigs = await this._getSessionSigs({
- ...authContext,
- userMaxPrices,
- });
- }
+ const sessionSigs = await this._getSessionSigs({
+ ...authContext,
+ userMaxPrices,
+ });
// ========== Get Network Signature ==========
const requestId = this._getNewRequestId();
@@ -1193,7 +1150,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
userMaxPrices.map(({ url }) => url),
(url: string) => {
// -- if session key is available, use it
- const authSigToSend = authSig ? authSig : sessionSigs[url];
+ const authSigToSend = sessionSigs[url];
if (!authSigToSend) {
throw new InvalidArgumentException(
@@ -1243,12 +1200,12 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
res as SuccessNodePromises
).values;
- logWithRequestId(requestId, 'signatureShares', signatureShares);
+ this._litNodeLogger.info({ requestId, signatureShares });
// ========== Result ==========
const decryptedData = await this._decryptWithSignatureShares(
this.subnetPubKey,
- uint8arrayFromString(identityParam, 'utf8'),
+ Buffer.from(identityParam, 'utf8'),
ciphertext,
signatureShares
);
@@ -1274,7 +1231,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
private _signSessionKey = async (
params: SignSessionKeyProp
): Promise => {
- log(`[signSessionKey] params:`, params);
+ this._litNodeLogger.info({ msg: `[signSessionKey] params:`, params });
// ========== Validate Params ==========
// -- validate: If it's NOT ready
@@ -1295,7 +1252,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
params.sessionKey ?? this._getSessionKey();
const sessionKeyUri = this._getSessionKeyUri(sessionKey.publicKey);
- log(
+ this._litNodeLogger.info(
`[signSessionKey] sessionKeyUri is not found in params, generating a new one`,
sessionKeyUri
);
@@ -1325,7 +1282,9 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
let siwe_statement = 'Lit Protocol PKP session signature';
if (params.statement) {
siwe_statement += ' ' + params.statement;
- log(`[signSessionKey] statement found in params: "${params.statement}"`);
+ this._litNodeLogger.info(
+ `[signSessionKey] statement found in params: "${params.statement}"`
+ );
}
let siweMessage;
@@ -1377,10 +1336,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
signingScheme: LIT_CURVE.BLS,
};
- log(`[signSessionKey] body:`, body);
+ this._litNodeLogger.info({ msg: `[signSessionKey] body:`, body });
const requestId = this._getNewRequestId();
- logWithRequestId(requestId, 'signSessionKey body', body);
+ this._litNodeLogger.info({ requestId, signSessionKeyBody: body });
const targetNodeUrls = targetNodePrices.map(({ url }) => url);
const nodePromises = this._getNodePromises(
@@ -1405,9 +1364,8 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
requestId,
this._getThreshold()
);
- log('signSessionKey node promises:', res);
+ this._litNodeLogger.info({ msg: 'signSessionKey node promises', res });
} catch (e) {
- logErrorWithRequestId(requestId, e);
throw new UnknownError(
{
info: {
@@ -1419,7 +1377,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
);
}
- logWithRequestId(requestId, 'handleNodePromises res:', res);
+ this._litNodeLogger.info({ requestId, handleNodePromisesRes: res });
// -- case: promises rejected
if (!res.success) {
@@ -1428,29 +1386,34 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
}
const responseData: BlsResponseData[] = res.values as BlsResponseData[];
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- '[signSessionKey] responseData',
- JSON.stringify(responseData, null, 2)
- );
+ responseData,
+ });
// ========== Extract shares from response data ==========
// -- 1. combine signed data as a list, and get the signatures from it
const curveType = responseData[0]?.curveType;
if (curveType === 'ECDSA') {
- throw new Error(
- 'The ECDSA curve type is not supported in this version. Please use version 6.x.x instead.'
+ throw new LitNetworkError(
+ {
+ info: {
+ requestId,
+ responseData,
+ },
+ },
+ 'The ECDSA curve type is not supported in this version.'
);
}
- log(`[signSessionKey] curveType is "${curveType}"`);
+ this._litNodeLogger.info(`[signSessionKey] curveType is "${curveType}"`);
const signedDataList = responseData.map((s) => s.dataSigned);
if (signedDataList.length <= 0) {
const err = `[signSessionKey] signedDataList is empty.`;
- log(err);
+ this._litNodeLogger.info(err);
throw new InvalidSignatureError(
{
info: {
@@ -1463,11 +1426,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
);
}
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- '[signSessionKey] signedDataList',
- signedDataList
- );
+ signedDataList,
+ });
// -- checking if we have enough shares.
const validatedSignedDataList = this._validateSignSessionKeyResponseData(
@@ -1478,32 +1440,41 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const blsSignedData: BlsResponseData[] = validatedSignedDataList;
- const sigType = mostCommonString(blsSignedData.map((s) => s.curveType));
- log(`[signSessionKey] sigType:`, sigType);
+ const sigType = mostCommonValue(blsSignedData.map((s) => s.curveType));
+ this._litNodeLogger.info(`[signSessionKey] sigType:`, sigType);
const signatureShares = getBlsSignatures(blsSignedData);
- log(`[signSessionKey] signatureShares:`, signatureShares);
+ this._litNodeLogger.info(
+ `[signSessionKey] signatureShares:`,
+ signatureShares
+ );
const blsCombinedSignature = await combineSignatureShares(signatureShares);
- log(`[signSessionKey] blsCombinedSignature:`, blsCombinedSignature);
+ this._litNodeLogger.info(
+ `[signSessionKey] blsCombinedSignature:`,
+ blsCombinedSignature
+ );
const publicKey = removeHexPrefix(params.pkpPublicKey);
- log(`[signSessionKey] publicKey:`, publicKey);
+ this._litNodeLogger.info(`[signSessionKey] publicKey:`, publicKey);
- const dataSigned = mostCommonString(blsSignedData.map((s) => s.dataSigned));
- log(`[signSessionKey] dataSigned:`, dataSigned);
+ const dataSigned = mostCommonValue(blsSignedData.map((s) => s.dataSigned));
+ this._litNodeLogger.info(`[signSessionKey] dataSigned:`, dataSigned);
- const mostCommonSiweMessage = mostCommonString(
+ const mostCommonSiweMessage = mostCommonValue(
blsSignedData.map((s) => s.siweMessage)
);
- log(`[signSessionKey] mostCommonSiweMessage:`, mostCommonSiweMessage);
+ this._litNodeLogger.info(
+ `[signSessionKey] mostCommonSiweMessage:`,
+ mostCommonSiweMessage
+ );
const signedMessage = normalizeAndStringify(mostCommonSiweMessage!);
- log(`[signSessionKey] signedMessage:`, signedMessage);
+ this._litNodeLogger.info(`[signSessionKey] signedMessage:`, signedMessage);
const signSessionKeyRes: SignSessionKeyResponse = {
authSig: {
@@ -1534,7 +1505,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
},
requestId: string
) => {
- log('getSignSessionKeyShares');
+ this._litNodeLogger.info('getSignSessionKeyShares');
const urlWithPath = composeLitUrl({
url,
endpoint: LIT_ENDPOINT.SIGN_SESSION_KEY,
@@ -1553,17 +1524,21 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
userMaxPrice?: bigint;
product: keyof typeof PRODUCT_IDS;
}) => {
- log('getMaxPricesForNodeProduct()', { product });
+ this._litNodeLogger.info({
+ msg: 'getMaxPricesForNodeProduct(): Product',
+ product,
+ });
const getUserMaxPrice = () => {
if (userMaxPrice) {
- log('getMaxPricesForNodeProduct(): User provided maxPrice of', {
+ this._litNodeLogger.info({
+ msg: 'getMaxPricesForNodeProduct(): User provided maxPrice of userMaxPrice',
userMaxPrice,
});
return userMaxPrice;
}
if (this.defaultMaxPriceByProduct[product] === -1n) {
- log(
+ this._litNodeLogger.info(
`getMaxPricesForNodeProduct(): No user-provided maxPrice and no defaultMaxPrice set for ${product}; setting to max value`
);
@@ -1572,7 +1547,6 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
return this.defaultMaxPriceByProduct[product];
};
- console.log('getMaxPricesForNodeProduct():', {});
return getMaxPricesForNodeProduct({
nodePrices: await this._getNodePrices(),
userMaxPrice: getUserMaxPrice(),
@@ -1655,7 +1629,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
// -- (CHECK) if we need to resign the session key
if (needToResignSessionKey) {
- log('need to re-sign session key. Signing...');
+ this._litNodeLogger.info('need to re-sign session key. Signing...');
authSig = await this._authCallbackAndUpdateStorageItem({
authCallback: params.authNeededCallback,
authCallbackParams: {
@@ -1722,16 +1696,6 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
const sessionSigs: SessionSigsMap = {};
- // console.log(
- // 'getSessionSigs()',
- // util.inspect(
- // {
- // userMaxPrices: params.userMaxPrices,
- // },
- // { depth: 4 }
- // )
- // );
-
params.userMaxPrices.forEach(({ url: nodeAddress, price }) => {
const toSign: SessionSigningTemplate = {
...sessionSigningTemplate,
@@ -1739,20 +1703,18 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
maxPrice: price.toString(),
};
- log(`Setting maxprice for ${nodeAddress} to `, price.toString());
+ this._litNodeLogger.info(
+ `Setting maxprice for ${nodeAddress} to `,
+ price.toString()
+ );
const signedMessage = JSON.stringify(toSign);
- const uint8arrayKey = uint8arrayFromString(
- sessionKey.secretKey,
- 'base16'
- );
-
- const uint8arrayMessage = uint8arrayFromString(signedMessage, 'utf8');
- const signature = nacl.sign.detached(uint8arrayMessage, uint8arrayKey);
+ const uint8arrayMessage = Buffer.from(signedMessage, 'utf8');
+ const signature = ed25519.sign(uint8arrayMessage, sessionKey.secretKey);
sessionSigs[nodeAddress] = {
- sig: uint8arrayToString(signature, 'base16'),
+ sig: Buffer.from(signature).toString('hex'),
derivedVia: 'litSessionSignViaNacl',
signedMessage: signedMessage,
address: sessionKey.publicKey,
@@ -1760,16 +1722,19 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
};
});
- log('sessionSigs:', sessionSigs);
+ this._litNodeLogger.info({ msg: 'sessionSigs', sessionSigs });
try {
const formattedSessionSigs = formatSessionSigs(
JSON.stringify(sessionSigs)
);
- log(formattedSessionSigs);
+ this._litNodeLogger.info(formattedSessionSigs);
} catch (e) {
// swallow error
- log('Error formatting session signatures: ', e);
+ this._litNodeLogger.info({
+ msg: 'Error formatting session signatures',
+ e,
+ });
}
return sessionSigs;
@@ -1973,18 +1938,18 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
};
});
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- `responseData: ${JSON.stringify(responseData, null, 2)}`
- );
+ responseData,
+ });
const derivedKeyId = responseData.values[0].derivedKeyId;
const pubkey = await this.computeHDPubKey(derivedKeyId);
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- `pubkey ${pubkey} derived from key id ${derivedKeyId}`
- );
+ msg: `pubkey ${pubkey} derived from key id ${derivedKeyId}`,
+ });
const relayParams = params as ClaimRequest<'relay'>;
@@ -2073,7 +2038,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
data[key] === null ||
data[key] === ''
) {
- log(
+ this._litNodeLogger.info(
`Invalid signed data. "${field}" is missing. Not a problem, we only need ${threshold} nodes to sign the session key.`
);
return null;
@@ -2082,7 +2047,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
if (!data.signatureShare.ProofOfPossession) {
const err = `Invalid signed data. "ProofOfPossession" is missing.`;
- log(err);
+ this._litNodeLogger.info(err);
throw new InvalidSignatureError(
{
info: {
@@ -2099,12 +2064,15 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
})
.filter((item) => item !== null);
- logWithRequestId(
+ this._litNodeLogger.info({
requestId,
- 'validated length:',
- validatedSignedDataList.length
- );
- logWithRequestId(requestId, 'minimum threshold:', threshold);
+ validatedSignedDataList,
+ });
+ this._litNodeLogger.info({
+ requestId,
+ msg: 'minimum threshold',
+ threshold,
+ });
if (validatedSignedDataList.length < threshold) {
throw new InvalidSignatureError(
diff --git a/packages/logger/README.md b/packages/logger/README.md
index 671f265971..e20602eadc 100644
--- a/packages/logger/README.md
+++ b/packages/logger/README.md
@@ -1,6 +1,6 @@
# logger
-This library was generated with [Nx](https://nx.dev).
+This package provides a centralized logging utility for the Lit Protocol SDK, offering structured logging capabilities across all packages. It is based in pino logger for minimal overhead and enables consistent log formatting, level-based filtering, and standardized error reporting throughout the Lit Protocol ecosystem.
## Building
diff --git a/packages/logger/src/lib/logger.spec.ts b/packages/logger/src/lib/logger.spec.ts
index a033af9426..0cd4983395 100644
--- a/packages/logger/src/lib/logger.spec.ts
+++ b/packages/logger/src/lib/logger.spec.ts
@@ -1,129 +1,68 @@
-import { LOG_LEVEL, LogLevel, LogManager } from './logger';
+import { Writable } from 'stream';
-describe('logger', () => {
- let lm: LogManager;
- beforeEach(() => {
- LogManager.clearInstance();
- lm = LogManager.Instance;
- });
-
- it('Log Manager singleton should be defined', () => {
- expect(typeof lm).toEqual('object');
- });
-
- it('should make logger with category', () => {
- const logger = lm.get('category');
- expect(logger.category).toEqual('category');
- });
-
- it('should make logger with id and category', () => {
- const logger = lm.get('category', 'foo');
- expect(logger.id).toEqual('foo');
- });
-
- it('Log Manager should pass config to loggers', () => {
- lm.withConfig({
- condenseLogs: true,
- });
- const logger = lm.get('category');
- expect(logger.Config?.['condenseLogs']).toEqual(true);
- });
-
- it('Hashing enabled should filter non unique logs', () => {
- lm.withConfig({
- condenseLogs: true,
- });
- const logger = lm.get('category', 'bar');
- logger.setLevel(LOG_LEVEL.INFO);
- expect(logger.Config?.['condenseLogs']).toEqual(true);
- logger.info('hello');
- logger.info('hello');
- const logs = lm.getLogsForId('bar');
- expect(logs.length).toEqual(1);
- });
+import { logger, setLoggerOptions, getChildLogger } from './logger';
- it('should respect info logging level', () => {
- const logger = lm.get('info-logger', 'foo');
- logger.setLevel(LOG_LEVEL.INFO);
- logger.info('logging');
- logger.debug('shouldnt log');
- const logs = lm.getLogsForId('foo');
- expect(logs.length).toEqual(1);
- });
+class TestStream extends Writable {
+ public data = '';
- it('should log error at any level', () => {
- const logger = lm.get('info-logger', 'foo2');
- logger.setLevel(LOG_LEVEL.DEBUG);
- logger.debug('logging');
- logger.error('error');
- const logs = lm.getLogsForId('foo2');
- expect(logs.length).toEqual(2);
- });
+ override _write(
+ chunk: { toString: () => string },
+ encoding: string,
+ callback: () => void
+ ) {
+ this.data += chunk.toString();
+ callback();
+ }
+}
- it('should safe serialize circular references', () => {
- const logger = lm.get('info-logger', 'foo3');
- logger.setLevel(LOG_LEVEL.DEBUG);
- const circ: any = { foo: 'bar' };
- circ.circ = circ;
- logger.debug('circular reference to serialize', circ);
- console.log(lm.getLogsForId('foo3'));
- expect(lm.getLogsForId('foo3').length).toEqual(1);
+describe('logger', () => {
+ it('should have default level "info"', () => {
+ expect(logger.level).toBe('info');
});
- it('should trace logs through multiple categories', () => {
- const logger = lm.get('info-logger', 'foo4');
- logger.setLevel(LOG_LEVEL.DEBUG);
- const logger2 = lm.get('debug-logger', 'foo4');
- logger2.setLevel(LOG_LEVEL.DEBUG);
- logger2.debug('foo');
- logger.debug('bar');
- expect(lm.getLogsForId('foo4').length).toEqual(2);
+ it('setLoggerOptions should update logger options', () => {
+ const testLogger = setLoggerOptions({ level: 'debug', name: 'TestLogger' });
+ expect(testLogger.level).toBe('debug');
});
- it('should not persist logs if level set to OFF', () => {
- const count = 1_000;
- for (let i = 0; i < count; i++) {
- const logger = lm.get('' + i, 'foo5');
- logger.setLevel(LOG_LEVEL.OFF);
- logger.debug(i + '');
- }
-
- expect(lm.getLogsForId('foo5').length).toEqual(0);
+ it('getChildLogger should create a child logger', () => {
+ const childLogger = getChildLogger({ module: 'childTest' });
+ expect(typeof childLogger.child).toBe('function');
+ expect(() => childLogger.info('Child logger test message')).not.toThrow();
});
- it('should persist logs across categories', async () => {
- const count = 10_000;
- for (let i = 0; i < count; i++) {
- const logger = lm.get('' + i, 'foo6');
- logger.setLevel(LOG_LEVEL.DEBUG);
- logger.debug(i + '');
- }
-
- expect(lm.getLogsForId('foo6').length).toEqual(count);
+ it('should log messages correctly on the parent logger', (done) => {
+ // Override the global logger with a test logger using our own destination stream:
+ const testStream = new TestStream();
+ const testLogger = setLoggerOptions(
+ { level: 'info', name: 'ParentTestLogger' },
+ testStream
+ );
+ testLogger.info('Parent message');
+
+ // Give a small amount time for the stream to process the log
+ setTimeout(() => {
+ expect(testStream.data).toMatch(/Parent message/);
+ done();
+ }, 50);
});
- it('should retain logger keys and return from LogManager', () => {
- const count = 10;
- for (let i = 0; i < count; i++) {
- const logger = lm.get('' + i, 'foo7');
- logger.setLevel(LogLevel.DEBUG);
- logger.debug(i + '');
- }
-
- expect(lm.getLogsForId('foo7').length).toEqual(count);
- expect(lm.LoggerIds.length).toEqual(10);
- });
-
- it('should order logs based on logger creation timestamp', async () => {
- const loggerA = lm.get('a', '1');
- await new Promise((res) => setTimeout(res, 100));
- const loggerB = lm.get('b', '2');
-
- const requestIds = lm.LoggerIds;
-
- expect(requestIds.length).toBe(2);
- expect(loggerA.timestamp).toBeLessThan(loggerB.timestamp);
- expect(requestIds[0]).toBe('1');
- expect(requestIds[1]).toBe('2');
+ it('should log messages on a child logger using the parent transport but adding its bindings', (done) => {
+ // Override the global logger for consistency in our test:
+ const testStream = new TestStream();
+ setLoggerOptions({ level: 'info', name: 'ParentTestLogger' }, testStream);
+ const childLogger = getChildLogger({ module: 'ChildModule' });
+ childLogger.info('Child message');
+
+ setTimeout(() => {
+ try {
+ expect(testStream.data).toMatch('"name":"ParentTestLogger"');
+ expect(testStream.data).toMatch('"msg":"Child message"');
+ expect(testStream.data).toMatch('"module":"ChildModule"');
+ done();
+ } catch (error) {
+ done(error);
+ }
+ }, 50);
});
});
diff --git a/packages/logger/src/lib/logger.ts b/packages/logger/src/lib/logger.ts
index 8af393f5e8..27021c6ea4 100644
--- a/packages/logger/src/lib/logger.ts
+++ b/packages/logger/src/lib/logger.ts
@@ -1,551 +1,32 @@
-import { version, LOG_LEVEL, LOG_LEVEL_VALUES } from '@lit-protocol/constants';
-import { hashMessage } from 'ethers/lib/utils';
-export { LOG_LEVEL };
+import { pino, Logger as Pino, LoggerOptions, DestinationStream } from 'pino';
-export enum LogLevel {
- OFF = -1,
- ERROR = 0,
- INFO = 1,
- DEBUG = 2,
- WARN = 3,
- FATAL = 4,
- TIMING_START = 5,
- TIMING_END = 6,
-}
-
-const colours = {
- reset: '\x1b[0m',
- bright: '\x1b[1m',
- dim: '\x1b[2m',
- underscore: '\x1b[4m',
- blink: '\x1b[5m',
- reverse: '\x1b[7m',
- hidden: '\x1b[8m',
-
- fg: {
- black: '\x1b[30m',
- red: '\x1b[31m',
- green: '\x1b[32m',
- yellow: '\x1b[33m',
- blue: '\x1b[34m',
- magenta: '\x1b[35m',
- cyan: '\x1b[36m',
- white: '\x1b[37m',
- gray: '\x1b[90m',
- crimson: '\x1b[38m', // Scarlet
- },
- bg: {
- black: '\x1b[40m',
- red: '\x1b[41m',
- green: '\x1b[42m',
- yellow: '\x1b[43m',
- blue: '\x1b[44m',
- magenta: '\x1b[45m',
- cyan: '\x1b[46m',
- white: '\x1b[47m',
- gray: '\x1b[100m',
- crimson: '\x1b[48m',
- },
+const DEFAULT_LOGGER_OPTIONS = {
+ name: 'LitProtocolSDK',
+ level: 'info',
};
-function _convertLoggingLevel(level: LOG_LEVEL_VALUES): string {
- switch (level) {
- case LOG_LEVEL.INFO:
- return `${colours.fg.green}[INFO]${colours.reset}`;
- case LOG_LEVEL.DEBUG:
- return `${colours.fg.cyan}[DEBUG]${colours.reset}`;
- case LOG_LEVEL.WARN:
- return `${colours.fg.yellow}[WARN]${colours.reset}`;
- case LOG_LEVEL.ERROR:
- return `${colours.fg.red}[ERROR]${colours.reset}`;
- case LOG_LEVEL.FATAL:
- return `${colours.fg.red}[FATAL]${colours.reset}`;
- case LOG_LEVEL.TIMING_START:
- return `${colours.fg.green}[TIME_START]${colours.reset}`;
- case LOG_LEVEL.TIMING_END:
- return `${colours.fg.green}[TIME_END]${colours.reset}`;
- }
-
- return '[UNKNOWN]';
-}
-
-function _resolveLoggingHandler(level: LOG_LEVEL_VALUES): any {
- switch (level) {
- case LOG_LEVEL.DEBUG:
- return console.debug;
- case LOG_LEVEL.INFO:
- return console.info;
- case LOG_LEVEL.ERROR:
- return console.error;
- case LOG_LEVEL.WARN:
- return console.warn;
- case LOG_LEVEL.FATAL:
- return console.error;
- case LOG_LEVEL.TIMING_END:
- return console.timeLog;
- case LOG_LEVEL.TIMING_START:
- return console.time;
- }
-}
-
-/**
- * Implementation of `JSON.stringify` which removes circular object references
- * @example
- * let circ = {foo: 'bar'};
- * circ.circ = circ; // creates a circular reference
- * _safeStringify(circ) -> {foo: 'bar'}
- * @param obj object to check for circular references
- * @param indent number of indents to include (spaces)
- * @returns obj param without without circular references
- */
-function _safeStringify(obj: any, indent = 2) {
- let cache: any[] | null = [];
- const retVal = JSON.stringify(
- obj,
- (_key, value) =>
- typeof value === 'object' && value !== null
- ? cache?.includes(value)
- ? undefined // Duplicate reference found, discard key
- : cache?.push(value) && value // Store value in our collection
- : value,
- indent
+type Logger = Pino;
+let logger: Logger = pino(DEFAULT_LOGGER_OPTIONS);
+
+function setLoggerOptions(
+ loggerOptions: LoggerOptions,
+ destination?: DestinationStream
+): Logger {
+ logger = pino(
+ {
+ ...DEFAULT_LOGGER_OPTIONS,
+ ...loggerOptions,
+ },
+ destination
);
- cache = null;
- return retVal;
-}
-interface ILog {
- timestamp: string;
- message: string;
- args: any[];
- id: string;
- category: string;
- level: LOG_LEVEL_VALUES;
- error?: any;
- toString(): string;
- toJSON(): Record;
+ return logger;
}
-class Log implements ILog {
- timestamp: string;
- message: string;
- args: any[];
- id: string;
- category: string;
- level: LOG_LEVEL_VALUES;
- error?: any;
-
- constructor(
- timestamp: string,
- message: string,
- args: any[],
- id: string,
- category: string,
- level: LOG_LEVEL_VALUES
- ) {
- this.timestamp = timestamp;
- this.message = message;
- this.args = args;
- this.id = id;
- this.category = category;
- this.level = level;
- }
-
- toString(): string {
- let fmtStr: string = `[Lit-JS-SDK v${version}]${_convertLoggingLevel(
- this.level
- )} [${this.category}] [id: ${this.id}] ${this.message}`;
- for (let i = 0; i < this.args.length; i++) {
- if (typeof this.args[i] === 'object') {
- fmtStr = `${fmtStr} ${_safeStringify(this.args[i])}`;
- } else {
- fmtStr = `${fmtStr} ${this.args[i]}`;
- }
- }
- return fmtStr;
- }
-
- toArray(): string[] {
- const args = [];
- args.push(`[Lit-JS-SDK v${version}]`);
- args.push(`[${this.timestamp}]`);
- args.push(_convertLoggingLevel(this.level));
- args.push(`[${this.category}]`);
-
- this.id && args.push(`${colours.fg.cyan}[id: ${this.id}]${colours.reset}`);
- this.message && args.push(this.message);
-
- for (let i = 0; i < this.args.length; i++) {
- args.push(this.args[i]);
- }
-
- return args;
- }
-
- toJSON(): Record {
- return {
- timestamp: this.timestamp,
- message: this.message,
- args: this.args,
- id: this.id,
- category: this.category,
- level: this.level,
- };
- }
+function getChildLogger(
+ ...childParams: Parameters
+): Logger {
+ return logger.child(...childParams);
}
-export type messageHandler = (log: Log) => void;
-
-export class Logger {
- private _category: string;
- private _level: LOG_LEVEL_VALUES;
- private _id: string;
- private _handler: messageHandler | undefined;
- private _consoleHandler: any;
- private _logs: Log[] = [];
- private _logHashes: Map = new Map();
- private _config: Record | undefined;
- private _isParent: boolean;
- private _children: Map;
- private _timestamp: number;
-
- public static createLogger(
- category: string,
- level: LOG_LEVEL_VALUES,
- id: string,
- isParent: boolean,
- config?: Record
- ): Logger {
- return new Logger(category, level, id, isParent, config);
- }
-
- private constructor(
- category: string,
- level: LOG_LEVEL_VALUES,
- id: string,
- isParent: boolean,
- config?: Record
- ) {
- this._category = category;
- this._level = level;
- this._id = id;
- this._consoleHandler = _resolveLoggingHandler(this._level);
- this._config = config;
- this._children = new Map();
- this._isParent = isParent;
- this._timestamp = Date.now();
- }
-
- get id(): string {
- return this._id;
- }
-
- get category(): string {
- return this._category;
- }
-
- get timestamp(): number {
- return this._timestamp;
- }
-
- get Logs(): Log[] {
- return this._logs;
- }
-
- set Config(value: Record | undefined) {
- this._config = value;
- }
-
- get Config(): Record | undefined {
- return this._config;
- }
-
- get Children(): Map {
- return this._children;
- }
-
- public setLevel(level: LOG_LEVEL_VALUES): void {
- this._level = level;
- }
-
- public setHandler(handler: messageHandler) {
- this._handler = handler;
- }
-
- public info(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.INFO, message, ...args);
- }
-
- public debug(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.DEBUG, message, ...args);
- }
-
- public warn(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.WARN, message, args);
- }
-
- public error(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.ERROR, message, ...args);
- }
-
- public fatal(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.FATAL, message, ...args);
- }
-
- public trace(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.FATAL, message, ...args);
- }
-
- public timeStart(message: string = '', ...args: any[]): void {
- this._log(LOG_LEVEL.TIMING_START, message, ...args);
- }
-
- public timeEnd(message: string = '', ...args: any[]): void {
- this._level < LOG_LEVEL.OFF &&
- this._log(LOG_LEVEL.TIMING_END, message, ...args);
- }
-
- private _log(
- level: LOG_LEVEL_VALUES,
- message: string = '',
- ...args: any[]
- ): void {
- const log = new Log(
- new Date().toISOString(),
- message,
- args,
- this._id,
- this._category,
- level
- );
-
- const arrayLog = log.toArray();
- if (this._config?.['condenseLogs'] && !this._checkHash(log)) {
- (this._level >= level || level === LogLevel.ERROR) &&
- this._consoleHandler &&
- this._consoleHandler(...arrayLog);
- (this._level >= level || level === LOG_LEVEL.ERROR) &&
- this._handler &&
- this._handler(log);
-
- (this._level >= level || level === LogLevel.ERROR) && this._addLog(log);
- } else if (!this._config?.['condenseLogs']) {
- (this._level >= level || level === LogLevel.ERROR) &&
- this._consoleHandler &&
- this._consoleHandler(...arrayLog);
- (this._level >= level || level === LOG_LEVEL.ERROR) &&
- this._handler &&
- this._handler(log);
- (this._level >= level || level === LOG_LEVEL.ERROR) && this._addLog(log);
- }
- }
-
- private _checkHash(log: Log): boolean {
- const strippedMessage = this._cleanString(log.message);
- const digest = hashMessage(strippedMessage);
- const hash = digest.toString();
- const item = this._logHashes.get(hash);
- if (item) {
- return true;
- } else {
- this._logHashes.set(hash, true);
- return false;
- }
- }
-
- private _addLog(log: Log) {
- this._logs.push(log);
- // TODO: currently we are not deleting old request id's which over time will fill local storage as the maximum storage size is 10mb
- // we should be deleting keys from the front of the collection of `Object.keys(category)` such that the first keys entered are deleted when we reach a pre defined key threshold
- // this implementation assumes that serialization / deserialization from `localStorage` keeps the same key ordering in each `category` object as we will asssume the array produced from `Object.keys` will always be the same ordering.
- // which then allows us to start at the front of the array and do `delete` operation on each key we wish to delete from the object.
- //log.id && this._addToLocalStorage(log);
- }
-
- private _addToLocalStorage(log: Log) {
- if (globalThis.localStorage) {
- let bucket: Record | string | null =
- globalThis.localStorage.getItem(log.category);
- if (bucket) {
- bucket = JSON.parse(bucket) as Record;
- if (!bucket[log.id]) {
- bucket[log.id] = [];
- }
- bucket[log.id].push(log.toString());
- globalThis.localStorage.setItem(log.category, _safeStringify(bucket));
- } else {
- const bucket: Record = {};
- bucket[log.id] = [log.toString()];
- globalThis.localStorage.setItem(log.category, _safeStringify(bucket));
- }
- }
- }
-
- /**
- *
- * @param input string which will be cleaned of non utf-8 characters
- * @returns {string} input cleaned of non utf-8 characters
- */
- private _cleanString(input: string): string {
- let output = '';
- for (let i = 0; i < input.length; i++) {
- if (input.charCodeAt(i) <= 127) {
- output += input.charAt(i);
- }
- }
- return output;
- }
-}
-
-export class LogManager {
- private static _instance: LogManager;
- private _loggers: Map;
- private _level: LOG_LEVEL_VALUES | undefined = LOG_LEVEL.DEBUG;
- private _config: Record | undefined;
-
- static get Instance(): LogManager {
- if (!LogManager._instance) {
- LogManager._instance = new LogManager();
- }
- return LogManager._instance;
- }
-
- static clearInstance() {
- (LogManager._instance as any) = undefined;
- }
-
- private constructor() {
- this._loggers = new Map();
- }
-
- public withConfig(config: Record) {
- this._config = config;
- for (const logger of this._loggers) {
- logger[1].Config = config;
- }
- }
-
- public setLevel(level: LOG_LEVEL_VALUES) {
- this._level = level;
- for (const logger of this._loggers) {
- logger[1].setLevel(level);
- }
- }
-
- public setHandler(handler: messageHandler) {
- for (const logger of this._loggers) {
- logger[1].setHandler(handler);
- }
- }
-
- get LoggerIds(): string[] {
- const keys: [string, number][] = [];
- for (const category of this._loggers.entries()) {
- for (const child of category[1].Children) {
- keys.push([child[0], child[1].timestamp]);
- }
- }
-
- return keys
- .sort((a: [string, number], b: [string, number]) => {
- return a[1] - b[1];
- })
- .map((value: [string, number]) => {
- return value[0];
- });
- }
-
- // if a logger is given an id it will persist logs under its logger instance
- public get(category: string, id?: string): Logger {
- let instance = this._loggers.get(category);
- if (!instance && !id) {
- this._loggers.set(
- category,
- Logger.createLogger(category, this._level ?? LOG_LEVEL.INFO, '', true)
- );
-
- instance = this._loggers.get(category) as Logger;
- instance.Config = this._config;
- return instance;
- }
-
- if (id) {
- if (!instance) {
- this._loggers.set(
- category,
- Logger.createLogger(category, this._level ?? LOG_LEVEL.INFO, '', true)
- );
-
- instance = this._loggers.get(category) as Logger;
- instance.Config = this._config;
- }
- const children = instance?.Children;
- let child = children?.get(id);
- if (child) {
- return child;
- }
- children?.set(
- id,
- Logger.createLogger(
- category,
- this._level ?? LOG_LEVEL.INFO,
- id ?? '',
- true
- )
- );
-
- child = children?.get(id) as Logger;
- child.Config = this._config;
- return children?.get(id) as Logger;
- // fall through condition for if there is no id for the logger and the category is not yet created.
- // ex: LogManager.Instance.get('foo');
- } else if (!instance) {
- this._loggers.set(
- category,
- Logger.createLogger(category, this._level ?? LOG_LEVEL.INFO, '', true)
- );
-
- instance = this._loggers.get(category) as Logger;
- instance.Config = this._config;
- }
-
- return instance as Logger;
- }
-
- getById(id: string): string[] {
- let logStrs: string[] = [];
- for (const category of this._loggers.entries()) {
- const logger = category[1].Children.get(id);
- if (logger) {
- const logStr = [];
- for (const log of logger.Logs) {
- logStr.push(log.toString());
- }
- logStrs = logStrs.concat(logStr);
- }
- }
-
- return logStrs;
- }
-
- public getLogsForId(id: string): string[] {
- let logsForRequest: string[] = this.getById(id);
- if (logsForRequest.length < 1 && globalThis.localStorage) {
- for (const category of this._loggers.keys()) {
- const bucketStr: string | null =
- globalThis.localStorage.getItem(category);
- const bucket: Record = JSON.parse(
- bucketStr as string
- );
- if (bucket && bucket[id]) {
- const logsForId: string[] = bucket[id].filter((log: string) =>
- log.includes(id)
- );
- logsForRequest = logsForId.concat(logsForRequest);
- }
- }
- }
-
- return logsForRequest;
- }
-}
+export { Logger, logger, setLoggerOptions, getChildLogger };
diff --git a/packages/misc-browser/src/lib/misc-browser.ts b/packages/misc-browser/src/lib/misc-browser.ts
index 9c2b0d96a5..12b060e341 100644
--- a/packages/misc-browser/src/lib/misc-browser.ts
+++ b/packages/misc-browser/src/lib/misc-browser.ts
@@ -1,46 +1,44 @@
import {
- ELeft,
- ERight,
- IEither,
- InvalidArgumentException,
LocalStorageItemNotFoundException,
LocalStorageItemNotRemovedException,
LocalStorageItemNotSetException,
} from '@lit-protocol/constants';
-import {
- uint8arrayFromString,
- uint8arrayToString,
-} from '@lit-protocol/uint8arrays';
/**
+ * Get the local storage item by key.
*
- * Get the local storage item by key
- *
- * @param { string } key
+ * @param {string} key The key to retrieve.
+ * @returns {string} The stored string.
+ * @throws Will throw an error if reading from localStorage fails or the item is not found.
*/
-export const getStorageItem = (key: string): IEither => {
- let item;
+export const getStorageItem = (key: string): string => {
+ let item: string | null;
try {
item = localStorage.getItem(key);
} catch (e) {
- // swallowing
+ throw new LocalStorageItemNotFoundException(
+ {
+ info: {
+ storageKey: key,
+ },
+ cause: e,
+ },
+ `Error reading localStorage for key "${key}"`
+ );
}
if (!item) {
- return ELeft(
- new LocalStorageItemNotFoundException(
- {
- info: {
- storageKey: key,
- },
+ throw new LocalStorageItemNotFoundException(
+ {
+ info: {
+ storageKey: key,
},
- `Failed to get %s from local storage`,
- key
- )
+ },
+ `Failed to find ${key} in local storage`
);
}
- return ERight(item);
+ return item;
};
/**
@@ -50,21 +48,20 @@ export const getStorageItem = (key: string): IEither => {
* @param { string } key is the key to set
* @param { string } value is the value to set
*/
-export const setStorageItem = (key: string, value: string): IEither => {
+export const setStorageItem = (key: string, value: string): string => {
try {
localStorage.setItem(key, value);
- return ERight(value);
+ return value;
} catch (e) {
- return ELeft(
- new LocalStorageItemNotSetException(
- {
- info: {
- storageKey: key,
- },
+ throw new LocalStorageItemNotSetException(
+ {
+ info: {
+ storageKey: key,
},
- `Failed to set %s in local storage`,
- key
- )
+ cause: e,
+ },
+ `Failed to set %s in local storage`,
+ key
);
}
};
@@ -74,176 +71,22 @@ export const setStorageItem = (key: string, value: string): IEither => {
* Remove the local storage item by key
*
* @param { string } key is the key to remove
- * @returns { IEither } Either the key or an error
+ * @returns { string } the key removed
*/
-export const removeStorageItem = (key: string): IEither => {
+export const removeStorageItem = (key: string): string => {
try {
localStorage.removeItem(key);
- return ERight(key);
+ return key;
} catch (e) {
- return ELeft(
- new LocalStorageItemNotRemovedException(
- {
- info: {
- storageKey: key,
- },
- },
- `Failed to remove %s from local storage`,
- key
- )
- );
- }
-};
-
-/**
- * Convert a Blob to a base64urlpad string. Note: This function returns a promise.
- *
- * @param { Blob | File } blob The Blob or File to turn into a base64 string
- * @returns { Promise } A promise that resolves to the base64 string
- */
-export const blobToBase64String = async (
- blob: Blob | File
-): Promise => {
- const arrayBuffer = await blob.arrayBuffer();
-
- const uint8array = new Uint8Array(arrayBuffer);
-
- return uint8arrayToString(uint8array, 'base64urlpad');
-};
-
-/**
- *
- * Convert a base64urlpad string to a Blob.
- * Note: This function DOES NOT return a promise
- *
- * @param { string } base64String The base64 string that to turn into a Blob
- * @returns { Blob } A blob that contains the decoded base64 data
- */
-export const base64StringToBlob = (base64String: string): Blob => {
- return new Blob([uint8arrayFromString(base64String, 'base64urlpad')]);
-};
-
-/**
- *
- * Convert a file to a data URL, which could then be embedded in a LIT.
- * A data URL is a string representation of a file.
- *
- * @param { File } file The file to turn into a data url
- * @returns { string } The data URL. This is a string representation that can be used anywhere the original file would be used.
- */
-export const fileToDataUrl = (
- file: File
-): Promise => {
- return new Promise((resolve) => {
- const reader = new FileReader();
- reader.onloadend = () => {
- resolve(reader.result);
- };
- reader.readAsDataURL(file);
- });
-};
-
-/**
- *
- * // TEST: downloadFile
- * Download a file in memory to the user's computer
- *
- * @param { Object } params
- * @property { string } filename The name of the file
- * @property { Uint8Array } data The actual file itself as a Uint8Array
- * @property { string } mimetype The mime type of the file
- *
- * @returns { void } The data URL. This is a string representation that can be used anywhere the original file would be used.
- *
- */
-export const downloadFile = ({
- fileName,
- data,
- mimeType,
-}: {
- fileName: string;
- data: Uint8Array;
- mimeType: string;
-}): void => {
- const element = document.createElement('a');
-
- element.setAttribute(
- 'href',
- 'data:' + mimeType + ';base64,' + uint8arrayToString(data, 'base64')
- );
- element.setAttribute('download', fileName);
-
- element.style.display = 'none';
-
- document.body.appendChild(element);
-
- element.click();
-
- document.body.removeChild(element);
-};
-
-/**
- *
- * // TEST: injectViewerIFrame
- * Inject an iFrame into the current page that will display a LIT.
- * This function safely sandboxes the content in the iFrame so that the LIT cannot see cookies or localStorage of the parent website.
- *
- * @param { Object } params
- * @property { string } destinationId The DOM ID of the element to inject the iFrame into
- * @property { string } title The title of the content being displayed
- * @property { string } fileUrl The URL of the content that will be shown in the iFrame
- * @property { string } className An optional DOM class name to add to the iFrame for styling
- *
- * @returns { void }
- */
-export const injectViewerIFrame = ({
- destinationId,
- title,
- fileUrl,
- className,
-}: {
- destinationId: string;
- title: string;
- fileUrl: string;
- className: string;
-}): void => {
- if (fileUrl.includes('data:')) {
- // data urls are not safe, refuse to do this
- throw new InvalidArgumentException(
- {
- info: {
- fileUrl,
- },
- },
- 'You can not inject an iFrame with a data url. Try a regular https URL.'
- );
- }
-
- const url = new URL(fileUrl);
- if (url.host.toLowerCase() === window.location.host.toLowerCase()) {
- throw new InvalidArgumentException(
+ throw new LocalStorageItemNotRemovedException(
{
info: {
- fileUrl,
+ storageKey: key,
},
+ cause: e,
},
- 'You cannot host a LIT on the same domain as the parent webpage. This is because iFrames with the same origin have access to localstorage and cookies in the parent webpage which is unsafe'
+ `Failed to remove %s from local storage`,
+ key
);
}
-
- const iframe = Object.assign(document.createElement('iframe'), {
- src: fileUrl,
- title: title,
- sandbox:
- 'allow-forms allow-scripts allow-popups allow-modals allow-popups-to-escape-sandbox allow-same-origin',
- loading: 'lazy',
- allow:
- 'accelerometer; ambient-light-sensor; autoplay; battery; camera; display-capture; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr; screen-wake-lock; web-share; xr-spatial-tracking',
- });
-
- if (className) {
- iframe.className = className;
- }
-
- document.getElementById(destinationId)?.appendChild(iframe);
};
diff --git a/packages/misc/.babelrc b/packages/misc/.babelrc
deleted file mode 100644
index 158083d278..0000000000
--- a/packages/misc/.babelrc
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "presets": [
- [
- "@nx/web/babel",
- {
- "useBuiltIns": "usage"
- }
- ]
- ]
-}
diff --git a/packages/misc/.eslintrc.json b/packages/misc/.eslintrc.json
deleted file mode 100644
index 9d9c0db55b..0000000000
--- a/packages/misc/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/packages/misc/README.md b/packages/misc/README.md
deleted file mode 100644
index 381773dbee..0000000000
--- a/packages/misc/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Quick Start
-
-This submodule contains various utility functions for error handling, logging, type checking, and other operations in the JavaScript SDK for the Lit Protocol.
-
-### node.js / browser
-
-```
-yarn add @lit-protocol/misc
-```
diff --git a/packages/misc/jest.config.ts b/packages/misc/jest.config.ts
deleted file mode 100644
index 0314388c24..0000000000
--- a/packages/misc/jest.config.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/* eslint-disable */
-export default {
- displayName: 'misc',
- preset: '../../jest.preset.js',
- globals: {
- 'ts-jest': {
- tsconfig: '/tsconfig.spec.json',
- },
- },
- transform: {
- '^.+\\.[t]s$': 'ts-jest',
- },
- moduleFileExtensions: ['ts', 'js', 'html'],
- coverageDirectory: '../../coverage/packages/misc',
- setupFilesAfterEnv: ['../../jest.setup.js'],
-};
diff --git a/packages/misc/package.json b/packages/misc/package.json
deleted file mode 100644
index 8ae2d1f91d..0000000000
--- a/packages/misc/package.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "name": "@lit-protocol/misc",
- "license": "MIT",
- "homepage": "https://github.com/Lit-Protocol/js-sdk",
- "repository": {
- "type": "git",
- "url": "https://github.com/LIT-Protocol/js-sdk"
- },
- "keywords": [
- "library"
- ],
- "bugs": {
- "url": "https://github.com/LIT-Protocol/js-sdk/issues"
- },
- "type": "commonjs",
- "publishConfig": {
- "access": "public",
- "directory": "../../dist/packages/misc"
- },
- "gitHead": "0d7334c2c55f448e91fe32f29edc5db8f5e09e4b",
- "tags": [
- "universal"
- ],
- "version": "8.0.0-alpha.0",
- "main": "./dist/src/index.js",
- "typings": "./dist/src/index.d.ts"
-}
diff --git a/packages/misc/project.json b/packages/misc/project.json
deleted file mode 100644
index 30a9e012c5..0000000000
--- a/packages/misc/project.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "misc",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/misc/src",
- "projectType": "library",
- "targets": {
- "build": {
- "executor": "@nx/js:tsc",
- "outputs": ["{options.outputPath}"],
- "options": {
- "outputPath": "dist/packages/misc",
- "main": "packages/misc/src/index.ts",
- "tsConfig": "packages/misc/tsconfig.lib.json",
- "assets": ["packages/misc/*.md"],
- "updateBuildableProjectDepsInPackageJson": true
- }
- },
- "lint": {
- "executor": "@nx/linter:eslint",
- "outputs": ["{options.outputFile}"],
- "options": {
- "lintFilePatterns": ["packages/misc/**/*.ts"]
- }
- },
- "test": {
- "executor": "@nx/jest:jest",
- "outputs": ["{workspaceRoot}/coverage/packages/misc"],
- "options": {
- "jestConfig": "packages/misc/jest.config.ts",
- "passWithNoTests": true
- }
- }
- },
- "tags": []
-}
diff --git a/packages/misc/src/index.ts b/packages/misc/src/index.ts
deleted file mode 100644
index c2ec7a0691..0000000000
--- a/packages/misc/src/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export * from './lib/addresses';
-export * from './lib/misc';
-export * from './lib/params-validators';
-export * from './lib/utils';
-export {
- validateSessionSig,
- validateSessionSigs,
-} from './lib/helper/session-sigs-validator';
-export { formatSessionSigs } from './lib/helper/session-sigs-reader';
diff --git a/packages/misc/src/lib/misc.spec.ts b/packages/misc/src/lib/misc.spec.ts
deleted file mode 100644
index f20dc60508..0000000000
--- a/packages/misc/src/lib/misc.spec.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-// @ts-nocheck
-import { TextEncoder, TextDecoder } from 'util';
-global.TextEncoder = TextEncoder;
-// @ts-ignore
-global.TextDecoder = TextDecoder;
-
-import * as utilsModule from './misc';
-
-describe('utils', () => {
- /**
- * Print Error
- */
- it('should console.log with name, message and stack', () => {
- let err: Error;
-
- try {
- throw new Error('Test Error');
- } catch (e) {
- err = e as Error;
- }
-
- console.log = jest.fn();
-
- utilsModule.printError(err);
-
- expect((console.log as any).mock.calls[0][0]).toBe('Error Stack');
- expect((console.log as any).mock.calls[1][0]).toBe('Error Name');
- expect((console.log as any).mock.calls[2][0]).toBe('Error Message');
- });
-
- it('should get the most common string in an array', () => {
- const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8];
-
- const mostOccured = utilsModule.mostCommonString(arr);
-
- expect(mostOccured).toBe(8);
- });
-
- it('should get the last element of the array if every element only appears once', () => {
- const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
-
- const mostOccured = utilsModule.mostCommonString(arr);
-
- expect(mostOccured).toBe(0);
- });
-
- it('should get value type by a given value', () => {
- const fooString = 'fooString';
- const fooBool = true;
- const fooNumber = 6;
- const fooList: number[] = [1, 2, 3];
- const fooArray: string[] = ['a', 'b', 'c'];
- const fooTuple: [string, number] = ['hello', 10];
- const fooUint8Arr = new Uint8Array([1, 2, 3, 4, 5]);
- const fooUint16Arr = new Uint16Array([1, 2, 3, 4, 5]);
- const fooBlob = new Blob([fooUint8Arr as BlobPart], {});
- const fooFile = new File([fooUint8Arr as BlobPart], '');
-
- expect(utilsModule.getVarType(fooString)).toBe('String');
- expect(utilsModule.getVarType(fooBool)).toBe('Boolean');
- expect(utilsModule.getVarType(fooNumber)).toBe('Number');
- expect(utilsModule.getVarType(fooList)).toBe('Array');
- expect(utilsModule.getVarType(fooArray)).toBe('Array');
- expect(utilsModule.getVarType(fooTuple)).toBe('Array');
- expect(utilsModule.getVarType(fooUint8Arr)).toBe('Uint8Array');
- expect(utilsModule.getVarType(fooUint16Arr)).toBe('Uint16Array');
- expect(utilsModule.getVarType(fooBlob)).toBe('Blob');
- expect(utilsModule.getVarType(fooFile)).toBe('File');
- });
-
- it('should check type', () => {
- expect(
- utilsModule.checkType({
- value: 999,
- allowedTypes: ['Number'],
- paramName: 'paramName1',
- functionName: 'functionName1',
- })
- ).toBe(true);
-
- expect(
- utilsModule.checkType({
- value: 'foo',
- allowedTypes: ['Number', 'String'],
- paramName: 'paramName2',
- functionName: 'functionName2',
- })
- ).toBe(true);
-
- expect(
- utilsModule.checkType({
- value: [1, 2],
- allowedTypes: ['Number', 'Array'],
- paramName: 'paramName3',
- functionName: 'functionName3',
- })
- ).toBe(true);
-
- expect(
- utilsModule.checkType({
- value: new Uint8Array([1, 2, 3]),
- allowedTypes: ['String', 'Uint8Array'],
- paramName: 'paramName4',
- functionName: 'functionName4',
- })
- ).toBe(true);
- });
-
- it('should check auth type', () => {
- const authSig = {
- sig: '',
- derivedVia: 'web3.eth.personal.sign',
- signedMessage:
- 'I am creating an account to use Lit Protocol at 2022-04-12T09:23:31.290Z',
- address: '0x7e7763BE1379Bb48AFEE4F5c232Fb67D7c03947F',
- };
-
- expect(
- utilsModule.checkIfAuthSigRequiresChainParam(authSig, 'ethereum', 'fName')
- ).toBe(true);
-
- expect(
- utilsModule.checkIfAuthSigRequiresChainParam(
- {
- ethereum: 'foo',
- },
- '123',
- 'fName'
- )
- ).toBe(true);
- });
-});
-
-describe('double escaped JSON string', () => {
- test('A doubly escaped JSON string', () => {
- const doublyEscapedJson = '{\\"key\\": \\"value\\"}';
- expect(utilsModule.normalizeAndStringify(doublyEscapedJson)).toBe(
- '{"key":"value"}'
- );
- });
-
- test('A triply escaped JSON string', () => {
- const triplyEscapedJson = '{\\\\\\"key\\\\\\": \\\\\\"value\\\\\\"}';
- expect(utilsModule.normalizeAndStringify(triplyEscapedJson)).toBe(
- '{"key":"value"}'
- );
- });
-
- test('A correctly escaped JSON string (for comparison)', () => {
- const correctlyEscapedJson = '{"key":"value"}';
- expect(utilsModule.normalizeAndStringify(correctlyEscapedJson)).toBe(
- '{"key":"value"}'
- );
- });
-
- test('regular siwe message', () => {
- const regularString =
- 'litprotocol.com wants you to sign in with your Ethereum account:\\n0x3edB...';
-
- expect(utilsModule.normalizeAndStringify(regularString)).toBe(
- regularString
- );
- });
-});
-it('should remove hex prefix from a string', () => {
- const input = '0xabcdef';
- const expectedOutput = 'abcdef';
-
- const result = utilsModule.removeHexPrefix(input);
-
- expect(result).toBe(expectedOutput);
-});
-
-it('should not remove hex prefix if it is not present', () => {
- const input = 'abcdef';
- const expectedOutput = 'abcdef';
-
- const result = utilsModule.removeHexPrefix(input);
-
- expect(result).toBe(expectedOutput);
-});
-
-it('should get ip address', async () => {
- // polyfill fetch
- const fetch = require('node-fetch');
- global.fetch = fetch;
-
- const ipAddres = await utilsModule.getIpAddress('cayenne.litgateway.com');
- expect(ipAddres).toBe('207.244.70.36');
-});
diff --git a/packages/misc/src/lib/misc.ts b/packages/misc/src/lib/misc.ts
deleted file mode 100644
index 3888723540..0000000000
--- a/packages/misc/src/lib/misc.ts
+++ /dev/null
@@ -1,749 +0,0 @@
-import { Contract } from '@ethersproject/contracts';
-import { JsonRpcProvider } from '@ethersproject/providers';
-
-import {
- ABI_ERC20,
- InvalidArgumentException,
- InvalidParamType,
- LIT_AUTH_SIG_CHAIN_KEYS,
- LIT_CHAINS,
- LIT_NETWORK,
- LIT_NETWORK_VALUES,
- LOG_LEVEL,
- LOG_LEVEL_VALUES,
- LitEVMChainKeys,
- NetworkError,
- RELAYER_URL_BY_NETWORK,
- RemovedFunctionError,
- UnknownError,
- WrongNetworkException,
-} from '@lit-protocol/constants';
-import { LogManager } from '@lit-protocol/logger';
-import {
- Chain,
- AuthSig,
- NodeErrorV3,
- ClaimResult,
- LitNodeClientConfig,
- MintCallback,
- RelayClaimProcessor,
-} from '@lit-protocol/types';
-
-const logBuffer: any[][] = [];
-
-// Module scoped variable to store the LitNodeClientConfig passed to LitCore
-let litConfig: LitNodeClientConfig | undefined;
-
-export const setMiscLitConfig = (config: LitNodeClientConfig | undefined) => {
- litConfig = config;
-};
-
-/**
- *
- * Print error message based on Error interface
- *
- * @param { Error } e
- * @returns { void }
- */
-export const printError = (e: Error): void => {
- console.log('Error Stack', e.stack);
- console.log('Error Name', e.name);
- console.log('Error Message', e.message);
-};
-
-/**
- *
- * Find the element that occurs the most in an array
- *
- * @param { Array } arr
- * @returns { any } the element that appeared the most
- */
-export const mostCommonString = (arr: T[]): T | undefined => {
- return arr
- .sort(
- (a: T, b: T) =>
- arr.filter((v: T) => v === a).length -
- arr.filter((v: T) => v === b).length
- )
- .pop();
-};
-
-export const findMostCommonResponse = (responses: object[]): object => {
- const result: Record = {};
-
- // Aggregate all values for each key across all responses
- const keys = new Set(responses.flatMap(Object.keys));
-
- for (const key of keys) {
- const values = responses.map(
- (response: Record) => response[key]
- );
-
- // Filter out undefined values before processing
- const filteredValues = values.filter(
- (value) => value !== undefined && value !== ''
- );
-
- if (filteredValues.length === 0) {
- result[key] = undefined; // or set a default value if needed
- } else if (
- typeof filteredValues[0] === 'object' &&
- !Array.isArray(filteredValues[0])
- ) {
- // Recursive case for objects
- result[key] = findMostCommonResponse(filteredValues);
- } else {
- // Most common element from filtered values
- result[key] = mostCommonString(filteredValues);
- }
- }
-
- return result;
-};
-
-declare global {
- var wasmExport: any;
- var wasmECDSA: any;
- var logger: any;
- var logManager: any;
-}
-
-export const throwRemovedFunctionError = (functionName: string) => {
- throw new RemovedFunctionError(
- {
- info: {
- functionName,
- },
- },
- `This function "${functionName}" has been removed. Please use the old SDK.`
- );
-};
-
-export const bootstrapLogManager = (
- id: string,
- level: LOG_LEVEL_VALUES = LOG_LEVEL.DEBUG
-) => {
- if (!globalThis.logManager) {
- globalThis.logManager = LogManager.Instance;
- globalThis.logManager.withConfig({
- condenseLogs: true,
- });
- globalThis.logManager.setLevel(level);
- }
-
- globalThis.logger = globalThis.logManager.get(id);
-};
-
-export const getLoggerbyId = (id: string) => {
- return globalThis.logManager.get(id);
-};
-
-/**
- *
- * console.log but prepend [Lit-JS-SDK] before the message
- *
- * @param { any } args
- *
- * @returns { void }
- */
-export const log = (...args: any): void => {
- if (!globalThis) {
- // there is no globalThis, just print the log
- console.log(...args);
- return;
- }
-
- // check if config is loaded yet
- if (!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.debug(...log);
- }
-
- globalThis?.logger && globalThis?.logger.debug(...args);
-};
-
-export const logWithRequestId = (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 (!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.logManager.get(globalThis.logger.category, id).debug(...log);
- }
-
- globalThis?.logger &&
- globalThis.logManager.get(globalThis.logger.category, id).debug(...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 (!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.logManager.get(globalThis.logger.category, id).error(...log);
- }
-
- globalThis?.logger &&
- globalThis.logManager.get(globalThis.logger.category, id).error(...args);
-};
-
-export const logError = (...args: any) => {
- if (!globalThis) {
- // there is no globalThis, just print the log
- console.log(...args);
- return;
- }
-
- // check if config is loaded yet
- if (!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.logManager.get(globalThis.logger.category).error(...log);
- }
-
- globalThis?.logger &&
- globalThis.logManager.get(globalThis.logger.category).error(...args);
-};
-
-/**
- *
- * Get the type of a variable, could be an object instance type.
- * eg Uint8Array instance should return 'Uint8Array` as string
- * or simply a `string` or `int` type
- *
- * @param { any } value
- * @returns { string } type
- */
-export const getVarType = (value: any): string => {
- return Object.prototype.toString.call(value).slice(8, -1);
-};
-
-/**
- *
- * Check if the given value is the given type
- * If not, throw `invalidParamType` error
- *
- * @property { any } value
- * @property { Array } allowedTypes
- * @property { string } paramName
- * @property { string } functionName
- * @property { boolean } throwOnError
- *
- * @returns { Boolean } true/false
- *
- */
-export const checkType = ({
- value,
- allowedTypes,
- paramName,
- functionName,
- throwOnError = true,
-}: {
- value: any;
- allowedTypes: string[] | any;
- paramName: string;
- functionName: string;
- throwOnError?: boolean;
-}): boolean => {
- // -- validate
- if (!allowedTypes.includes(getVarType(value))) {
- const message = `Expecting ${allowedTypes.join(
- ' or '
- )} type for parameter named ${paramName} in Lit-JS-SDK function ${functionName}(), but received "${getVarType(
- value
- )}" type instead. value: ${
- value instanceof Object ? JSON.stringify(value) : value
- }`;
-
- if (throwOnError) {
- throw new InvalidParamType(
- {
- info: {
- allowedTypes,
- value,
- paramName,
- functionName,
- },
- },
- message
- );
- }
- return false;
- }
-
- // -- else
- return true;
-};
-
-/**
- *
- * @param { AuthSig } authSig
- * @param { string } chain
- * @param { string } functionName
- *
- * @returns { boolean }
- */
-export const checkIfAuthSigRequiresChainParam = (
- authSig: AuthSig,
- chain: string,
- functionName: string
-): boolean => {
- log('checkIfAuthSigRequiresChainParam');
- for (const key of LIT_AUTH_SIG_CHAIN_KEYS) {
- if (key in authSig) {
- return true;
- }
- }
-
- // if we're here, then we need the chain param
- if (
- !checkType({
- value: chain,
- allowedTypes: ['String'],
- paramName: 'chain',
- functionName,
- })
- ) {
- return false;
- }
-
- return true;
-};
-
-/**
- * TODO: Fix "any"
- * Sort object
- *
- * @param { any } obj
- * @returns { any }
- */
-export const sortedObject = (obj: any): any => {
- if (typeof obj !== 'object' || obj === null) {
- return obj;
- }
- if (Array.isArray(obj)) {
- return obj.map(sortedObject);
- }
- const sortedKeys = Object.keys(obj).sort();
- const result: any = {};
-
- // NOTE: Use forEach instead of reduce for performance with large objects eg Wasm code
- sortedKeys.forEach((key) => {
- result[key] = sortedObject(obj[key]);
- });
-
- return result;
-};
-
-/**
- *
- * Convert number to hex
- * @param { number } v
- * @return { string } hex value prexied with 0x
- */
-export const numberToHex = (v: number): string => {
- return '0x' + v.toString(16);
-};
-
-/**
- *
- * Check if the given value is the given type
- * If not, throw `invalidParamType` error
- *
- * @param { any } value
- * @param { string } type
- * @param { string } paramName
- * @param { string } functionName
- * @param { boolean } throwOnError
- * @returns { Boolean } true/false
- */
-export const is = (
- value: any,
- type: string,
- paramName: string,
- functionName: string,
- throwOnError: boolean = true
-): boolean => {
- if (getVarType(value) !== type) {
- const message = `Expecting "${type}" type for parameter named ${paramName} in Lit-JS-SDK function ${functionName}(), but received "${getVarType(
- value
- )}" type instead. value: ${
- value instanceof Object ? JSON.stringify(value) : value
- }`;
-
- if (throwOnError) {
- throw new InvalidParamType(
- {
- info: {
- value,
- paramName,
- functionName,
- },
- },
- message
- );
- }
- return false;
- }
-
- return true;
-};
-
-export const isNode = () => {
- let isNode = false;
- // @ts-ignore
- if (typeof process === 'object') {
- // @ts-ignore
- if (typeof process.versions === 'object') {
- // @ts-ignore
- if (typeof process.versions.node !== 'undefined') {
- isNode = true;
- }
- }
- }
- return isNode;
-};
-export const isBrowser = () => {
- return isNode() === false;
-};
-
-/**
- *
- * Get the number of decimal places in a token
- *
- * @property { string } contractAddress The token contract address
- * @property { LitEVMChainKeys } chain The chain on which the token is deployed
- *
- * @returns { number } The number of decimal places in the token
- */
-export const decimalPlaces = async ({
- contractAddress,
- chain,
-}: {
- contractAddress: string;
- chain: LitEVMChainKeys;
-}): Promise => {
- const rpcUrl = LIT_CHAINS[chain].rpcUrls[0] as string;
-
- const web3 = new JsonRpcProvider({
- url: rpcUrl,
- skipFetchSetup: true,
- });
-
- const contract = new Contract(contractAddress, (ABI_ERC20 as any).abi, web3);
-
- return await contract['decimals']();
-};
-
-/**
- *
- * Generate a random path (for testing)
- *
- * @returns { string } The random path
- */
-export const genRandomPath = (): string => {
- return (
- '/' +
- Math.random().toString(36).substring(2, 15) +
- Math.random().toString(36).substring(2, 15)
- );
-};
-
-/**
- * Checks if the given LIT_NETWORK value is supported.
- * @param litNetwork - The Lit Network value to check.
- * @throws {Error} - Throws an error if the Lit Network value is not supported.
- */
-export function isSupportedLitNetwork(
- litNetwork: LIT_NETWORK_VALUES
-): asserts litNetwork is LIT_NETWORK_VALUES {
- const supportedNetworks = Object.values(LIT_NETWORK);
-
- if (!supportedNetworks.includes(litNetwork)) {
- throw new WrongNetworkException(
- {
- info: {
- litNetwork,
- supportedNetworks,
- },
- },
- `Unsupported LitNetwork! (${supportedNetworks.join('|')}) are supported.`
- );
- }
-}
-
-export const defaultMintClaimCallback: MintCallback<
- RelayClaimProcessor
-> = async (
- params: ClaimResult,
- network: LIT_NETWORK_VALUES = LIT_NETWORK.NagaDev
-): Promise => {
- isSupportedLitNetwork(network);
-
- const AUTH_CLAIM_PATH = '/auth/claim';
-
- const relayUrl: string = params.relayUrl || RELAYER_URL_BY_NETWORK[network];
-
- if (!relayUrl) {
- throw new InvalidArgumentException(
- {
- info: {
- network,
- relayUrl,
- },
- },
- 'No relayUrl provided and no default relayUrl found for network'
- );
- }
-
- const relayUrlWithPath = relayUrl + AUTH_CLAIM_PATH;
-
- const response = await fetch(relayUrlWithPath, {
- method: 'POST',
- body: JSON.stringify(params),
- headers: {
- 'api-key': params.relayApiKey
- ? params.relayApiKey
- : '67e55044-10b1-426f-9247-bb680e5fe0c8_relayer',
- 'Content-Type': 'application/json',
- },
- });
-
- if (response.status < 200 || response.status >= 400) {
- const errResp = (await response.json()) ?? '';
- const errStmt = `An error occurred requesting "/auth/claim" endpoint ${JSON.stringify(
- errResp
- )}`;
- console.warn(errStmt);
- throw new NetworkError(
- {
- info: {
- response,
- errResp,
- },
- },
- `An error occurred requesting "/auth/claim" endpoint`
- );
- }
-
- const body = await response.json();
- return body.requestId;
-};
-
-/**
- * Adds a '0x' prefix to a string if it doesn't already have one.
- * @param str - The input string.
- * @returns The input string with a '0x' prefix.
- */
-export const hexPrefixed = (str: string): `0x${string}` => {
- if (str.startsWith('0x')) {
- return str as `0x${string}`;
- }
-
- return ('0x' + str) as `0x${string}`;
-};
-
-/**
- * Removes the '0x' prefix from a hexadecimal string if it exists.
- *
- * @param str - The input string.
- * @returns The input string with the '0x' prefix removed, if present.
- */
-export const removeHexPrefix = (str: string) => {
- if (str.startsWith('0x')) {
- return str.slice(2);
- }
-
- return str;
-};
-
-/**
- * getEnv - Determine the debug status based on environment variables or URL query parameters.
- *
- * @function
- * @export
- * @param {Object} [options={}] - Configuration options for determining debug status.
- * @param {string} [options.nodeEnvVar='DEBUG'] - The Node.js environment variable to check.
- * @param {string} [options.urlQueryParam='dev'] - The URL query parameter to check in a browser environment.
- * @param {string} [options.urlQueryValue='debug=true'] - The expected value of the URL query parameter to enable debugging.
- * @param {boolean} [options.defaultValue=false] - The default boolean value to return if no debug conditions are met.
- * @returns {boolean} - True if debug conditions are met, otherwise returns the provided defaultValue.
- *
- * @example
- * // Usage in Node.js environment
- * process.env.DEBUG = 'true';
- * console.log(getEnv()); // Outputs: true
- *
- * @example
- * // Usage in Browser environment with URL: http://example.com?dev=debug=true
- * console.log(getEnv()); // Outputs: true
- */
-export function getEnv({
- nodeEnvVar = 'DEBUG',
- urlQueryParam = 'dev',
- urlQueryValue = 'debug=true',
- defaultValue = false,
-} = {}) {
- // Node.js environment
- if (isNode()) {
- return process.env[nodeEnvVar] === 'true';
- }
- // Browser environment
- else if (isBrowser()) {
- const urlParams = new URLSearchParams(window.location.search);
- return urlParams.get(urlQueryParam) === urlQueryValue;
- }
- // Default
- return defaultValue;
-}
-
-export function sendRequest(
- url: string,
- req: RequestInit,
- requestId: string
-): Promise {
- return fetch(url, req)
- .then(async (response) => {
- const isJson = response.headers
- .get('content-type')
- ?.includes('application/json');
-
- const data = isJson ? await response.json() : null;
-
- if (!response.ok) {
- // get error message from body or default to response status
- const error = data || response.status;
- return Promise.reject(error);
- }
-
- return data;
- })
- .catch((error: NodeErrorV3) => {
- logErrorWithRequestId(
- requestId,
- `Something went wrong, internal id for request: lit_${requestId}. Please provide this identifier with any support requests. ${
- error?.message || error?.details
- ? `Error is ${error.message} - ${error.details}`
- : ''
- }`
- );
- return Promise.reject(error);
- });
-}
-
-/**
- * Attempts to normalize a string by unescaping it until it can be parsed as a JSON object,
- * then stringifies it exactly once. If the input is a regular string that does not represent
- * a JSON object or array, the function will return it as is without modification.
- * This function is designed to handle cases where strings might be excessively escaped due
- * to multiple layers of encoding, ensuring that JSON data is stored in a consistent and
- * predictable format, and regular strings are left unchanged.
- *
- * @param input The potentially excessively escaped string.
- * @return A string that is either the JSON.stringify version of the original JSON object
- * or the original string if it does not represent a JSON object or array.
- */
-export function normalizeAndStringify(input: string): string {
- try {
- // Directly return the string if it's not in a JSON format
- if (!input.startsWith('{') && !input.startsWith('[')) {
- return input;
- }
-
- // Attempt to parse the input as JSON
- const parsed = JSON.parse(input);
-
- // If parsing succeeds, return the stringified version of the parsed JSON
- return JSON.stringify(parsed);
- } catch (error) {
- // If parsing fails, it might be due to extra escaping
- const unescaped = input.replace(/\\(.)/g, '$1');
-
- // If unescaping doesn't change the string, return it as is
- if (input === unescaped) {
- return input;
- }
-
- // Otherwise, recursively call the function with the unescaped string
- return normalizeAndStringify(unescaped);
- }
-}
-
-/**
- * Retrieves the IP address associated with a given domain.
- * @param domain - The domain for which to retrieve the IP address.
- * @returns A Promise that resolves to the IP address.
- * @throws If no IP address is found or if the domain name is invalid.
- */
-export async function getIpAddress(domain: string): Promise {
- const apiURL = `https://dns.google/resolve?name=${domain}&type=A`;
-
- try {
- const response = await fetch(apiURL);
- const data = await response.json();
-
- if (data.Answer && data.Answer.length > 0) {
- return data.Answer[0].data;
- } else {
- throw new UnknownError(
- {
- info: {
- domain,
- apiURL,
- },
- },
- 'No IP Address found or bad domain name'
- );
- }
- } catch (error: any) {
- throw new UnknownError(
- {
- info: {
- domain,
- apiURL,
- },
- cause: error,
- },
- 'message' in error ? error.message : String(error)
- );
- }
-}
diff --git a/packages/misc/src/lib/params-validators.ts b/packages/misc/src/lib/params-validators.ts
deleted file mode 100644
index 3c7c59a92a..0000000000
--- a/packages/misc/src/lib/params-validators.ts
+++ /dev/null
@@ -1,680 +0,0 @@
-/**
- * Param Validators is an abstraction of validating params of a function, each validator
- * returns a boolean value indicating whether the validation is passed or not.
- */
-
-import { isHexString } from 'ethers/lib/utils';
-
-import {
- EITHER_TYPE,
- ELeft,
- ERight,
- IEither,
- InvalidArgumentException,
- InvalidBooleanException,
- InvalidParamType,
- ParamsMissingError,
-} from '@lit-protocol/constants';
-import {
- AcceptedFileType,
- AccessControlConditions,
- DecryptFromJsonProps,
- DecryptRequest,
- EncryptUint8ArrayRequest,
- EncryptFileRequest,
- EncryptRequest,
- EncryptStringRequest,
- EncryptToJsonPayload,
- EncryptToJsonProps,
- EvmContractConditions,
- JsonExecutionSdkParams,
- SolRpcConditions,
- UnifiedAccessControlConditions,
- AuthSig,
- AuthenticationContext,
-} from '@lit-protocol/types';
-
-import { checkIfAuthSigRequiresChainParam, checkType, is, log } from './misc';
-import { isValidBooleanExpression } from './utils';
-
-export const safeParams = ({
- functionName,
- params,
-}: {
- functionName: string;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- params: any[] | any;
-}): IEither => {
- if (!paramsValidators[functionName]) {
- log(`This function ${functionName} is skipping params safe guarding.`);
- return ERight(undefined);
- }
-
- const paramValidators = paramsValidators[functionName](params);
-
- for (const validator of paramValidators) {
- const validationResponse = validator.validate();
- if (validationResponse.type === EITHER_TYPE.ERROR) {
- return validationResponse;
- }
- }
-
- return ERight(undefined);
-};
-
-export const paramsValidators: Record<
- string,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (params: any) => ParamsValidator[]
-> = {
- // ========== NO AUTH MATERIAL NEEDED FOR CLIENT SIDE ENCRYPTION ==========
- encrypt: (params: EncryptRequest) => [
- new AccessControlConditionsValidator('encrypt', params),
- ],
-
- encryptUint8Array: (params: EncryptUint8ArrayRequest) => [
- new AccessControlConditionsValidator('encryptUint8Array', params),
- new Uint8ArrayValidator('encryptUint8Array', params.dataToEncrypt),
- ],
-
- encryptFile: (params: EncryptFileRequest) => [
- new AccessControlConditionsValidator('encryptFile', params),
- new FileValidator('encryptFile', params.file),
- ],
-
- encryptString: (params: EncryptStringRequest) => [
- new AccessControlConditionsValidator('encryptString', params),
- new StringValidator('encryptString', params.dataToEncrypt, 'dataToEncrypt'),
- ],
-
- encryptToJson: (params: EncryptToJsonProps) => [
- new AccessControlConditionsValidator('encryptToJson', params),
- new EncryptToJsonValidator('encryptToJson', params),
- ],
-
- // ========== REQUIRED AUTH MATERIAL VALIDATORS ==========
- executeJs: (params: JsonExecutionSdkParams) => [
- new AuthMaterialValidator('executeJs', params),
- new ExecuteJsValidator('executeJs', params),
- ],
-
- decrypt: (params: DecryptRequest) => [
- new AccessControlConditionsValidator('decrypt', params),
- new AuthMaterialValidator('decrypt', params, true),
- new StringValidator('decrypt', params.ciphertext, 'ciphertext'),
- ],
-
- decryptFromJson: (params: DecryptFromJsonProps) => [
- new AuthMaterialValidator('decryptFromJson', params),
- new DecryptFromJsonValidator('decryptFromJson', params.parsedJsonData),
- ],
-};
-
-export type ParamsValidatorsType = typeof paramsValidators;
-
-//////////////////////// VALIDATORS ////////////////////////
-
-interface ParamsValidator {
- validate: () => IEither;
-}
-
-class EncryptToJsonValidator implements ParamsValidator {
- private fnName: string;
- private readonly params: EncryptToJsonProps;
-
- constructor(fnName: string, params: EncryptToJsonProps) {
- this.fnName = fnName;
- this.params = params;
- }
-
- validate(): IEither {
- const { file, string } = this.params;
-
- if (string === undefined && file === undefined)
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'string',
- value: string,
- functionName: this.fnName,
- },
- },
- 'Either string or file must be provided'
- )
- );
-
- if (string !== undefined && file !== undefined)
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'string',
- value: string,
- functionName: this.fnName,
- },
- },
- 'Provide only a "string" or "file" to encrypt; you cannot provide both'
- )
- );
-
- return ERight(undefined);
- }
-}
-
-class DecryptFromJsonValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly params: EncryptToJsonPayload;
-
- constructor(fnName: string, params: EncryptToJsonPayload) {
- this.fnName = fnName;
- this.params = params;
- }
-
- validate(): IEither {
- const validators = [new StringValidator(this.fnName, this.params.dataType)];
-
- for (const validator of validators) {
- const validationResponse = validator.validate();
- if (validationResponse.type === EITHER_TYPE.ERROR) {
- return validationResponse;
- }
- }
-
- const { dataType } = this.params;
-
- if (dataType !== 'string' && dataType !== 'file')
- return ELeft(
- new InvalidArgumentException(
- {
- info: {
- functionName: this.fnName,
- dataType,
- },
- },
- `dataType of %s is not valid. Must be 'string' or 'file'.`,
- dataType
- )
- );
-
- return ERight(undefined);
- }
-}
-
-class Uint8ArrayValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly paramName: string;
- private readonly uint8array?: Uint8Array;
-
- constructor(
- fnName: string,
- uint8array?: Uint8Array,
- paramName: string = 'uint8array'
- ) {
- this.fnName = fnName;
- this.paramName = paramName;
- this.uint8array = uint8array;
- }
-
- validate(): IEither {
- if (!this.uint8array) {
- return ELeft(new InvalidParamType({}, 'uint8array is undefined'));
- }
-
- if (
- !checkType({
- value: this.uint8array,
- allowedTypes: ['Uint8Array'],
- paramName: this.paramName,
- functionName: this.fnName,
- })
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: this.paramName,
- value: this.uint8array,
- functionName: this.fnName,
- },
- },
- '%s is not a Uint8Array',
- this.paramName
- )
- );
-
- return ERight(undefined);
- }
-}
-
-class StringValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly paramName: string;
- private readonly checkIsHex: boolean;
- private readonly str?: string;
-
- constructor(
- fnName: string,
- str?: string,
- paramName: string = 'string',
- checkIsHex: boolean = false
- ) {
- this.fnName = fnName;
- this.paramName = paramName;
- this.checkIsHex = checkIsHex;
- this.str = str;
- }
-
- validate(): IEither {
- if (!this.str) {
- return ELeft(new InvalidParamType({}, 'str is undefined'));
- }
-
- if (
- !checkType({
- value: this.str,
- allowedTypes: ['String'],
- paramName: this.paramName,
- functionName: this.fnName,
- })
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: this.paramName,
- value: this.str,
- functionName: this.fnName,
- },
- },
- '%s is not a string',
- this.paramName
- )
- );
-
- if (this.checkIsHex && !isHexString(this.str)) {
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: this.paramName,
- value: this.str,
- functionName: this.fnName,
- },
- },
- '%s is not a valid hex string',
- this.paramName
- )
- );
- }
-
- return ERight(undefined);
- }
-}
-
-interface ExecuteJsValidatorProps {
- code?: string;
- ipfsId?: string;
-}
-
-class ExecuteJsValidator implements ParamsValidator {
- private fnName: string;
- private readonly params: ExecuteJsValidatorProps;
-
- constructor(fnName: string, params: ExecuteJsValidatorProps) {
- this.fnName = fnName;
- this.params = params;
- }
-
- validate(): IEither {
- const { code, ipfsId } = this.params;
-
- // -- validate: either 'code' or 'ipfsId' must exists
- if (!code && !ipfsId) {
- return ELeft(
- new ParamsMissingError(
- {
- info: {
- functionName: this.fnName,
- params: this.params,
- },
- },
- 'You must pass either code or ipfsId'
- )
- );
- }
-
- // -- validate: 'code' and 'ipfsId' can't exists at the same time
- if (code && ipfsId) {
- return ELeft(
- new ParamsMissingError(
- {
- info: {
- functionName: this.fnName,
- params: this.params,
- },
- },
- "You cannot have both 'code' and 'ipfs' at the same time"
- )
- );
- }
-
- return ERight(undefined);
- }
-}
-
-class FileValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly file?: AcceptedFileType;
-
- constructor(fnName: string, file?: AcceptedFileType) {
- this.fnName = fnName;
- this.file = file;
- }
-
- validate(): IEither {
- if (!this.file) {
- return ELeft(
- new InvalidArgumentException(
- {
- info: {
- functionName: this.fnName,
- file: this.file,
- },
- },
- 'You must pass file param'
- )
- );
- }
-
- const allowedTypes = ['Blob', 'File', 'Uint8Array'];
- if (
- !checkType({
- value: this.file,
- allowedTypes,
- paramName: 'file',
- functionName: this.fnName,
- })
- )
- return ELeft(
- new InvalidArgumentException(
- {
- info: {
- functionName: this.fnName,
- file: this.file,
- allowedTypes,
- },
- },
- 'File param is not a valid Blob or File object'
- )
- );
-
- return ERight(undefined);
- }
-}
-
-export interface AuthMaterialValidatorProps {
- chain?: string;
- authSig?: AuthSig;
- authContext?: AuthenticationContext;
-}
-
-class AuthMaterialValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly authMaterial: AuthMaterialValidatorProps;
- private readonly checkIfAuthSigRequiresChainParam: boolean;
-
- constructor(
- fnName: string,
- params: AuthMaterialValidatorProps,
- checkIfAuthSigRequiresChainParam: boolean = false
- ) {
- this.fnName = fnName;
- this.authMaterial = params;
- this.checkIfAuthSigRequiresChainParam = checkIfAuthSigRequiresChainParam;
- }
-
- validate(): IEither {
- const { authSig } = this.authMaterial;
-
- if (authSig && !is(authSig, 'Object', 'authSig', this.fnName))
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'authSig',
- value: authSig,
- functionName: this.fnName,
- },
- },
- 'authSig is not an object'
- )
- );
-
- if (this.checkIfAuthSigRequiresChainParam) {
- if (!this.authMaterial.chain)
- return ELeft(
- new InvalidArgumentException(
- {
- info: {
- functionName: this.fnName,
- chain: this.authMaterial.chain,
- },
- },
- 'You must pass chain param'
- )
- );
-
- if (
- authSig &&
- !checkIfAuthSigRequiresChainParam(
- authSig,
- this.authMaterial.chain,
- this.fnName
- )
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'authSig',
- value: authSig,
- functionName: this.fnName,
- },
- },
- 'authSig is not valid'
- )
- );
- }
-
- return ERight(undefined);
- }
-}
-
-export interface AccessControlConditionsValidatorProps {
- accessControlConditions?: AccessControlConditions;
- evmContractConditions?: EvmContractConditions;
- solRpcConditions?: SolRpcConditions;
- unifiedAccessControlConditions?: UnifiedAccessControlConditions;
-}
-
-class AccessControlConditionsValidator implements ParamsValidator {
- private readonly fnName: string;
- private readonly conditions: AccessControlConditionsValidatorProps;
-
- constructor(fnName: string, params: AccessControlConditionsValidatorProps) {
- this.fnName = fnName;
- this.conditions = params;
- }
-
- validate(): IEither {
- const {
- accessControlConditions,
- evmContractConditions,
- solRpcConditions,
- unifiedAccessControlConditions,
- } = this.conditions;
-
- if (
- accessControlConditions &&
- !is(
- accessControlConditions,
- 'Array',
- 'accessControlConditions',
- this.fnName
- )
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'accessControlConditions',
- value: accessControlConditions,
- functionName: this.fnName,
- },
- },
- '%s is not an array',
- 'accessControlConditions'
- )
- );
- if (
- evmContractConditions &&
- !is(evmContractConditions, 'Array', 'evmContractConditions', this.fnName)
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'evmContractConditions',
- value: evmContractConditions,
- functionName: this.fnName,
- },
- },
- '%s is not an array',
- 'evmContractConditions'
- )
- );
-
- if (
- solRpcConditions &&
- !is(solRpcConditions, 'Array', 'solRpcConditions', this.fnName)
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'solRpcConditions',
- value: solRpcConditions,
- functionName: this.fnName,
- },
- },
- '%s is not an array',
- 'solRpcConditions'
- )
- );
-
- if (
- unifiedAccessControlConditions &&
- !is(
- unifiedAccessControlConditions,
- 'Array',
- 'unifiedAccessControlConditions',
- this.fnName
- )
- )
- return ELeft(
- new InvalidParamType(
- {
- info: {
- param: 'unifiedAccessControlConditions',
- value: unifiedAccessControlConditions,
- functionName: this.fnName,
- },
- },
- '%s is not an array',
- 'unifiedAccessControlConditions'
- )
- );
-
- if (
- !accessControlConditions &&
- !evmContractConditions &&
- !solRpcConditions &&
- !unifiedAccessControlConditions
- )
- return ELeft(
- new InvalidArgumentException(
- {
- info: {
- functionName: this.fnName,
- conditions: this.conditions,
- },
- },
- 'You must pass either accessControlConditions, evmContractConditions, solRpcConditions or unifiedAccessControlConditions'
- )
- );
-
- if (
- accessControlConditions &&
- !isValidBooleanExpression(accessControlConditions)
- )
- return ELeft(
- new InvalidBooleanException(
- {
- info: {
- functionName: this.fnName,
- accessControlConditions,
- },
- },
- 'Invalid boolean Access Control Conditions'
- )
- );
-
- if (
- evmContractConditions &&
- !isValidBooleanExpression(evmContractConditions)
- )
- return ELeft(
- new InvalidBooleanException(
- {
- info: {
- functionName: this.fnName,
- evmContractConditions,
- },
- },
- 'Invalid boolean EVM Access Control Conditions'
- )
- );
-
- if (solRpcConditions && !isValidBooleanExpression(solRpcConditions))
- return ELeft(
- new InvalidBooleanException(
- {
- info: {
- functionName: this.fnName,
- solRpcConditions,
- },
- },
- 'Invalid boolean Solana Access Control Conditions'
- )
- );
-
- if (
- unifiedAccessControlConditions &&
- !isValidBooleanExpression(unifiedAccessControlConditions)
- )
- return ELeft(
- new InvalidBooleanException(
- {
- info: {
- functionName: this.fnName,
- unifiedAccessControlConditions,
- },
- },
- 'Invalid boolean Unified Access Control Conditions'
- )
- );
-
- return ERight(undefined);
- }
-}
diff --git a/packages/misc/tsconfig.json b/packages/misc/tsconfig.json
deleted file mode 100644
index f5b85657a8..0000000000
--- a/packages/misc/tsconfig.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "module": "commonjs",
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitOverride": true,
- "noPropertyAccessFromIndexSignature": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true
- },
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.lib.json"
- },
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/packages/misc/tsconfig.lib.json b/packages/misc/tsconfig.lib.json
deleted file mode 100644
index e85ef50f65..0000000000
--- a/packages/misc/tsconfig.lib.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "declaration": true,
- "types": []
- },
- "include": ["**/*.ts"],
- "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
-}
diff --git a/packages/misc/tsconfig.spec.json b/packages/misc/tsconfig.spec.json
deleted file mode 100644
index a2f7dd30d7..0000000000
--- a/packages/misc/tsconfig.spec.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "module": "commonjs",
- "types": ["jest", "node"],
- "allowJs": true
- },
- "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
-}
diff --git a/packages/nacl/.babelrc b/packages/nacl/.babelrc
deleted file mode 100644
index 158083d278..0000000000
--- a/packages/nacl/.babelrc
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "presets": [
- [
- "@nx/web/babel",
- {
- "useBuiltIns": "usage"
- }
- ]
- ]
-}
diff --git a/packages/nacl/.eslintrc.json b/packages/nacl/.eslintrc.json
deleted file mode 100644
index 9d9c0db55b..0000000000
--- a/packages/nacl/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/packages/nacl/README.md b/packages/nacl/README.md
deleted file mode 100644
index 9e0511c571..0000000000
--- a/packages/nacl/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Quick Start
-
-re-export of https://www.npmjs.com/package/nacl
-
-### node.js / browser
-
-```
-yarn add @lit-protocol/nacl
-```
diff --git a/packages/nacl/jest.config.ts b/packages/nacl/jest.config.ts
deleted file mode 100644
index d97296773f..0000000000
--- a/packages/nacl/jest.config.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/* eslint-disable */
-export default {
- displayName: 'nacl',
- preset: '../../jest.preset.js',
- globals: {
- 'ts-jest': {
- tsconfig: '/tsconfig.spec.json',
- },
- },
- transform: {
- '^.+\\.[t]s$': 'ts-jest',
- },
- moduleFileExtensions: ['ts', 'js', 'html'],
- coverageDirectory: '../../coverage/packages/nacl',
- setupFilesAfterEnv: ['../../jest.setup.js'],
-};
diff --git a/packages/nacl/package.json b/packages/nacl/package.json
deleted file mode 100644
index dd669d2048..0000000000
--- a/packages/nacl/package.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "name": "@lit-protocol/nacl",
- "license": "MIT",
- "homepage": "https://github.com/Lit-Protocol/js-sdk",
- "repository": {
- "type": "git",
- "url": "https://github.com/LIT-Protocol/js-sdk"
- },
- "keywords": [
- "library"
- ],
- "bugs": {
- "url": "https://github.com/LIT-Protocol/js-sdk/issues"
- },
- "type": "commonjs",
- "tags": [
- "universal"
- ],
- "gitHead": "0d7334c2c55f448e91fe32f29edc5db8f5e09e4b",
- "publishConfig": {
- "access": "public",
- "directory": "../../dist/packages/nacl"
- },
- "version": "8.0.0-alpha.0",
- "main": "./dist/src/index.js",
- "typings": "./dist/src/index.d.ts"
-}
diff --git a/packages/nacl/project.json b/packages/nacl/project.json
deleted file mode 100644
index d1447cfbfa..0000000000
--- a/packages/nacl/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "nacl",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/nacl/src",
- "projectType": "library",
- "targets": {
- "build": {
- "executor": "@nx/js:tsc",
- "outputs": ["{options.outputPath}"],
- "options": {
- "outputPath": "dist/packages/nacl",
- "main": "packages/nacl/src/index.ts",
- "tsConfig": "packages/nacl/tsconfig.lib.json",
- "assets": ["packages/nacl/*.md"],
- "updateBuildableProjectDepsInPackageJson": true
- }
- },
- "lint": {
- "executor": "@nx/linter:eslint",
- "outputs": ["{options.outputFile}"],
- "options": {
- "lintFilePatterns": ["packages/nacl/**/*.ts"]
- }
- },
- "test": {
- "executor": "@nx/jest:jest",
- "outputs": ["{workspaceRoot}/coverage/packages/nacl"],
- "options": {
- "jestConfig": "packages/nacl/jest.config.ts",
- "passWithNoTests": true
- }
- },
- "testWatch": {
- "executor": "@nx/jest:jest",
- "outputs": ["{workspaceRoot}/coverage/packages/nacl"],
- "options": {
- "jestConfig": "packages/nacl/jest.config.ts",
- "passWithNoTests": true,
- "watch": true
- }
- }
- },
- "tags": []
-}
diff --git a/packages/nacl/src/index.ts b/packages/nacl/src/index.ts
deleted file mode 100644
index 00965a232d..0000000000
--- a/packages/nacl/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './lib/nacl';
diff --git a/packages/nacl/src/lib/nacl.spec.ts b/packages/nacl/src/lib/nacl.spec.ts
deleted file mode 100644
index 6b2a39e9b3..0000000000
--- a/packages/nacl/src/lib/nacl.spec.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { nacl } from './nacl';
-
-describe('nacl', () => {
- it('should work', () => {
- expect(Object.keys(nacl)).toEqual([
- 'lowlevel',
- 'randomBytes',
- 'secretbox',
- 'scalarMult',
- 'box',
- 'sign',
- 'hash',
- 'verify',
- 'setPRNG',
- ]);
- });
-});
diff --git a/packages/nacl/src/lib/nacl.ts b/packages/nacl/src/lib/nacl.ts
deleted file mode 100644
index be2faaf584..0000000000
--- a/packages/nacl/src/lib/nacl.ts
+++ /dev/null
@@ -1,1331 +0,0 @@
-// @ts-nocheck
-// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
-// Public domain.
-//
-// Implementation derived from TweetNaCl version 20140427.
-// See for details: http://tweet_nacl.cr.yp.to/
-
-var u64 = function (h, l) {
- this.hi = h | (0 >>> 0);
- this.lo = l | (0 >>> 0);
-};
-var gf = function (init) {
- var i,
- r = new Float64Array(16);
- if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
- return r;
-};
-
-// Pluggable, initialized in high-level API below.
-var randombytes = function (/* x, n */) {
- throw new Error('no PRNG');
-};
-
-var _0 = new Uint8Array(16);
-var _9 = new Uint8Array(32);
-_9[0] = 9;
-
-var gf0 = gf(),
- gf1 = gf([1]),
- _121665 = gf([0xdb41, 1]),
- D = gf([
- 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898,
- 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203,
- ]),
- D2 = gf([
- 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130,
- 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406,
- ]),
- X = gf([
- 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c,
- 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169,
- ]),
- Y = gf([
- 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
- ]),
- I = gf([
- 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7,
- 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83,
- ]);
-
-function L32(x, c) {
- return (x << c) | (x >>> (32 - c));
-}
-
-function ld32(x, i) {
- var u = x[i + 3] & 0xff;
- u = (u << 8) | (x[i + 2] & 0xff);
- u = (u << 8) | (x[i + 1] & 0xff);
- return (u << 8) | (x[i + 0] & 0xff);
-}
-
-function dl64(x, i) {
- var h = (x[i] << 24) | (x[i + 1] << 16) | (x[i + 2] << 8) | x[i + 3];
- var l = (x[i + 4] << 24) | (x[i + 5] << 16) | (x[i + 6] << 8) | x[i + 7];
- return new u64(h, l);
-}
-
-function st32(x, j, u) {
- var i;
- for (i = 0; i < 4; i++) {
- x[j + i] = u & 255;
- u >>>= 8;
- }
-}
-
-function ts64(x, i, u) {
- x[i] = (u.hi >> 24) & 0xff;
- x[i + 1] = (u.hi >> 16) & 0xff;
- x[i + 2] = (u.hi >> 8) & 0xff;
- x[i + 3] = u.hi & 0xff;
- x[i + 4] = (u.lo >> 24) & 0xff;
- x[i + 5] = (u.lo >> 16) & 0xff;
- x[i + 6] = (u.lo >> 8) & 0xff;
- x[i + 7] = u.lo & 0xff;
-}
-
-function vn(x, xi, y, yi, n) {
- var i,
- d = 0;
- for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i];
- return (1 & ((d - 1) >>> 8)) - 1;
-}
-
-function crypto_verify_16(x, xi, y, yi) {
- return vn(x, xi, y, yi, 16);
-}
-
-function crypto_verify_32(x, xi, y, yi) {
- return vn(x, xi, y, yi, 32);
-}
-
-function core(out, inp, k, c, h) {
- var w = new Uint32Array(16),
- x = new Uint32Array(16),
- y = new Uint32Array(16),
- t = new Uint32Array(4);
- var i, j, m;
-
- for (i = 0; i < 4; i++) {
- x[5 * i] = ld32(c, 4 * i);
- x[1 + i] = ld32(k, 4 * i);
- x[6 + i] = ld32(inp, 4 * i);
- x[11 + i] = ld32(k, 16 + 4 * i);
- }
-
- for (i = 0; i < 16; i++) y[i] = x[i];
-
- for (i = 0; i < 20; i++) {
- for (j = 0; j < 4; j++) {
- for (m = 0; m < 4; m++) t[m] = x[(5 * j + 4 * m) % 16];
- t[1] ^= L32((t[0] + t[3]) | 0, 7);
- t[2] ^= L32((t[1] + t[0]) | 0, 9);
- t[3] ^= L32((t[2] + t[1]) | 0, 13);
- t[0] ^= L32((t[3] + t[2]) | 0, 18);
- for (m = 0; m < 4; m++) w[4 * j + ((j + m) % 4)] = t[m];
- }
- for (m = 0; m < 16; m++) x[m] = w[m];
- }
-
- if (h) {
- for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0;
- for (i = 0; i < 4; i++) {
- x[5 * i] = (x[5 * i] - ld32(c, 4 * i)) | 0;
- x[6 + i] = (x[6 + i] - ld32(inp, 4 * i)) | 0;
- }
- for (i = 0; i < 4; i++) {
- st32(out, 4 * i, x[5 * i]);
- st32(out, 16 + 4 * i, x[6 + i]);
- }
- } else {
- for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0);
- }
-}
-
-function crypto_core_salsa20(out, inp, k, c) {
- core(out, inp, k, c, false);
- return 0;
-}
-
-function crypto_core_hsalsa20(out, inp, k, c) {
- core(out, inp, k, c, true);
- return 0;
-}
-
-var sigma = new Uint8Array([
- 101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107,
-]);
-// "expand 32-byte k"
-
-function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
- var z = new Uint8Array(16),
- x = new Uint8Array(64);
- var u, i;
- if (!b) return 0;
- for (i = 0; i < 16; i++) z[i] = 0;
- for (i = 0; i < 8; i++) z[i] = n[i];
- while (b >= 64) {
- crypto_core_salsa20(x, z, k, sigma);
- for (i = 0; i < 64; i++) c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
- u = 1;
- for (i = 8; i < 16; i++) {
- u = (u + (z[i] & 0xff)) | 0;
- z[i] = u & 0xff;
- u >>>= 8;
- }
- b -= 64;
- cpos += 64;
- if (m) mpos += 64;
- }
- if (b > 0) {
- crypto_core_salsa20(x, z, k, sigma);
- for (i = 0; i < b; i++) c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
- }
- return 0;
-}
-
-function crypto_stream_salsa20(c, cpos, d, n, k) {
- return crypto_stream_salsa20_xor(c, cpos, null, 0, d, n, k);
-}
-
-function crypto_stream(c, cpos, d, n, k) {
- var s = new Uint8Array(32);
- crypto_core_hsalsa20(s, n, k, sigma);
- return crypto_stream_salsa20(c, cpos, d, n.subarray(16), s);
-}
-
-function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
- var s = new Uint8Array(32);
- crypto_core_hsalsa20(s, n, k, sigma);
- return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, n.subarray(16), s);
-}
-
-function add1305(h, c) {
- var j,
- u = 0;
- for (j = 0; j < 17; j++) {
- u = (u + ((h[j] + c[j]) | 0)) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
-}
-
-var minusp = new Uint32Array([
- 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252,
-]);
-
-function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
- var s, i, j, u;
- var x = new Uint32Array(17),
- r = new Uint32Array(17),
- h = new Uint32Array(17),
- c = new Uint32Array(17),
- g = new Uint32Array(17);
- for (j = 0; j < 17; j++) r[j] = h[j] = 0;
- for (j = 0; j < 16; j++) r[j] = k[j];
- r[3] &= 15;
- r[4] &= 252;
- r[7] &= 15;
- r[8] &= 252;
- r[11] &= 15;
- r[12] &= 252;
- r[15] &= 15;
-
- while (n > 0) {
- for (j = 0; j < 17; j++) c[j] = 0;
- for (j = 0; j < 16 && j < n; ++j) c[j] = m[mpos + j];
- c[j] = 1;
- mpos += j;
- n -= j;
- add1305(h, c);
- for (i = 0; i < 17; i++) {
- x[i] = 0;
- for (j = 0; j < 17; j++)
- x[i] =
- (x[i] + h[j] * (j <= i ? r[i - j] : (320 * r[i + 17 - j]) | 0)) |
- 0 |
- 0;
- }
- for (i = 0; i < 17; i++) h[i] = x[i];
- u = 0;
- for (j = 0; j < 16; j++) {
- u = (u + h[j]) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
- u = (u + h[16]) | 0;
- h[16] = u & 3;
- u = (5 * (u >>> 2)) | 0;
- for (j = 0; j < 16; j++) {
- u = (u + h[j]) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
- u = (u + h[16]) | 0;
- h[16] = u;
- }
-
- for (j = 0; j < 17; j++) g[j] = h[j];
- add1305(h, minusp);
- s = -(h[16] >>> 7) | 0;
- for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]);
-
- for (j = 0; j < 16; j++) c[j] = k[j + 16];
- c[16] = 0;
- add1305(h, c);
- for (j = 0; j < 16; j++) out[outpos + j] = h[j];
- return 0;
-}
-
-function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
- var x = new Uint8Array(16);
- crypto_onetimeauth(x, 0, m, mpos, n, k);
- return crypto_verify_16(h, hpos, x, 0);
-}
-
-function crypto_secretbox(c, m, d, n, k) {
- var i;
- if (d < 32) return -1;
- crypto_stream_xor(c, 0, m, 0, d, n, k);
- crypto_onetimeauth(c, 16, c, 32, d - 32, c);
- for (i = 0; i < 16; i++) c[i] = 0;
- return 0;
-}
-
-function crypto_secretbox_open(m, c, d, n, k) {
- var i;
- var x = new Uint8Array(32);
- if (d < 32) return -1;
- crypto_stream(x, 0, 32, n, k);
- if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1;
- crypto_stream_xor(m, 0, c, 0, d, n, k);
- for (i = 0; i < 32; i++) m[i] = 0;
- return 0;
-}
-
-function set25519(r, a) {
- var i;
- for (i = 0; i < 16; i++) r[i] = a[i] | 0;
-}
-
-function car25519(o) {
- var c;
- var i;
- for (i = 0; i < 16; i++) {
- o[i] += 65536;
- c = Math.floor(o[i] / 65536);
- o[(i + 1) * (i < 15 ? 1 : 0)] += c - 1 + 37 * (c - 1) * (i === 15 ? 1 : 0);
- o[i] -= c * 65536;
- }
-}
-
-function sel25519(p, q, b) {
- var t,
- c = ~(b - 1);
- for (var i = 0; i < 16; i++) {
- t = c & (p[i] ^ q[i]);
- p[i] ^= t;
- q[i] ^= t;
- }
-}
-
-function pack25519(o, n) {
- var i, j, b;
- var m = gf(),
- t = gf();
- for (i = 0; i < 16; i++) t[i] = n[i];
- car25519(t);
- car25519(t);
- car25519(t);
- for (j = 0; j < 2; j++) {
- m[0] = t[0] - 0xffed;
- for (i = 1; i < 15; i++) {
- m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
- m[i - 1] &= 0xffff;
- }
- m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
- b = (m[15] >> 16) & 1;
- m[14] &= 0xffff;
- sel25519(t, m, 1 - b);
- }
- for (i = 0; i < 16; i++) {
- o[2 * i] = t[i] & 0xff;
- o[2 * i + 1] = t[i] >> 8;
- }
-}
-
-function neq25519(a, b) {
- var c = new Uint8Array(32),
- d = new Uint8Array(32);
- pack25519(c, a);
- pack25519(d, b);
- return crypto_verify_32(c, 0, d, 0);
-}
-
-function par25519(a) {
- var d = new Uint8Array(32);
- pack25519(d, a);
- return d[0] & 1;
-}
-
-function unpack25519(o, n) {
- var i;
- for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8);
- o[15] &= 0x7fff;
-}
-
-function A(o, a, b) {
- var i;
- for (i = 0; i < 16; i++) o[i] = (a[i] + b[i]) | 0;
-}
-
-function Z(o, a, b) {
- var i;
- for (i = 0; i < 16; i++) o[i] = (a[i] - b[i]) | 0;
-}
-
-function M(o, a, b) {
- var i,
- j,
- t = new Float64Array(31);
- for (i = 0; i < 31; i++) t[i] = 0;
- for (i = 0; i < 16; i++) {
- for (j = 0; j < 16; j++) {
- t[i + j] += a[i] * b[j];
- }
- }
- for (i = 0; i < 15; i++) {
- t[i] += 38 * t[i + 16];
- }
- for (i = 0; i < 16; i++) o[i] = t[i];
- car25519(o);
- car25519(o);
-}
-
-function S(o, a) {
- M(o, a, a);
-}
-
-function inv25519(o, i) {
- var c = gf();
- var a;
- for (a = 0; a < 16; a++) c[a] = i[a];
- for (a = 253; a >= 0; a--) {
- S(c, c);
- if (a !== 2 && a !== 4) M(c, c, i);
- }
- for (a = 0; a < 16; a++) o[a] = c[a];
-}
-
-function pow2523(o, i) {
- var c = gf();
- var a;
- for (a = 0; a < 16; a++) c[a] = i[a];
- for (a = 250; a >= 0; a--) {
- S(c, c);
- if (a !== 1) M(c, c, i);
- }
- for (a = 0; a < 16; a++) o[a] = c[a];
-}
-
-function crypto_scalarmult(q, n, p) {
- var z = new Uint8Array(32);
- var x = new Float64Array(80),
- r,
- i;
- var a = gf(),
- b = gf(),
- c = gf(),
- d = gf(),
- e = gf(),
- f = gf();
- for (i = 0; i < 31; i++) z[i] = n[i];
- z[31] = (n[31] & 127) | 64;
- z[0] &= 248;
- unpack25519(x, p);
- for (i = 0; i < 16; i++) {
- b[i] = x[i];
- d[i] = a[i] = c[i] = 0;
- }
- a[0] = d[0] = 1;
- for (i = 254; i >= 0; --i) {
- r = (z[i >>> 3] >>> (i & 7)) & 1;
- sel25519(a, b, r);
- sel25519(c, d, r);
- A(e, a, c);
- Z(a, a, c);
- A(c, b, d);
- Z(b, b, d);
- S(d, e);
- S(f, a);
- M(a, c, a);
- M(c, b, e);
- A(e, a, c);
- Z(a, a, c);
- S(b, a);
- Z(c, d, f);
- M(a, c, _121665);
- A(a, a, d);
- M(c, c, a);
- M(a, d, f);
- M(d, b, x);
- S(b, e);
- sel25519(a, b, r);
- sel25519(c, d, r);
- }
- for (i = 0; i < 16; i++) {
- x[i + 16] = a[i];
- x[i + 32] = c[i];
- x[i + 48] = b[i];
- x[i + 64] = d[i];
- }
- var x32 = x.subarray(32);
- var x16 = x.subarray(16);
- inv25519(x32, x32);
- M(x16, x16, x32);
- pack25519(q, x16);
- return 0;
-}
-
-function crypto_scalarmult_base(q, n) {
- return crypto_scalarmult(q, n, _9);
-}
-
-function crypto_box_keypair(y, x) {
- randombytes(x, 32);
- return crypto_scalarmult_base(y, x);
-}
-
-function crypto_box_beforenm(k, y, x) {
- var s = new Uint8Array(32);
- crypto_scalarmult(s, x, y);
- return crypto_core_hsalsa20(k, _0, s, sigma);
-}
-
-var crypto_box_afternm = crypto_secretbox;
-var crypto_box_open_afternm = crypto_secretbox_open;
-
-function crypto_box(c, m, d, n, y, x) {
- var k = new Uint8Array(32);
- crypto_box_beforenm(k, y, x);
- return crypto_box_afternm(c, m, d, n, k);
-}
-
-function crypto_box_open(m, c, d, n, y, x) {
- var k = new Uint8Array(32);
- crypto_box_beforenm(k, y, x);
- return crypto_box_open_afternm(m, c, d, n, k);
-}
-
-function add64() {
- var a = 0,
- b = 0,
- c = 0,
- d = 0,
- m16 = 65535,
- l,
- h,
- i;
- for (i = 0; i < arguments.length; i++) {
- l = arguments[i].lo;
- h = arguments[i].hi;
- a += l & m16;
- b += l >>> 16;
- c += h & m16;
- d += h >>> 16;
- }
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- return new u64((c & m16) | (d << 16), (a & m16) | (b << 16));
-}
-
-function shr64(x, c) {
- return new u64(x.hi >>> c, (x.lo >>> c) | (x.hi << (32 - c)));
-}
-
-function xor64() {
- var l = 0,
- h = 0,
- i;
- for (i = 0; i < arguments.length; i++) {
- l ^= arguments[i].lo;
- h ^= arguments[i].hi;
- }
- return new u64(h, l);
-}
-
-function R(x, c) {
- var h,
- l,
- c1 = 32 - c;
- if (c < 32) {
- h = (x.hi >>> c) | (x.lo << c1);
- l = (x.lo >>> c) | (x.hi << c1);
- } else if (c < 64) {
- h = (x.lo >>> c) | (x.hi << c1);
- l = (x.hi >>> c) | (x.lo << c1);
- }
- return new u64(h, l);
-}
-
-function Ch(x, y, z) {
- var h = (x.hi & y.hi) ^ (~x.hi & z.hi),
- l = (x.lo & y.lo) ^ (~x.lo & z.lo);
- return new u64(h, l);
-}
-
-function Maj(x, y, z) {
- var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi),
- l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo);
- return new u64(h, l);
-}
-
-function Sigma0(x) {
- return xor64(R(x, 28), R(x, 34), R(x, 39));
-}
-function Sigma1(x) {
- return xor64(R(x, 14), R(x, 18), R(x, 41));
-}
-function sigma0(x) {
- return xor64(R(x, 1), R(x, 8), shr64(x, 7));
-}
-function sigma1(x) {
- return xor64(R(x, 19), R(x, 61), shr64(x, 6));
-}
-
-var K = [
- new u64(0x428a2f98, 0xd728ae22),
- new u64(0x71374491, 0x23ef65cd),
- new u64(0xb5c0fbcf, 0xec4d3b2f),
- new u64(0xe9b5dba5, 0x8189dbbc),
- new u64(0x3956c25b, 0xf348b538),
- new u64(0x59f111f1, 0xb605d019),
- new u64(0x923f82a4, 0xaf194f9b),
- new u64(0xab1c5ed5, 0xda6d8118),
- new u64(0xd807aa98, 0xa3030242),
- new u64(0x12835b01, 0x45706fbe),
- new u64(0x243185be, 0x4ee4b28c),
- new u64(0x550c7dc3, 0xd5ffb4e2),
- new u64(0x72be5d74, 0xf27b896f),
- new u64(0x80deb1fe, 0x3b1696b1),
- new u64(0x9bdc06a7, 0x25c71235),
- new u64(0xc19bf174, 0xcf692694),
- new u64(0xe49b69c1, 0x9ef14ad2),
- new u64(0xefbe4786, 0x384f25e3),
- new u64(0x0fc19dc6, 0x8b8cd5b5),
- new u64(0x240ca1cc, 0x77ac9c65),
- new u64(0x2de92c6f, 0x592b0275),
- new u64(0x4a7484aa, 0x6ea6e483),
- new u64(0x5cb0a9dc, 0xbd41fbd4),
- new u64(0x76f988da, 0x831153b5),
- new u64(0x983e5152, 0xee66dfab),
- new u64(0xa831c66d, 0x2db43210),
- new u64(0xb00327c8, 0x98fb213f),
- new u64(0xbf597fc7, 0xbeef0ee4),
- new u64(0xc6e00bf3, 0x3da88fc2),
- new u64(0xd5a79147, 0x930aa725),
- new u64(0x06ca6351, 0xe003826f),
- new u64(0x14292967, 0x0a0e6e70),
- new u64(0x27b70a85, 0x46d22ffc),
- new u64(0x2e1b2138, 0x5c26c926),
- new u64(0x4d2c6dfc, 0x5ac42aed),
- new u64(0x53380d13, 0x9d95b3df),
- new u64(0x650a7354, 0x8baf63de),
- new u64(0x766a0abb, 0x3c77b2a8),
- new u64(0x81c2c92e, 0x47edaee6),
- new u64(0x92722c85, 0x1482353b),
- new u64(0xa2bfe8a1, 0x4cf10364),
- new u64(0xa81a664b, 0xbc423001),
- new u64(0xc24b8b70, 0xd0f89791),
- new u64(0xc76c51a3, 0x0654be30),
- new u64(0xd192e819, 0xd6ef5218),
- new u64(0xd6990624, 0x5565a910),
- new u64(0xf40e3585, 0x5771202a),
- new u64(0x106aa070, 0x32bbd1b8),
- new u64(0x19a4c116, 0xb8d2d0c8),
- new u64(0x1e376c08, 0x5141ab53),
- new u64(0x2748774c, 0xdf8eeb99),
- new u64(0x34b0bcb5, 0xe19b48a8),
- new u64(0x391c0cb3, 0xc5c95a63),
- new u64(0x4ed8aa4a, 0xe3418acb),
- new u64(0x5b9cca4f, 0x7763e373),
- new u64(0x682e6ff3, 0xd6b2b8a3),
- new u64(0x748f82ee, 0x5defb2fc),
- new u64(0x78a5636f, 0x43172f60),
- new u64(0x84c87814, 0xa1f0ab72),
- new u64(0x8cc70208, 0x1a6439ec),
- new u64(0x90befffa, 0x23631e28),
- new u64(0xa4506ceb, 0xde82bde9),
- new u64(0xbef9a3f7, 0xb2c67915),
- new u64(0xc67178f2, 0xe372532b),
- new u64(0xca273ece, 0xea26619c),
- new u64(0xd186b8c7, 0x21c0c207),
- new u64(0xeada7dd6, 0xcde0eb1e),
- new u64(0xf57d4f7f, 0xee6ed178),
- new u64(0x06f067aa, 0x72176fba),
- new u64(0x0a637dc5, 0xa2c898a6),
- new u64(0x113f9804, 0xbef90dae),
- new u64(0x1b710b35, 0x131c471b),
- new u64(0x28db77f5, 0x23047d84),
- new u64(0x32caab7b, 0x40c72493),
- new u64(0x3c9ebe0a, 0x15c9bebc),
- new u64(0x431d67c4, 0x9c100d4c),
- new u64(0x4cc5d4be, 0xcb3e42b6),
- new u64(0x597f299c, 0xfc657e2a),
- new u64(0x5fcb6fab, 0x3ad6faec),
- new u64(0x6c44198c, 0x4a475817),
-];
-
-function crypto_hashblocks(x, m, n) {
- var z = [],
- b = [],
- a = [],
- w = [],
- t,
- i,
- j;
-
- for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8 * i);
-
- var pos = 0;
- while (n >= 128) {
- for (i = 0; i < 16; i++) w[i] = dl64(m, 8 * i + pos);
- for (i = 0; i < 80; i++) {
- for (j = 0; j < 8; j++) b[j] = a[j];
- t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i % 16]);
- b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2]));
- b[3] = add64(b[3], t);
- for (j = 0; j < 8; j++) a[(j + 1) % 8] = b[j];
- if (i % 16 === 15) {
- for (j = 0; j < 16; j++) {
- w[j] = add64(
- w[j],
- w[(j + 9) % 16],
- sigma0(w[(j + 1) % 16]),
- sigma1(w[(j + 14) % 16])
- );
- }
- }
- }
-
- for (i = 0; i < 8; i++) {
- a[i] = add64(a[i], z[i]);
- z[i] = a[i];
- }
-
- pos += 128;
- n -= 128;
- }
-
- for (i = 0; i < 8; i++) ts64(x, 8 * i, z[i]);
- return n;
-}
-
-var iv = new Uint8Array([
- 0x6a, 0x09, 0xe6, 0x67, 0xf3, 0xbc, 0xc9, 0x08, 0xbb, 0x67, 0xae, 0x85, 0x84,
- 0xca, 0xa7, 0x3b, 0x3c, 0x6e, 0xf3, 0x72, 0xfe, 0x94, 0xf8, 0x2b, 0xa5, 0x4f,
- 0xf5, 0x3a, 0x5f, 0x1d, 0x36, 0xf1, 0x51, 0x0e, 0x52, 0x7f, 0xad, 0xe6, 0x82,
- 0xd1, 0x9b, 0x05, 0x68, 0x8c, 0x2b, 0x3e, 0x6c, 0x1f, 0x1f, 0x83, 0xd9, 0xab,
- 0xfb, 0x41, 0xbd, 0x6b, 0x5b, 0xe0, 0xcd, 0x19, 0x13, 0x7e, 0x21, 0x79,
-]);
-
-function crypto_hash(out, m, n) {
- var h = new Uint8Array(64),
- x = new Uint8Array(256);
- var i,
- b = n;
-
- for (i = 0; i < 64; i++) h[i] = iv[i];
-
- crypto_hashblocks(h, m, n);
- n %= 128;
-
- for (i = 0; i < 256; i++) x[i] = 0;
- for (i = 0; i < n; i++) x[i] = m[b - n + i];
- x[n] = 128;
-
- n = 256 - 128 * (n < 112 ? 1 : 0);
- x[n - 9] = 0;
- ts64(x, n - 8, new u64((b / 0x20000000) | 0, b << 3));
- crypto_hashblocks(h, x, n);
-
- for (i = 0; i < 64; i++) out[i] = h[i];
-
- return 0;
-}
-
-function add(p, q) {
- var a = gf(),
- b = gf(),
- c = gf(),
- d = gf(),
- e = gf(),
- f = gf(),
- g = gf(),
- h = gf(),
- t = gf();
-
- Z(a, p[1], p[0]);
- Z(t, q[1], q[0]);
- M(a, a, t);
- A(b, p[0], p[1]);
- A(t, q[0], q[1]);
- M(b, b, t);
- M(c, p[3], q[3]);
- M(c, c, D2);
- M(d, p[2], q[2]);
- A(d, d, d);
- Z(e, b, a);
- Z(f, d, c);
- A(g, d, c);
- A(h, b, a);
-
- M(p[0], e, f);
- M(p[1], h, g);
- M(p[2], g, f);
- M(p[3], e, h);
-}
-
-function cswap(p, q, b) {
- var i;
- for (i = 0; i < 4; i++) {
- sel25519(p[i], q[i], b);
- }
-}
-
-function pack(r, p) {
- var tx = gf(),
- ty = gf(),
- zi = gf();
- inv25519(zi, p[2]);
- M(tx, p[0], zi);
- M(ty, p[1], zi);
- pack25519(r, ty);
- r[31] ^= par25519(tx) << 7;
-}
-
-function scalarmult(p, q, s) {
- var b, i;
- set25519(p[0], gf0);
- set25519(p[1], gf1);
- set25519(p[2], gf1);
- set25519(p[3], gf0);
- for (i = 255; i >= 0; --i) {
- b = (s[(i / 8) | 0] >> (i & 7)) & 1;
- cswap(p, q, b);
- add(q, p);
- add(p, p);
- cswap(p, q, b);
- }
-}
-
-function scalarbase(p, s) {
- var q = [gf(), gf(), gf(), gf()];
- set25519(q[0], X);
- set25519(q[1], Y);
- set25519(q[2], gf1);
- M(q[3], X, Y);
- scalarmult(p, q, s);
-}
-
-function crypto_sign_keypair(pk, sk, seeded) {
- var d = new Uint8Array(64);
- var p = [gf(), gf(), gf(), gf()];
- var i;
-
- if (!seeded) randombytes(sk, 32);
- crypto_hash(d, sk, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- scalarbase(p, d);
- pack(pk, p);
-
- for (i = 0; i < 32; i++) sk[i + 32] = pk[i];
- return 0;
-}
-
-var L = new Float64Array([
- 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde,
- 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
-]);
-
-function modL(r, x) {
- var carry, i, j, k;
- for (i = 63; i >= 32; --i) {
- carry = 0;
- for (j = i - 32, k = i - 12; j < k; ++j) {
- x[j] += carry - 16 * x[i] * L[j - (i - 32)];
- carry = Math.floor((x[j] + 128) / 256);
- x[j] -= carry * 256;
- }
- x[j] += carry;
- x[i] = 0;
- }
- carry = 0;
- for (j = 0; j < 32; j++) {
- x[j] += carry - (x[31] >> 4) * L[j];
- carry = x[j] >> 8;
- x[j] &= 255;
- }
- for (j = 0; j < 32; j++) x[j] -= carry * L[j];
- for (i = 0; i < 32; i++) {
- x[i + 1] += x[i] >> 8;
- r[i] = x[i] & 255;
- }
-}
-
-function reduce(r) {
- var x = new Float64Array(64),
- i;
- for (i = 0; i < 64; i++) x[i] = r[i];
- for (i = 0; i < 64; i++) r[i] = 0;
- modL(r, x);
-}
-
-// Note: difference from C - smlen returned, not passed as argument.
-function crypto_sign(sm, m, n, sk) {
- var d = new Uint8Array(64),
- h = new Uint8Array(64),
- r = new Uint8Array(64);
- var i,
- j,
- x = new Float64Array(64);
- var p = [gf(), gf(), gf(), gf()];
-
- crypto_hash(d, sk, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- var smlen = n + 64;
- for (i = 0; i < n; i++) sm[64 + i] = m[i];
- for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
-
- crypto_hash(r, sm.subarray(32), n + 32);
- reduce(r);
- scalarbase(p, r);
- pack(sm, p);
-
- for (i = 32; i < 64; i++) sm[i] = sk[i];
- crypto_hash(h, sm, n + 64);
- reduce(h);
-
- for (i = 0; i < 64; i++) x[i] = 0;
- for (i = 0; i < 32; i++) x[i] = r[i];
- for (i = 0; i < 32; i++) {
- for (j = 0; j < 32; j++) {
- x[i + j] += h[i] * d[j];
- }
- }
-
- modL(sm.subarray(32), x);
- return smlen;
-}
-
-function unpackneg(r, p) {
- var t = gf(),
- chk = gf(),
- num = gf(),
- den = gf(),
- den2 = gf(),
- den4 = gf(),
- den6 = gf();
-
- set25519(r[2], gf1);
- unpack25519(r[1], p);
- S(num, r[1]);
- M(den, num, D);
- Z(num, num, r[2]);
- A(den, r[2], den);
-
- S(den2, den);
- S(den4, den2);
- M(den6, den4, den2);
- M(t, den6, num);
- M(t, t, den);
-
- pow2523(t, t);
- M(t, t, num);
- M(t, t, den);
- M(t, t, den);
- M(r[0], t, den);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)) M(r[0], r[0], I);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)) return -1;
-
- if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]);
-
- M(r[3], r[0], r[1]);
- return 0;
-}
-
-function crypto_sign_open(m, sm, n, pk) {
- var i;
- var t = new Uint8Array(32),
- h = new Uint8Array(64);
- var p = [gf(), gf(), gf(), gf()],
- q = [gf(), gf(), gf(), gf()];
-
- if (n < 64) return -1;
-
- if (unpackneg(q, pk)) return -1;
-
- for (i = 0; i < n; i++) m[i] = sm[i];
- for (i = 0; i < 32; i++) m[i + 32] = pk[i];
- crypto_hash(h, m, n);
- reduce(h);
- scalarmult(p, q, h);
-
- scalarbase(q, sm.subarray(32));
- add(p, q);
- pack(t, p);
-
- n -= 64;
- if (crypto_verify_32(sm, 0, t, 0)) {
- for (i = 0; i < n; i++) m[i] = 0;
- return -1;
- }
-
- for (i = 0; i < n; i++) m[i] = sm[i + 64];
- return n;
-}
-
-var crypto_secretbox_KEYBYTES = 32,
- crypto_secretbox_NONCEBYTES = 24,
- crypto_secretbox_ZEROBYTES = 32,
- crypto_secretbox_BOXZEROBYTES = 16,
- crypto_scalarmult_BYTES = 32,
- crypto_scalarmult_SCALARBYTES = 32,
- crypto_box_PUBLICKEYBYTES = 32,
- crypto_box_SECRETKEYBYTES = 32,
- crypto_box_BEFORENMBYTES = 32,
- crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
- crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
- crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
- crypto_sign_BYTES = 64,
- crypto_sign_PUBLICKEYBYTES = 32,
- crypto_sign_SECRETKEYBYTES = 64,
- crypto_sign_SEEDBYTES = 32,
- crypto_hash_BYTES = 64;
-
-var _nacl = {
- lowlevel: {},
-};
-
-_nacl.lowlevel = {
- crypto_core_hsalsa20: crypto_core_hsalsa20,
- crypto_stream_xor: crypto_stream_xor,
- crypto_stream: crypto_stream,
- crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
- crypto_stream_salsa20: crypto_stream_salsa20,
- crypto_onetimeauth: crypto_onetimeauth,
- crypto_onetimeauth_verify: crypto_onetimeauth_verify,
- crypto_verify_16: crypto_verify_16,
- crypto_verify_32: crypto_verify_32,
- crypto_secretbox: crypto_secretbox,
- crypto_secretbox_open: crypto_secretbox_open,
- crypto_scalarmult: crypto_scalarmult,
- crypto_scalarmult_base: crypto_scalarmult_base,
- crypto_box_beforenm: crypto_box_beforenm,
- crypto_box_afternm: crypto_box_afternm,
- crypto_box: crypto_box,
- crypto_box_open: crypto_box_open,
- crypto_box_keypair: crypto_box_keypair,
- crypto_hash: crypto_hash,
- crypto_sign: crypto_sign,
- crypto_sign_keypair: crypto_sign_keypair,
- crypto_sign_open: crypto_sign_open,
-
- crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
- crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
- crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
- crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
- crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
- crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
- crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
- crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
- crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
- crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
- crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
- crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
- crypto_sign_BYTES: crypto_sign_BYTES,
- crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
- crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
- crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
- crypto_hash_BYTES: crypto_hash_BYTES,
-
- gf: gf,
- D: D,
- L: L,
- pack25519: pack25519,
- unpack25519: unpack25519,
- M: M,
- A: A,
- S: S,
- Z: Z,
- pow2523: pow2523,
- add: add,
- set25519: set25519,
- modL: modL,
- scalarmult: scalarmult,
- scalarbase: scalarbase,
-};
-
-/* High-level API */
-
-function checkLengths(k, n) {
- if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
- if (n.length !== crypto_secretbox_NONCEBYTES)
- throw new Error('bad nonce size');
-}
-
-function checkBoxLengths(pk, sk) {
- if (pk.length !== crypto_box_PUBLICKEYBYTES)
- throw new Error('bad public key size');
- if (sk.length !== crypto_box_SECRETKEYBYTES)
- throw new Error('bad secret key size');
-}
-
-function checkArrayTypes() {
- for (var i = 0; i < arguments.length; i++) {
- if (!(arguments[i] instanceof Uint8Array))
- throw new TypeError('unexpected type, use Uint8Array');
- }
-}
-
-function cleanup(arr) {
- for (var i = 0; i < arr.length; i++) arr[i] = 0;
-}
-
-_nacl.randomBytes = function (n) {
- var b = new Uint8Array(n);
- randombytes(b, n);
- return b;
-};
-
-_nacl.secretbox = function (msg, nonce, key) {
- checkArrayTypes(msg, nonce, key);
- checkLengths(key, nonce);
- var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
- var c = new Uint8Array(m.length);
- for (var i = 0; i < msg.length; i++)
- m[i + crypto_secretbox_ZEROBYTES] = msg[i];
- crypto_secretbox(c, m, m.length, nonce, key);
- return c.subarray(crypto_secretbox_BOXZEROBYTES);
-};
-
-_nacl.secretbox.open = function (box, nonce, key) {
- checkArrayTypes(box, nonce, key);
- checkLengths(key, nonce);
- var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
- var m = new Uint8Array(c.length);
- for (var i = 0; i < box.length; i++)
- c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
- if (c.length < 32) return null;
- if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
- return m.subarray(crypto_secretbox_ZEROBYTES);
-};
-
-_nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
-_nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
-_nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
-
-_nacl.scalarMult = function (n, p) {
- checkArrayTypes(n, p);
- if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
- if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
- var q = new Uint8Array(crypto_scalarmult_BYTES);
- crypto_scalarmult(q, n, p);
- return q;
-};
-
-_nacl.scalarMult.base = function (n) {
- checkArrayTypes(n);
- if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
- var q = new Uint8Array(crypto_scalarmult_BYTES);
- crypto_scalarmult_base(q, n);
- return q;
-};
-
-_nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
-_nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
-
-_nacl.box = function (msg, nonce, publicKey, secretKey) {
- var k = _nacl.box.before(publicKey, secretKey);
- return _nacl.secretbox(msg, nonce, k);
-};
-
-_nacl.box.before = function (publicKey, secretKey) {
- checkArrayTypes(publicKey, secretKey);
- checkBoxLengths(publicKey, secretKey);
- var k = new Uint8Array(crypto_box_BEFORENMBYTES);
- crypto_box_beforenm(k, publicKey, secretKey);
- return k;
-};
-
-_nacl.box.after = _nacl.secretbox;
-
-_nacl.box.open = function (msg, nonce, publicKey, secretKey) {
- var k = _nacl.box.before(publicKey, secretKey);
- return _nacl.secretbox.open(msg, nonce, k);
-};
-
-_nacl.box.open.after = _nacl.secretbox.open;
-
-_nacl.box.keyPair = function () {
- var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
- var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
- crypto_box_keypair(pk, sk);
- return { publicKey: pk, secretKey: sk };
-};
-
-_nacl.box.keyPair.fromSecretKey = function (secretKey) {
- checkArrayTypes(secretKey);
- if (secretKey.length !== crypto_box_SECRETKEYBYTES)
- throw new Error('bad secret key size');
- var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
- crypto_scalarmult_base(pk, secretKey);
- return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
-};
-
-_nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
-_nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
-_nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
-_nacl.box.nonceLength = crypto_box_NONCEBYTES;
-_nacl.box.overheadLength = _nacl.secretbox.overheadLength;
-
-_nacl.sign = function (msg, secretKey) {
- checkArrayTypes(msg, secretKey);
- if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
- throw new Error('bad secret key size');
- var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
- crypto_sign(signedMsg, msg, msg.length, secretKey);
- return signedMsg;
-};
-
-_nacl.sign.open = function (signedMsg, publicKey) {
- checkArrayTypes(signedMsg, publicKey);
- if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
- throw new Error('bad public key size');
- var tmp = new Uint8Array(signedMsg.length);
- var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
- if (mlen < 0) return null;
- var m = new Uint8Array(mlen);
- for (var i = 0; i < m.length; i++) m[i] = tmp[i];
- return m;
-};
-
-_nacl.sign.detached = function (msg, secretKey) {
- var signedMsg = _nacl.sign(msg, secretKey);
- var sig = new Uint8Array(crypto_sign_BYTES);
- for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
- return sig;
-};
-
-_nacl.sign.detached.verify = function (msg, sig, publicKey) {
- checkArrayTypes(msg, sig, publicKey);
- if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size');
- if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
- throw new Error('bad public key size');
- var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
- var m = new Uint8Array(crypto_sign_BYTES + msg.length);
- var i;
- for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
- for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i];
- return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
-};
-
-_nacl.sign.keyPair = function () {
- var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
- crypto_sign_keypair(pk, sk);
- return { publicKey: pk, secretKey: sk };
-};
-
-_nacl.sign.keyPair.fromSecretKey = function (secretKey) {
- checkArrayTypes(secretKey);
- if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
- throw new Error('bad secret key size');
- var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i];
- return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
-};
-
-_nacl.sign.keyPair.fromSeed = function (seed) {
- checkArrayTypes(seed);
- if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size');
- var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
- var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
- for (var i = 0; i < 32; i++) sk[i] = seed[i];
- crypto_sign_keypair(pk, sk, true);
- return { publicKey: pk, secretKey: sk };
-};
-
-_nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
-_nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
-_nacl.sign.seedLength = crypto_sign_SEEDBYTES;
-_nacl.sign.signatureLength = crypto_sign_BYTES;
-
-_nacl.hash = function (msg) {
- checkArrayTypes(msg);
- var h = new Uint8Array(crypto_hash_BYTES);
- crypto_hash(h, msg, msg.length);
- return h;
-};
-
-_nacl.hash.hashLength = crypto_hash_BYTES;
-
-_nacl.verify = function (x, y) {
- checkArrayTypes(x, y);
- // Zero length arguments are considered not equal.
- if (x.length === 0 || y.length === 0) return false;
- if (x.length !== y.length) return false;
- return vn(x, 0, y, 0, x.length) === 0 ? true : false;
-};
-
-_nacl.setPRNG = function (fn) {
- randombytes = fn;
-};
-
-(function () {
- // Initialize PRNG if environment provides CSPRNG.
- // If not, methods calling randombytes will throw.
- var crypto =
- typeof self !== 'undefined' ? self.crypto || self.msCrypto : null;
- if (crypto && crypto.getRandomValues) {
- // Browsers.
- var QUOTA = 65536;
- _nacl.setPRNG(function (x, n) {
- var i,
- v = new Uint8Array(n);
- for (i = 0; i < n; i += QUOTA) {
- crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
- }
- for (i = 0; i < n; i++) x[i] = v[i];
- cleanup(v);
- });
- } else if (typeof require !== 'undefined') {
- crypto = require('crypto');
- if (crypto && crypto.randomBytes) {
- _nacl.setPRNG(function (x, n) {
- var i,
- v = crypto.randomBytes(n);
- for (i = 0; i < n; i++) x[i] = v[i];
- cleanup(v);
- });
- }
- }
-})();
-
-export const nacl = _nacl.default || _nacl;
diff --git a/packages/nacl/tsconfig.json b/packages/nacl/tsconfig.json
deleted file mode 100644
index d87cb2e661..0000000000
--- a/packages/nacl/tsconfig.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "module": "commonjs",
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitOverride": true,
- "noPropertyAccessFromIndexSignature": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true,
- "allowJs": true
- },
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.lib.json"
- },
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/packages/nacl/tsconfig.lib.json b/packages/nacl/tsconfig.lib.json
deleted file mode 100644
index 4d4d2492f1..0000000000
--- a/packages/nacl/tsconfig.lib.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "declaration": true,
- "types": []
- },
- "include": ["**/*.ts", "src/lib/nacl.js"],
- "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
-}
diff --git a/packages/nacl/tsconfig.spec.json b/packages/nacl/tsconfig.spec.json
deleted file mode 100644
index 546f12877f..0000000000
--- a/packages/nacl/tsconfig.spec.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "module": "commonjs",
- "types": ["jest", "node"]
- },
- "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
-}
diff --git a/packages/pkp-base/src/lib/pkp-base.ts b/packages/pkp-base/src/lib/pkp-base.ts
index 3f7ff3feb0..912950464b 100644
--- a/packages/pkp-base/src/lib/pkp-base.ts
+++ b/packages/pkp-base/src/lib/pkp-base.ts
@@ -12,8 +12,9 @@ import {
LitNodeClientNotReadyError,
UnknownError,
} from '@lit-protocol/constants';
+import { publicKeyCompress } from '@lit-protocol/crypto';
import { LitNodeClient } from '@lit-protocol/lit-node-client';
-import { publicKeyConvert } from '@lit-protocol/misc';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import {
AuthenticationContext,
JsonExecutionSdkParams,
@@ -23,29 +24,11 @@ import {
RPCUrls,
} from '@lit-protocol/types';
-/**
- * Compresses a given public key.
- * @param {string} pubKey - The public key to be compressed.
- * @returns {string} - The compressed public key.
- */
-const compressPubKey = (pubKey: string): string => {
- const testBuffer = Buffer.from(pubKey, 'hex');
- if (testBuffer.length === 64) {
- pubKey = '04' + pubKey;
- }
-
- // const hex = Buffer.from(pubKey, 'hex');
- const uint8array = Buffer.from(pubKey, 'hex');
- const compressedKey = publicKeyConvert(uint8array, true);
- const hex = Buffer.from(compressedKey).toString('hex');
-
- return hex;
-};
-
/**
* A base class that can be shared between Ethers and Cosmos signers.
*/
export class PKPBase {
+ private readonly _logger: Logger;
rpcs?: RPCUrls;
authContext: AuthenticationContext;
@@ -62,11 +45,6 @@ export class PKPBase {
debug: boolean;
useAction: boolean | undefined;
- // -- debug things
- private PREFIX = '[PKPBase]';
- private orange = '\x1b[33m';
- private reset = '\x1b[0m';
-
get litNodeClientReady(): boolean {
return this.litNodeClient.ready;
}
@@ -77,6 +55,10 @@ export class PKPBase {
const prop = { ...pkpBaseProp }; // Avoid modifications to the received object
this.debug = prop.debug || false;
+ this._logger = getChildLogger({
+ module: 'PKPBase',
+ ...(prop.debug ? { level: 'debug' } : {}),
+ });
if (prop.pkpPubKey.startsWith('0x')) {
prop.pkpPubKey = prop.pkpPubKey.slice(2);
@@ -87,7 +69,7 @@ export class PKPBase {
this.rpcs = prop.rpcs;
- console.log('authContext:', prop.authContext);
+ this._logger.info({ msg: 'authContext', authContext: prop.authContext });
this.authContext = prop.authContext;
this.validateAuthContext();
@@ -131,6 +113,25 @@ export class PKPBase {
}
}
+ /**
+ * Compresses a given public key.
+ * @param {string} pubKey - The public key to be compressed.
+ * @returns {string} - The compressed public key.
+ */
+ private compressPubKey(pubKey: string): string {
+ const testBuffer = Buffer.from(pubKey, 'hex');
+ if (testBuffer.length === 64) {
+ pubKey = '04' + pubKey;
+ }
+
+ // const hex = Buffer.from(pubKey, 'hex');
+ const uint8array = Buffer.from(pubKey, 'hex');
+ const compressedKey = publicKeyCompress(uint8array);
+ const hex = Buffer.from(compressedKey).toString('hex');
+
+ return hex;
+ }
+
/**
* Sets the compressed public key and its buffer representation.
*
@@ -138,7 +139,7 @@ export class PKPBase {
*/
private setCompressedPubKeyAndBuffer(prop: PKPBaseProp): void | never {
try {
- this.compressedPubKey = compressPubKey(prop.pkpPubKey);
+ this.compressedPubKey = this.compressPubKey(prop.pkpPubKey);
this.compressedPubKeyBuffer = Buffer.from(this.compressedPubKey, 'hex');
} catch (e) {
throw new UnknownError(
@@ -178,7 +179,7 @@ export class PKPBase {
}
if (!pkpBaseProp.litActionCode && !pkpBaseProp.litActionIPFS) {
- this.log(
+ this._logger.debug(
'No lit action code or IPFS hash provided. Using default action.'
);
this.useAction = false;
@@ -205,7 +206,7 @@ export class PKPBase {
async init(): Promise {
try {
await this.litNodeClient.connect();
- this.log('Connected to Lit Node');
+ this._logger.debug('Connected to Lit Node');
} catch (e) {
throw new LitNodeClientNotReadyError(
{
@@ -310,14 +311,14 @@ export class PKPBase {
);
}
- this.log('executeJsArgs:', executeJsArgs);
+ this._logger.debug({ msg: 'executeJsArgs', executeJsArgs });
const res = await this.litNodeClient.executeJs(executeJsArgs);
const sig = res.signatures[sigName];
- this.log('res:', res);
- this.log('res.signatures[sigName]:', sig);
+ this._logger.debug({ msg: 'res', res });
+ this._logger.debug({ msg: 'res.signatures[sigName]', sig });
if (sig.r && sig.s) {
// pad sigs with 0 if length is odd
@@ -350,26 +351,21 @@ export class PKPBase {
this.validateAuthContext();
- try {
- const sig = await this.litNodeClient.pkpSign({
- toSign,
- pubKey: this.uncompressedPubKey,
- authContext: this.authContext,
- });
+ const sig = await this.litNodeClient.pkpSign({
+ toSign,
+ pubKey: this.uncompressedPubKey,
+ authContext: this.authContext,
+ });
- if (!sig) {
- throw new UnknownError({}, 'No signature returned');
- }
+ if (!sig) {
+ throw new UnknownError({}, 'No signature returned');
+ }
- // pad sigs with 0 if length is odd
- sig.r = sig.r.length % 2 === 0 ? sig.r : '0' + sig.r;
- sig.s = sig.s.length % 2 === 0 ? sig.s : '0' + sig.s;
+ // pad sigs with 0 if length is odd
+ sig.r = sig.r.length % 2 === 0 ? sig.r : '0' + sig.r;
+ sig.s = sig.s.length % 2 === 0 ? sig.s : '0' + sig.s;
- return sig;
- } catch (e) {
- console.log('err: ', e);
- throw e;
- }
+ return sig;
}
/**
@@ -383,18 +379,4 @@ export class PKPBase {
await this.init();
}
}
-
- /**
- * Logs the provided arguments to the console, but only if debugging is enabled.
- *
- * @param {...any[]} args - The values to be logged to the console.
- *
- * @returns {void} - This function does not return a value.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- log(...args: any[]): void {
- if (this.debug) {
- console.log(this.orange + this.PREFIX + this.reset, ...args);
- }
- }
}
diff --git a/packages/pkp-cosmos/src/lib/pkp-cosmos.ts b/packages/pkp-cosmos/src/lib/pkp-cosmos.ts
index 3438ce657b..e1c73cc956 100644
--- a/packages/pkp-cosmos/src/lib/pkp-cosmos.ts
+++ b/packages/pkp-cosmos/src/lib/pkp-cosmos.ts
@@ -37,6 +37,7 @@ import {
InvalidArgumentException,
RemovedFunctionError,
} from '@lit-protocol/constants';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import { PKPBase } from '@lit-protocol/pkp-base';
import {
PKPClientHelpers,
@@ -56,6 +57,7 @@ const DEFAULT_COSMOS_RPC_URL =
export class PKPCosmosWallet
implements PKPWallet, OfflineDirectSigner, PKPClientHelpers
{
+ private readonly _logger: Logger;
private readonly pkpBase: PKPBase;
// Address prefix for Bech32 addresses
@@ -73,6 +75,10 @@ export class PKPCosmosWallet
constructor(prop: PKPCosmosWalletProp) {
this.pkpBase = PKPBase.createInstance(prop);
+ this._logger = getChildLogger({
+ module: 'PKPCosmosWallet',
+ ...(prop.debug ? { level: 'debug' } : {}),
+ });
// Set the address prefix and RPC URL based on the provided properties
this.addressPrefix = prop.addressPrefix ?? 'cosmos';
@@ -204,7 +210,7 @@ export class PKPCosmosWallet
);
// Log the encoded signature.
- this.pkpBase.log('stdSignature:', stdSignature);
+ this._logger.debug({ msg: 'stdSignature', stdSignature });
// Return the signed transaction and encoded signature.
return {
diff --git a/packages/pkp-ethers/src/lib/pkp-ethers.ts b/packages/pkp-ethers/src/lib/pkp-ethers.ts
index 179ec04e6a..3cea06141c 100644
--- a/packages/pkp-ethers/src/lib/pkp-ethers.ts
+++ b/packages/pkp-ethers/src/lib/pkp-ethers.ts
@@ -24,7 +24,6 @@ import {
ProgressCallback,
} from '@ethersproject/json-wallets';
import { keccak256 } from '@ethersproject/keccak256';
-import { Logger } from '@ethersproject/logger';
import { defineReadOnly, resolveProperties } from '@ethersproject/properties';
import { randomBytes } from '@ethersproject/random';
import {
@@ -33,10 +32,11 @@ import {
UnsignedTransaction,
} from '@ethersproject/transactions';
import { Wordlist } from '@ethersproject/wordlists';
-import { ethers, version, Wallet } from 'ethers';
+import { ethers, Wallet } from 'ethers';
import {
InitError,
+ InvalidArgumentException,
RPC_URL_BY_NETWORK,
InvalidParamType,
UnknownError,
@@ -44,6 +44,7 @@ import {
UnsupportedChainException,
LIT_CHAINS,
} from '@lit-protocol/constants';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import { PKPBase } from '@lit-protocol/pkp-base';
import {
PKPClientHelpers,
@@ -60,8 +61,6 @@ import {
ETHTxRes,
} from './pkp-ethers-types';
-const logger = new Logger(version);
-
export class PKPEthersWallet
implements
PKPWallet,
@@ -70,6 +69,7 @@ export class PKPEthersWallet
TypedDataSigner,
PKPClientHelpers
{
+ private readonly _logger: Logger;
private readonly pkpBase: PKPBase;
readonly address!: string;
@@ -90,6 +90,10 @@ export class PKPEthersWallet
constructor(prop: PKPEthersWalletProp) {
this.pkpBase = PKPBase.createInstance(prop);
+ this._logger = getChildLogger({
+ module: 'PKPEthersWallet',
+ ...(prop.debug ? { level: 'debug' } : {}),
+ });
const rpcUrl =
prop.rpc || RPC_URL_BY_NETWORK[prop.litNodeClient.config.litNetwork];
@@ -198,13 +202,13 @@ export class PKPEthersWallet
}
async signTransaction(transaction: TransactionRequest): Promise {
- this.pkpBase.log('signTransaction => transaction:', transaction);
+ this._logger.debug({ msg: 'signTransaction => transaction', transaction });
// Check if the LIT node client is connected, and connect if it's not.
await this.pkpBase.ensureLitNodeClientReady();
const addr = await this.getAddress();
- this.pkpBase.log('signTransaction => addr:', addr);
+ this._logger.debug({ msg: 'signTransaction => addr', addr });
// if manual settings are set, use them
if (this.manualGasPrice) {
@@ -226,40 +230,57 @@ export class PKPEthersWallet
try {
if (!transaction['gasLimit']) {
transaction.gasLimit = await this.rpcProvider.estimateGas(transaction);
- this.pkpBase.log('signTransaction => gasLimit:', transaction.gasLimit);
+ this._logger.debug({
+ msg: 'signTransaction => gasLimit',
+ gasLimit: transaction.gasLimit,
+ });
}
if (!transaction['nonce']) {
transaction.nonce = await this.rpcProvider.getTransactionCount(addr);
- this.pkpBase.log('signTransaction => nonce:', transaction.nonce);
+ this._logger.debug({
+ msg: 'signTransaction => nonce',
+ nonce: transaction.nonce,
+ });
}
if (!transaction['chainId']) {
transaction.chainId = (await this.rpcProvider.getNetwork()).chainId;
- this.pkpBase.log('signTransaction => chainId:', transaction.chainId);
+ this._logger.debug({
+ msg: 'signTransaction => chainId',
+ chainId: transaction.chainId,
+ });
}
if (!transaction['gasPrice']) {
transaction.gasPrice = await this.getGasPrice();
- this.pkpBase.log('signTransaction => gasPrice:', transaction.gasPrice);
+ this._logger.debug({
+ msg: 'signTransaction => gasPrice',
+ gasPrice: transaction.gasPrice,
+ });
}
} catch (err) {
- this.pkpBase.log(
- 'signTransaction => unable to populate transaction with details:',
- err
- );
+ this._logger.debug({
+ msg: 'signTransaction => unable to populate transaction with details',
+ err,
+ });
}
return resolveProperties(transaction).then(async (tx) => {
- this.pkpBase.log('tx.from:', tx.from);
- this.pkpBase.log('this.address:', this.address);
+ this._logger.debug({ msg: 'tx.from', from: tx.from });
+ this._logger.debug({ msg: 'this.address', address: this.address });
- if (tx.from != null) {
+ if (tx.from) {
if (getAddress(tx.from) !== this.address) {
- logger.throwArgumentError(
- 'transaction from address mismatch',
- 'transaction.from',
- transaction.from
+ throw new InvalidArgumentException(
+ {
+ info: {
+ transaction,
+ tx,
+ address: this.address,
+ },
+ },
+ 'transaction from address mismatch'
);
}
delete tx.from;
@@ -273,11 +294,11 @@ export class PKPEthersWallet
let signature;
if (this.pkpBase.useAction) {
- this.pkpBase.log('running lit action => sigName: pkp-eth-sign-tx');
+ this._logger.debug('running lit action => sigName: pkp-eth-sign-tx');
signature = (await this.pkpBase.runLitAction(toSign, 'pkp-eth-sign-tx'))
.signature;
} else {
- this.pkpBase.log('requesting signature from nodes');
+ this._logger.debug('requesting signature from nodes');
signature = (await this.pkpBase.runSign(toSign)).signature;
}
@@ -295,10 +316,10 @@ export class PKPEthersWallet
const toSign = arrayify(hashMessage(message));
let signature;
if (this.pkpBase.useAction) {
- this.pkpBase.log('running lit action => sigName: pkp-eth-sign-message');
+ this._logger.debug('running lit action => sigName: pkp-eth-sign-message');
signature = await this.runLitAction(toSign, 'pkp-eth-sign-message');
} else {
- this.pkpBase.log('requesting signature from nodes');
+ this._logger.debug('requesting signature from nodes');
signature = await this.runSign(toSign);
}
@@ -352,10 +373,10 @@ export class PKPEthersWallet
let signature;
if (this.pkpBase.useAction) {
- this.pkpBase.log('running lit action => sigName: pkp-eth-sign-message');
+ this._logger.debug('running lit action => sigName: pkp-eth-sign-message');
signature = await this.runLitAction(toSignBuffer, 'pkp-eth-sign-message');
} else {
- this.pkpBase.log('requesting signature from nodes');
+ this._logger.debug('requesting signature from nodes');
signature = await this.runSign(toSignBuffer);
}
@@ -401,7 +422,7 @@ export class PKPEthersWallet
async sendTransaction(transaction: TransactionRequest | any): Promise {
// : Promise
- this.pkpBase.log('sendTransaction => transaction:', transaction);
+ this._logger.debug({ msg: 'sendTransaction => transaction', transaction });
let res;
let signedTxn;
@@ -557,7 +578,7 @@ export class PKPEthersWallet
}
_checkProvider(): void {
- this.pkpBase.log(
+ this._logger.debug(
'This function is not implemented yet, but will skip it for now.'
);
}
diff --git a/packages/pkp-sui/src/lib/pkp-sui.ts b/packages/pkp-sui/src/lib/pkp-sui.ts
index 776187b29d..7f57a1aee5 100644
--- a/packages/pkp-sui/src/lib/pkp-sui.ts
+++ b/packages/pkp-sui/src/lib/pkp-sui.ts
@@ -30,12 +30,12 @@ import { secp256k1 } from '@noble/curves/secp256k1';
import { blake2b } from '@noble/hashes/blake2b';
import { sha256 } from '@noble/hashes/sha256';
-import { PKPBase } from '@lit-protocol/pkp-base';
-import { PKPBaseProp, PKPWallet, SigResponse } from '@lit-protocol/types';
import {
InvalidArgumentException,
UnknownError,
} from '@lit-protocol/constants';
+import { PKPBase } from '@lit-protocol/pkp-base';
+import { PKPBaseProp, PKPWallet, SigResponse } from '@lit-protocol/types';
import { getDigestFromBytes } from './TransactionBlockData';
diff --git a/packages/pkp-walletconnect/src/lib/pkp-walletconnect.ts b/packages/pkp-walletconnect/src/lib/pkp-walletconnect.ts
index f3e703e6cc..ce433be0bc 100644
--- a/packages/pkp-walletconnect/src/lib/pkp-walletconnect.ts
+++ b/packages/pkp-walletconnect/src/lib/pkp-walletconnect.ts
@@ -29,6 +29,7 @@ import {
ParamsMissingError,
UnsupportedMethodError,
} from '@lit-protocol/constants';
+import { Logger, getChildLogger } from '@lit-protocol/logger';
import {
PKPEthersWallet,
SupportedETHSigningMethods,
@@ -46,19 +47,19 @@ export interface InitWalletConnectParams
}
export class PKPWalletConnect {
+ private readonly debug: boolean = false;
+ private readonly _logger: Logger;
// WalletConnect client
private client: IWeb3Wallet | undefined;
// List of PKP wallets
private pkpEthersWallets: PKPEthersWallet[] = [];
- // For logging
- private readonly debug: boolean = false;
- private readonly PREFIX = '[PKPWalletConnect]';
- private readonly orange = '\x1b[33m';
- private readonly reset = '\x1b[0m';
-
constructor(debug?: boolean) {
this.debug = debug || false;
+ this._logger = getChildLogger({
+ module: 'PKPWalletConnect',
+ ...(debug ? { level: 'debug' } : {}),
+ });
}
/**
@@ -689,7 +690,7 @@ export class PKPWalletConnect {
client: IWeb3Wallet | undefined
): IWeb3Wallet {
if (!client) {
- this._log('WalletConnect client has not yet been initialized.');
+ this._logger.debug('WalletConnect client has not yet been initialized.');
throw new InitError(
{},
'WalletConnect client has not yet been initialized. Please call initWalletConnect().'
@@ -697,16 +698,4 @@ export class PKPWalletConnect {
}
return client;
}
-
- /**
- * Logs the provided arguments to the console if the `debug` property is set to true.
- *
- * @private
- * @param {...any[]} args - The arguments to log to the console.
- */
- private _log(...args: any[]): void {
- if (this.debug) {
- console.log(this.orange + this.PREFIX + this.reset, ...args);
- }
- }
}
diff --git a/packages/schemas/project.json b/packages/schemas/project.json
index 44e7606077..d78fcc5a8e 100644
--- a/packages/schemas/project.json
+++ b/packages/schemas/project.json
@@ -28,7 +28,7 @@
"lintFilePatterns": ["packages/schemas/**/*.ts"]
}
},
- "testPackage": {
+ "test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/packages/schemas"],
"options": {
diff --git a/packages/schemas/src/index.ts b/packages/schemas/src/index.ts
index 8259b5c291..034c4467f9 100644
--- a/packages/schemas/src/index.ts
+++ b/packages/schemas/src/index.ts
@@ -1 +1,4 @@
+export * from './lib/encryption';
+export * from './lib/models';
export * from './lib/schemas';
+export * from './lib/validation';
diff --git a/packages/schemas/src/lib/encryption.ts b/packages/schemas/src/lib/encryption.ts
new file mode 100644
index 0000000000..9099a89455
--- /dev/null
+++ b/packages/schemas/src/lib/encryption.ts
@@ -0,0 +1,37 @@
+import { z } from 'zod';
+
+import { MultipleAccessControlConditionsSchema } from '@lit-protocol/access-control-conditions-schemas';
+
+import { AuthenticationContextSchema } from './models';
+import { AuthSigSchema, ChainedSchema, PricedSchema } from './schemas';
+
+export const DecryptRequestBaseSchema =
+ MultipleAccessControlConditionsSchema.merge(ChainedSchema)
+ .merge(PricedSchema.partial())
+ .extend({
+ authContext: AuthenticationContextSchema,
+ authSig: AuthSigSchema.optional(),
+ });
+
+export const EncryptResponseSchema = z.object({
+ /**
+ * The base64-encoded ciphertext
+ */
+ ciphertext: z.string(),
+ /**
+ * The hash of the data that was encrypted
+ */
+ dataToEncryptHash: z.string(),
+});
+
+export const DecryptRequestSchema = EncryptResponseSchema.merge(
+ DecryptRequestBaseSchema
+);
+
+export const EncryptRequestSchema =
+ MultipleAccessControlConditionsSchema.extend({
+ /**
+ * The uint8array that you wish to encrypt
+ */
+ dataToEncrypt: z.instanceof(Uint8Array),
+ });
diff --git a/packages/schemas/src/lib/models.ts b/packages/schemas/src/lib/models.ts
new file mode 100644
index 0000000000..caf8048090
--- /dev/null
+++ b/packages/schemas/src/lib/models.ts
@@ -0,0 +1,253 @@
+import { SiweMessage } from 'siwe';
+import { z } from 'zod';
+
+import {
+ AttenuationsObjectSchema,
+ AuthMethodSchema,
+ AuthSigSchema,
+ ChainSchema,
+ CosmosWalletTypeSchema,
+ DefinedJsonSchema,
+ EvmChainSchema,
+ ExecuteJsAdvancedOptionsSchema,
+ IpfsOptionsSchema,
+ LitAbilitySchema,
+ LitActionSdkParamsSchema,
+ LitResourcePrefixSchema,
+ PricedSchema,
+ SessionKeyPairSchema,
+} from './schemas';
+
+export const ILitResourceSchema = z.object({
+ /**
+ * Gets the fully qualified resource key.
+ * @returns The fully qualified resource key.
+ */
+ getResourceKey: z.function().args().returns(z.string()),
+ /**
+ * Validates that the given LIT ability is valid for this resource.
+ * @param litAbility The LIT ability to validate.
+ */
+ isValidLitAbility: z.function().args(LitAbilitySchema).returns(z.boolean()),
+ toString: z.function().args().returns(z.string()),
+ resourcePrefix: LitResourcePrefixSchema.readonly(),
+ resource: z.string().readonly(),
+});
+
+/**
+ * A LIT resource ability is a combination of a LIT resource and a LIT ability.
+ * It specifies which LIT specific ability is being requested to be performed
+ * on the specified LIT resource.
+ *
+ * @description This object does NOT guarantee compatibility between the
+ * specified LIT resource and the specified LIT ability, and will be validated by
+ * the LIT-internal systems.
+ */
+export const LitResourceAbilityRequestSchema = z.object({
+ resource: ILitResourceSchema,
+ ability: LitAbilitySchema,
+ data: z.record(z.string(), DefinedJsonSchema).optional(),
+});
+
+export const AuthCallbackParamsSchema = LitActionSdkParamsSchema.extend({
+ /**
+ * The serialized session key pair to sign. If not provided, a session key pair will be fetched from localStorge or generated.
+ */
+ sessionKey: SessionKeyPairSchema.optional(),
+ /**
+ * The chain you want to use. Find the supported list of chains here: https://developer.litprotocol.com/docs/supportedChains
+ */
+ chain: EvmChainSchema,
+ /**
+ * The statement that describes what the user is signing. If the auth callback is for signing a SIWE message, you MUST add this statement to the end of the SIWE statement.
+ */
+ statement: z.string().optional(),
+ /**
+ * The blockhash that the nodes return during the handshake
+ */
+ nonce: z.string(),
+ /**
+ * Optional and only used with EVM chains. A list of resources to be passed to Sign In with Ethereum. These resources will be part of the Sign in with Ethereum signed message presented to the user.
+ */
+ resources: z.array(z.string()).optional(),
+ /**
+ * Optional and only used with EVM chains right now. Set to true by default. Whether or not to ask Metamask or the user's wallet to switch chains before signing. This may be desired if you're going to have the user send a txn on that chain. On the other hand, if all you care about is the user's wallet signature, then you probably don't want to make them switch chains for no reason. Pass false here to disable this chain switching behavior.
+ */
+ switchChain: z.boolean().optional(),
+ // --- Following for Session Auth ---
+ expiration: z.string().optional(),
+ uri: z.string().optional(),
+ /**
+ * Cosmos wallet type, to support mutliple popular cosmos wallets
+ * Keplr & Cypher -> window.keplr
+ * Leap -> window.leap
+ */
+ cosmosWalletType: CosmosWalletTypeSchema.optional(),
+ /**
+ * Optional project ID for WalletConnect V2. Only required if one is using checkAndSignAuthMessage and wants to display WalletConnect as an option.
+ */
+ walletConnectProjectId: z.string().optional(),
+ resourceAbilityRequests: z.array(LitResourceAbilityRequestSchema).optional(),
+});
+
+export const AuthCallbackSchema = z
+ .function()
+ .args(AuthCallbackParamsSchema)
+ .returns(z.promise(AuthSigSchema));
+
+export const ISessionCapabilityObjectSchema = z.object({
+ attenuations: AttenuationsObjectSchema,
+ proofs: z.array(z.string()), // CID[]
+ statement: z.string(),
+ addProof: z.function().args(z.string()).returns(z.void()), // (proof: CID) => void
+ /**
+ * Add an arbitrary attenuation to the session capability object.
+ *
+ * @description We do NOT recommend using this unless with the LIT specific
+ * abilities. Use this ONLY if you know what you are doing.
+ */
+ addAttenuation: z
+ .function()
+ .args(
+ z.string(),
+ z.string().optional(),
+ z.string().optional(),
+ z.record(z.string(), DefinedJsonSchema).optional()
+ )
+ .returns(z.void()),
+ addToSiweMessage: z
+ .function()
+ .args(z.instanceof(SiweMessage))
+ .returns(z.instanceof(SiweMessage)),
+ /**
+ * Encode the session capability object as a SIWE resource.
+ */
+ encodeAsSiweResource: z.function().returns(z.string()),
+
+ /** LIT specific methods */
+
+ /**
+ * Add a LIT-specific capability to the session capability object for the
+ * specified resource.
+ *
+ * @param litResource The LIT-specific resource being added.
+ * @param ability The LIT-specific ability being added.
+ * @param [data]
+ * @example If the ability is `LitAbility.AccessControlConditionDecryption`,
+ * then the resource should be the hashed key value of the access control
+ * condition.
+ * @example If the ability is `LitAbility.AccessControlConditionSigning`,
+ * then the resource should be the hashed key value of the access control
+ * condition.
+ * @example If the ability is `LitAbility.PKPSigning`, then the resource
+ * should be the PKP token ID.
+ * @example If the ability is `LitAbility.RateLimitIncreaseAuth`, then the
+ * resource should be the RLI token ID.
+ * @example If the ability is `LitAbility.LitActionExecution`, then the
+ * resource should be the Lit Action IPFS CID.
+ * @throws If the ability is not a LIT-specific ability.
+ */
+ addCapabilityForResource: z
+ .function()
+ .args(
+ ILitResourceSchema,
+ LitAbilitySchema,
+ z.record(z.string(), DefinedJsonSchema).optional()
+ )
+ .returns(z.void()),
+ /**
+ * Verify that the session capability object has the specified LIT-specific
+ * capability for the specified resource.
+ */
+ verifyCapabilitiesForResource: z
+ .function()
+ .args(ILitResourceSchema, LitAbilitySchema)
+ .returns(z.boolean()),
+ /**
+ * Add a wildcard ability to the session capability object for the specified
+ * resource.
+ */
+ addAllCapabilitiesForResource: z
+ .function()
+ .args(ILitResourceSchema)
+ .returns(z.void()),
+});
+
+export const AuthenticationContextSchema = LitActionSdkParamsSchema.extend({
+ /**
+ * Session signature properties shared across all functions that generate session signatures.
+ */
+ pkpPublicKey: z.string().optional(),
+
+ /**
+ * When this session signature will expire. After this time is up you will need to reauthenticate, generating a new session signature. The default time until expiration is 24 hours. The formatting is an [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339) timestamp.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ expiration: z.any().optional(),
+
+ /**
+ * The chain to use for the session signature and sign the session key. This value is almost always `ethereum`. If you're using EVM, this parameter isn't very important.
+ */
+ chain: ChainSchema.optional(),
+
+ /**
+ * An array of resource abilities that you want to request for this session. These will be signed with the session key.
+ * For example, an ability is added to grant a session permission to decrypt content associated with a particular Access Control Conditions (ACC) hash. When trying to decrypt, this ability is checked in the `resourceAbilityRequests` to verify if the session has the required decryption capability.
+ * @example
+ * [{ resource: new LitAccessControlConditionResource('someAccHash`), ability: LitAbility.AccessControlConditionDecryption }]
+ */
+ resourceAbilityRequests: z.array(LitResourceAbilityRequestSchema),
+
+ /**
+ * The session capability object that you want to request for this session.
+ * It is likely you will not need this, as the object will be automatically derived from the `resourceAbilityRequests`.
+ * If you pass nothing, then this will default to a wildcard for each type of resource you're accessing.
+ * The wildcard means that the session will be granted the ability to perform operations with any access control condition.
+ */
+ sessionCapabilityObject: ISessionCapabilityObjectSchema.optional(),
+
+ /**
+ * If you want to ask MetaMask to try and switch the user's chain, you may pass true here. This will only work if the user is using MetaMask, otherwise this will be ignored.
+ */
+ switchChain: z.boolean().optional(),
+ /**
+ * The serialized session key pair to sign.
+ * If not provided, a session key pair will be fetched from localStorage or generated.
+ */
+ sessionKey: SessionKeyPairSchema.optional(),
+
+ /**
+ * Not limited to capacityDelegationAuthSig. Other AuthSigs with other purposes can also be in this array.
+ */
+ capabilityAuthSigs: z.array(AuthSigSchema).optional(),
+
+ /**
+ * This is a callback that will be used to generate an AuthSig within the session signatures. It's inclusion is required, as it defines the specific resources and abilities that will be allowed for the current session.
+ */
+ authNeededCallback: AuthCallbackSchema.optional(),
+
+ authMethods: z.array(AuthMethodSchema).optional(),
+
+ ipfsOptions: IpfsOptionsSchema.optional(),
+});
+
+export const JsonExecutionSdkParamsBaseSchema = LitActionSdkParamsSchema.pick({
+ jsParams: true,
+})
+ .merge(ExecuteJsAdvancedOptionsSchema)
+ .merge(PricedSchema.partial())
+ .extend({
+ /**
+ * JS code to run on the nodes
+ */
+ code: z.string().optional(),
+ /**
+ * The IPFS ID of some JS code to run on the nodes
+ */
+ ipfsId: z.string().optional(),
+
+ /**
+ * auth context
+ */
+ authContext: AuthenticationContextSchema,
+ });
diff --git a/packages/schemas/src/lib/schemas.ts b/packages/schemas/src/lib/schemas.ts
index 05d9c2a9b3..e0aeaaba5d 100644
--- a/packages/schemas/src/lib/schemas.ts
+++ b/packages/schemas/src/lib/schemas.ts
@@ -1,21 +1,49 @@
import { z } from 'zod';
import {
- LIT_ABILITY,
LIT_AUTH_SIG_CHAIN_KEYS,
+ LIT_ABILITY,
+ LIT_CHAINS_KEYS,
LIT_NETWORK,
LIT_RESOURCE_PREFIX,
VMTYPE,
} from '@lit-protocol/constants';
+const definedLiteralSchema = z.union([z.string(), z.number(), z.boolean()]);
+export type DefinedLiteral = z.infer;
+export type DefinedJson =
+ | DefinedLiteral
+ | { [key: string]: DefinedJson }
+ | DefinedJson[];
+export const DefinedJsonSchema: z.ZodType = z.lazy(() =>
+ z.union([
+ definedLiteralSchema,
+ z.array(DefinedJsonSchema),
+ z.record(DefinedJsonSchema),
+ ])
+);
+
const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
-type Literal = z.infer;
-type Json = Literal | { [key: string]: Json } | Json[];
+export type Literal = z.infer;
+export type Json = Literal | { [key: string]: Json } | Json[];
export const JsonSchema: z.ZodType = z.lazy(() =>
z.union([literalSchema, z.array(JsonSchema), z.record(JsonSchema)])
);
+export const HexSchema = z.string().regex(/^0x[0-9a-fA-F]+$/);
export const ChainSchema = z.string();
+export const EvmChainSchema = z.enum(LIT_CHAINS_KEYS);
+
+export const ChainedSchema = z.object({
+ /**
+ * The chain name of the chain that will be used. See LIT_CHAINS for currently supported chains.
+ */
+ chain: ChainSchema,
+});
+
+export const PricedSchema = z.object({
+ userMaxPrice: z.bigint(),
+});
export const LitNetworkKeysSchema = z.nativeEnum(LIT_NETWORK);
@@ -101,3 +129,139 @@ export const AllLitChainsSchema = z.record(
z.string(),
z.union([LitEVMChainSchema, LitSVMChainSchema, LitCosmosChainSchema])
);
+
+export const AuthSigSchema = z.object({
+ /**
+ * The signature produced by signing the `signMessage` property with the corresponding private key for the `address` property.
+ */
+ sig: z.string(),
+ /**
+ * The method used to derive the signature (e.g, `web3.eth.personal.sign`).
+ */
+ derivedVia: z.string(),
+ /**
+ * An [ERC-5573](https://eips.ethereum.org/EIPS/eip-5573) SIWE (Sign-In with Ethereum) message. This can be prepared by using one of the `createSiweMessage` functions from the [`@auth-helpers`](https://v6-api-doc-lit-js-sdk.vercel.app/modules/auth_helpers_src.html) package:
+ * - [`createSiweMessage`](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessage.html)
+ * - [`createSiweMessageWithRecaps](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessageWithRecaps.html)
+ * - [`createSiweMessageWithCapacityDelegation`](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessageWithCapacityDelegation.html)
+ */
+ signedMessage: z.string(),
+ /**
+ * The Ethereum address that was used to sign `signedMessage` and create the `sig`.
+ */
+ address: z.string(),
+ /**
+ * An optional property only seen when generating session signatures, this is the signing algorithm used to generate session signatures.
+ */
+ algo: z.string().optional(),
+});
+
+export const ResponseStrategySchema = z.enum([
+ 'leastCommon',
+ 'mostCommon',
+ 'custom',
+]);
+
+export const LitActionResponseStrategySchema = z.object({
+ strategy: ResponseStrategySchema,
+ customFilter: z
+ .function()
+ .args(z.array(z.record(z.string(), z.string())))
+ .returns(z.record(z.string(), z.string()))
+ .optional(),
+});
+
+export const IpfsOptionsSchema = z.object({
+ overwriteCode: z.boolean().optional(),
+ gatewayUrl: z.string().startsWith('https://').endsWith('/ipfs/').optional(),
+});
+
+export const ExecuteJsAdvancedOptionsSchema = z.object({
+ /**
+ * a strategy for processing `response` objects returned from the
+ * Lit Action execution context
+ */
+ responseStrategy: LitActionResponseStrategySchema.optional(),
+ /**
+ * Allow overriding the default `code` property in the `JsonExecutionSdkParams`
+ */
+ ipfsOptions: IpfsOptionsSchema.optional(),
+ /**
+ * Only run the action on a single node; this will only work if all code in your action is non-interactive
+ */
+ useSingleNode: z.boolean().optional(),
+});
+
+// pub struct AuthMethod {
+// pub auth_method_type: u32,
+// pub access_token: String,
+// }
+export const AuthMethodSchema = z.object({
+ authMethodType: z.number(),
+ accessToken: z.string(),
+});
+
+// TODO make it forcefully have litActionCode OR litActionIpfsId, one and only one of them MUST be provided
+export const LitActionSdkParamsSchema = z.object({
+ /**
+ * The litActionCode is the JavaScript code that will run on the nodes.
+ * You will need to convert the string content to base64.
+ *
+ * @example
+ * Buffer.from(litActionCodeString).toString('base64');
+ */
+ litActionCode: z.string().optional(),
+ /**
+ * You can obtain the Lit Action IPFS CID by converting your JavaScript code using this tool:
+ * https://explorer.litprotocol.com/create-action
+ *
+ * Note: You do not need to pin your code to IPFS necessarily.
+ * You can convert a code string to an IPFS hash using the "ipfs-hash-only" or 'ipfs-unixfs-importer' library.
+ *
+ * @example
+ * async function stringToIpfsHash(input: string): Promise {
+ * // Convert the input string to a Buffer
+ * const content = Buffer.from(input);
+ *
+ * // Import the content to create an IPFS file
+ * const files = importer([{ content }], {} as any, { onlyHash: true });
+ *
+ * // Get the first (and only) file result
+ * const result = (await files.next()).value;
+ *
+ * const ipfsHash = (result as any).cid.toString();
+ * if (!ipfsHash.startsWith('Qm')) {
+ * throw new Error('Generated hash does not start with Qm');
+ * }
+ *
+ * return ipfsHash;
+ * }
+ */
+ litActionIpfsId: z.string().optional(),
+ /**
+ * An object that contains params to expose to the Lit Action. These will be injected to the JS runtime before your code runs, so you can use any of these as normal variables in your Lit Action.
+ */
+ jsParams: z
+ .union([
+ z.any(), // TODO what happens if jsParams is a string/number/primitive?
+ z
+ .object({
+ publicKey: z.string().optional(),
+ sigName: z.string().optional(),
+ })
+ .catchall(z.any()),
+ ])
+ .optional(),
+});
+
+export const CosmosWalletTypeSchema = z.enum(['keplr', 'leap'] as const);
+
+export const SessionKeyPairSchema = z.object({
+ publicKey: z.string(),
+ secretKey: z.string(),
+});
+
+export const AttenuationsObjectSchema = z.record(
+ z.string(),
+ z.record(z.string(), z.array(DefinedJsonSchema))
+);
diff --git a/packages/schemas/src/lib/validation.ts b/packages/schemas/src/lib/validation.ts
new file mode 100644
index 0000000000..7561f3eea4
--- /dev/null
+++ b/packages/schemas/src/lib/validation.ts
@@ -0,0 +1,33 @@
+import { z } from 'zod';
+import { fromError, isZodErrorLike } from 'zod-validation-error';
+
+import { InvalidArgumentException } from '@lit-protocol/constants';
+
+export function throwFailedValidation(
+ functionName: string,
+ params: unknown,
+ e: unknown
+): never {
+ throw new InvalidArgumentException(
+ {
+ info: {
+ params,
+ function: functionName,
+ },
+ cause: isZodErrorLike(e) ? fromError(e) : e,
+ },
+ `Invalid params for ${functionName}. Check error for details.`
+ );
+}
+
+export function applySchemaWithValidation(
+ functionName: string,
+ params: T,
+ schema: z.ZodType
+): T {
+ try {
+ return schema.parse(params);
+ } catch (e) {
+ throwFailedValidation(functionName, params, e);
+ }
+}
diff --git a/packages/types/src/lib/interfaces.ts b/packages/types/src/lib/interfaces.ts
index f6da23aa46..0888ce1ecf 100644
--- a/packages/types/src/lib/interfaces.ts
+++ b/packages/types/src/lib/interfaces.ts
@@ -1,21 +1,37 @@
import { Provider } from '@ethersproject/abstract-provider';
+import { z } from 'zod';
+import { MultipleAccessControlConditionsSchema } from '@lit-protocol/access-control-conditions-schemas';
import { LitEVMChainKeys } from '@lit-protocol/constants';
+import {
+ AuthCallbackSchema,
+ AuthenticationContextSchema,
+ AuthMethodSchema,
+ AuthSigSchema,
+ DecryptRequestSchema,
+ EncryptResponseSchema,
+ EncryptRequestSchema,
+ ExecuteJsAdvancedOptionsSchema,
+ IpfsOptionsSchema,
+ JsonExecutionSdkParamsBaseSchema,
+ LitActionResponseStrategySchema,
+ LitActionSdkParamsSchema,
+ SessionKeyPairSchema,
+} from '@lit-protocol/schemas';
import { SigType } from './EndpointResponses';
import { ILitNodeClient } from './ILitNodeClient';
import { ISessionCapabilityObject, LitResourceAbilityRequest } from './models';
import {
- AcceptedFileType,
AccessControlConditions,
Chain,
EvmContractConditions,
+ Hex,
IRelayAuthStatus,
JsonRequest,
LIT_NETWORKS_KEYS,
LitContractContext,
LitContractResolverContext,
- ResponseStrategy,
SolRpcConditions,
UnifiedAccessControlConditions,
} from './types';
@@ -25,35 +41,7 @@ import {
/**
* An `AuthSig` represents a cryptographic proof of ownership for an Ethereum address, created by signing a standardized [ERC-5573 SIWE ReCap](https://eips.ethereum.org/EIPS/eip-5573) (Sign-In with Ethereum) message. This signature serves as a verifiable credential, allowing the Lit network to associate specific permissions, access rights, and operational parameters with the signing Ethereum address. By incorporating various capabilities, resources, and parameters into the SIWE message before signing, the resulting `AuthSig` effectively defines and communicates these authorizations and specifications for the address within the Lit network.
*/
-export interface AuthSig {
- /**
- * The signature produced by signing the `signMessage` property with the corresponding private key for the `address` property.
- */
- sig: string;
-
- /**
- * The method used to derive the signature (e.g, `web3.eth.personal.sign`).
- */
- derivedVia: string;
-
- /**
- * An [ERC-5573](https://eips.ethereum.org/EIPS/eip-5573) SIWE (Sign-In with Ethereum) message. This can be prepared by using one of the `createSiweMessage` functions from the [`@auth-helpers`](https://v6-api-doc-lit-js-sdk.vercel.app/modules/auth_helpers_src.html) package:
- * - [`createSiweMessage`](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessage.html)
- * - [`createSiweMessageWithRecaps](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessageWithRecaps.html)
- * - [`createSiweMessageWithCapacityDelegation`](https://v6-api-doc-lit-js-sdk.vercel.app/functions/auth_helpers_src.createSiweMessageWithCapacityDelegation.html)
- */
- signedMessage: string;
-
- /**
- * The Ethereum address that was used to sign `signedMessage` and create the `sig`.
- */
- address: string;
-
- /**
- * An optional property only seen when generating session signatures, this is the signing algorithm used to generate session signatures.
- */
- algo?: string;
-}
+export type AuthSig = z.infer;
export interface AuthCallbackParams extends LitActionSdkParams {
/**
@@ -236,7 +224,6 @@ export interface NodeSetRequired {
export interface JsonSignSessionKeyRequestV1
extends Pick,
- Pick,
NodeSetRequired {
sessionKey: string;
authMethods: AuthMethod[];
@@ -247,11 +234,11 @@ export interface JsonSignSessionKeyRequestV1
// custom auth params
code?: string;
+ litActionIpfsId?: string;
}
export interface JsonSignSessionKeyRequestV2
extends Pick,
- Pick,
NodeSetRequired {
sessionKey: string;
authMethods: AuthMethod[];
@@ -262,6 +249,7 @@ export interface JsonSignSessionKeyRequestV2
// custom auth params
code?: string;
+ litActionIpfsId?: string;
signingScheme: T;
}
@@ -334,21 +322,9 @@ export interface JsonSigningResourceId {
extraData: string;
}
-// CHANGE: `MultipleAccessControlConditions` is basically identical to `AccessControlConditions`,
-// but due to the way the types are deeply nested, we will revisit this later.
-export interface MultipleAccessControlConditions {
- // The access control conditions that the user must meet to obtain this signed token. This could be possession of an NFT, for example. You must pass either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions.
- accessControlConditions?: AccessControlConditions;
-
- // EVM Smart Contract access control conditions that the user must meet to obtain this signed token. This could be possession of an NFT, for example. This is different than accessControlConditions because accessControlConditions only supports a limited number of contract calls. evmContractConditions supports any contract call. You must pass either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions.
- evmContractConditions?: EvmContractConditions;
-
- // Solana RPC call conditions that the user must meet to obtain this signed token. This could be possession of an NFT, for example.
- solRpcConditions?: SolRpcConditions;
-
- // An array of unified access control conditions. You may use AccessControlCondition, EVMContractCondition, or SolRpcCondition objects in this array, but make sure you add a conditionType for each one. You must pass either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions.
- unifiedAccessControlConditions?: UnifiedAccessControlConditions;
-}
+export type MultipleAccessControlConditions = z.infer<
+ typeof MultipleAccessControlConditionsSchema
+>;
export interface JsonAccsRequest extends MultipleAccessControlConditions {
// The chain name of the chain that you are querying. See ALL_LIT_CHAINS for currently supported chains.
@@ -423,52 +399,19 @@ export interface JsonEncryptionRetrieveRequest extends JsonAccsRequest {
toDecrypt: string;
}
-export interface LitActionResponseStrategy {
- strategy: ResponseStrategy;
- customFilter?: (
- responses: Record[]
- ) => Record;
-}
-
-export interface IpfsOptions {
- overwriteCode?: boolean;
- gatewayUrl?: `https://${string}/ipfs/`;
-}
-
-export interface JsonExecutionSdkParams
- extends Pick,
- ExecuteJsAdvancedOptions {
- /**
- * JS code to run on the nodes
- */
- code?: string;
-
- /**
- * The IPFS ID of some JS code to run on the nodes
- */
- ipfsId?: string;
-
- authContext: AuthenticationContext;
- userMaxPrice?: bigint;
-}
+export type LitActionResponseStrategy = z.infer<
+ typeof LitActionResponseStrategySchema
+>;
-export interface ExecuteJsAdvancedOptions {
- /**
- * a strategy for proccessing `reponse` objects returned from the
- * Lit Action execution context
- */
- responseStrategy?: LitActionResponseStrategy;
+export type IpfsOptions = z.infer;
- /**
- * Allow overriding the default `code` property in the `JsonExecutionSdkParams`
- */
- ipfsOptions?: IpfsOptions;
+export type ExecuteJsAdvancedOptions = z.infer<
+ typeof ExecuteJsAdvancedOptionsSchema
+>;
- /**
- * Only run the action on a single node; this will only work if all code in your action is non-interactive
- */
- useSingleNode?: boolean;
-}
+export type JsonExecutionSdkParams = z.infer<
+ typeof JsonExecutionSdkParamsBaseSchema
+>;
export interface JsonExecutionRequest
extends Pick,
@@ -485,56 +428,11 @@ export interface JsonExecutionRequest
authMethods?: AuthMethod[];
}
-export interface DecryptRequestBase extends MultipleAccessControlConditions {
- /**
- * The chain name of the chain that this contract is deployed on. See LIT_CHAINS for currently supported chains.
- */
- chain: Chain;
- authSig?: AuthSig;
- authContext: AuthenticationContext;
- userMaxPrice?: bigint;
-}
-export interface EncryptSdkParams extends MultipleAccessControlConditions {
- dataToEncrypt: Uint8Array;
-}
+export type EncryptSdkParams = z.infer;
-export interface EncryptRequest extends DecryptRequestBase {
- // The data that you wish to encrypt as a Uint8Array
- dataToEncrypt: Uint8Array;
-}
+export type EncryptResponse = z.infer;
-export interface EncryptResponse {
- /**
- * The base64-encoded ciphertext
- */
- ciphertext: string;
-
- /**
- * The hash of the data that was encrypted
- */
- dataToEncryptHash: string;
-}
-
-export interface EncryptUint8ArrayRequest
- extends MultipleAccessControlConditions {
- /**
- * The uint8array that you wish to encrypt
- */
- dataToEncrypt: Uint8Array;
-}
-
-export interface EncryptStringRequest extends MultipleAccessControlConditions {
- /**
- * String that you wish to encrypt
- */
- dataToEncrypt: string;
-}
-
-export interface EncryptFileRequest extends DecryptRequestBase {
- file: AcceptedFileType;
-}
-
-export interface DecryptRequest extends EncryptResponse, DecryptRequestBase {}
+export type DecryptRequest = z.infer;
export interface DecryptResponse {
// The decrypted data as a Uint8Array
@@ -549,7 +447,7 @@ export interface SigResponse {
r: string;
s: string;
recid: number;
- signature: `0x${string}`;
+ signature: Hex;
publicKey: string; // pkp public key (no 0x prefix)
dataSigned: string;
}
@@ -721,46 +619,6 @@ export interface JsonHandshakeResponse {
latestBlockhash?: string;
}
-export interface EncryptToJsonProps extends MultipleAccessControlConditions {
- /**
- * The chain
- */
- chain: string;
-
- /**
- * The string you wish to encrypt
- */
- string?: string;
-
- /**
- * The file you wish to encrypt
- */
- file?: AcceptedFileType;
-
- /**
- * An instance of LitNodeClient that is already connected
- */
- litNodeClient: ILitNodeClient;
-
- authContext: AuthenticationContext;
-}
-
-export type EncryptToJsonDataType = 'string' | 'file';
-
-export interface EncryptToJsonPayload extends DecryptRequestBase {
- ciphertext: string;
- dataToEncryptHash: string;
- dataType: EncryptToJsonDataType;
-}
-
-export interface DecryptFromJsonProps {
- // An instance of LitNodeClient that is already connected
- litNodeClient: ILitNodeClient;
-
- parsedJsonData: EncryptToJsonPayload;
- authContext: AuthenticationContext;
-}
-
/**
* Struct in rust
* -----
@@ -783,17 +641,11 @@ export interface SessionKeySignedMessage {
nodeAddress: string;
}
-export interface SessionKeyPair {
- publicKey: string;
- secretKey: string;
-}
+export type SessionKeyPair = z.infer;
/** ========== Session ========== */
-export interface AuthMethod {
- authMethodType: number;
- accessToken: string;
-}
+export type AuthMethod = z.infer;
// pub struct JsonSignSessionKeyRequest {
// pub session_key: String,
@@ -854,65 +706,9 @@ export interface SignSessionKeyResponse {
authSig: AuthSig;
}
-export interface AuthenticationContext extends LitActionSdkParams {
- /**
- * Session signature properties shared across all functions that generate session signatures.
- */
- pkpPublicKey?: string;
-
- /**
- * When this session signature will expire. After this time is up you will need to reauthenticate, generating a new session signature. The default time until expiration is 24 hours. The formatting is an [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339) timestamp.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- expiration?: any;
-
- /**
- * The chain to use for the session signature and sign the session key. This value is almost always `ethereum`. If you're using EVM, this parameter isn't very important.
- */
- chain?: Chain;
-
- /**
- * An array of resource abilities that you want to request for this session. These will be signed with the session key.
- * For example, an ability is added to grant a session permission to decrypt content associated with a particular Access Control Conditions (ACC) hash. When trying to decrypt, this ability is checked in the `resourceAbilityRequests` to verify if the session has the required decryption capability.
- * @example
- * [{ resource: new LitAccessControlConditionResource('someAccHash`), ability: LitAbility.AccessControlConditionDecryption }]
- */
- resourceAbilityRequests: LitResourceAbilityRequest[];
-
- /**
- * The session capability object that you want to request for this session.
- * It is likely you will not need this, as the object will be automatically derived from the `resourceAbilityRequests`.
- * If you pass nothing, then this will default to a wildcard for each type of resource you're accessing.
- * The wildcard means that the session will be granted the ability to perform operations with any access control condition.
- */
- sessionCapabilityObject?: ISessionCapabilityObject;
-
- /**
- * If you want to ask MetaMask to try and switch the user's chain, you may pass true here. This will only work if the user is using MetaMask, otherwise this will be ignored.
- */
- switchChain?: boolean;
- /**
- * The serialized session key pair to sign.
- * If not provided, a session key pair will be fetched from localStorage or generated.
- */
- sessionKey?: SessionKeyPair;
+export type AuthenticationContext = z.infer;
- /**
- * Not limited to capacityDelegationAuthSig. Other AuthSigs with other purposes can also be in this array.
- */
- capabilityAuthSigs?: AuthSig[];
-
- /**
- * This is a callback that will be used to generate an AuthSig within the session signatures. It's inclusion is required, as it defines the specific resources and abilities that will be allowed for the current session.
- */
- authNeededCallback?: AuthCallback;
-
- authMethods?: AuthMethod[];
-
- ipfsOptions?: IpfsOptions;
-}
-
-export type AuthCallback = (params: AuthCallbackParams) => Promise;
+export type AuthCallback = z.infer;
/**
* A map of node addresses to the session signature payload
@@ -1359,57 +1155,7 @@ export interface CapacityCreditsRes {
capacityDelegationAuthSig: AuthSig;
}
-export interface LitActionSdkParams {
- /**
- * The litActionCode is the JavaScript code that will run on the nodes.
- * You will need to convert the string content to base64.
- *
- * @example
- * Buffer.from(litActionCodeString).toString('base64');
- */
- litActionCode?: string;
-
- /**
- * You can obtain the Lit Action IPFS CID by converting your JavaScript code using this tool:
- * https://explorer.litprotocol.com/create-action
- *
- * Note: You do not need to pin your code to IPFS necessarily.
- * You can convert a code string to an IPFS hash using the "ipfs-hash-only" or 'ipfs-unixfs-importer' library.
- *
- * @example
- * async function stringToIpfsHash(input: string): Promise {
- * // Convert the input string to a Buffer
- * const content = Buffer.from(input);
- *
- * // Import the content to create an IPFS file
- * const files = importer([{ content }], {} as any, { onlyHash: true });
- *
- * // Get the first (and only) file result
- * const result = (await files.next()).value;
- *
- * const ipfsHash = (result as any).cid.toString();
- * if (!ipfsHash.startsWith('Qm')) {
- * throw new Error('Generated hash does not start with Qm');
- * }
- *
- * return ipfsHash;
- * }
- */
- litActionIpfsId?: string;
-
- /**
- * An object that contains params to expose to the Lit Action. These will be injected to the JS runtime before your code runs, so you can use any of these as normal variables in your Lit Action.
- */
- jsParams?:
- | {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- [key: string]: any;
- publicKey?: string;
- sigName?: string;
- }
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- | any;
-}
+export type LitActionSdkParams = z.infer;
export interface LitEndpoint {
path: string;
diff --git a/packages/types/src/lib/models.ts b/packages/types/src/lib/models.ts
index a86736b55d..57e67c6c4b 100644
--- a/packages/types/src/lib/models.ts
+++ b/packages/types/src/lib/models.ts
@@ -1,115 +1,22 @@
-import { SiweMessage } from 'siwe';
+import { z } from 'zod';
-import { LitAbility, LitResourcePrefix } from './types';
+import {
+ AttenuationsObjectSchema,
+ ISessionCapabilityObjectSchema,
+ LitResourceAbilityRequestSchema,
+ ILitResourceSchema,
+} from '@lit-protocol/schemas';
-export type PlainJSON =
- | boolean
- | number
- | string
- | { [key: string]: PlainJSON }
- | PlainJSON[];
-export type AttenuationsObject = Record>;
-export type CID = string;
-
-export interface ISessionCapabilityObject {
- get attenuations(): AttenuationsObject;
- get proofs(): CID[];
- get statement(): string;
- addProof(proof: CID): void;
-
- /**
- * Add an arbitrary attenuation to the session capability object.
- *
- * @description We do NOT recommend using this unless with the LIT specific
- * abilities. Use this ONLY if you know what you are doing.
- */
- addAttenuation(
- resource: string,
- namespace?: string,
- name?: string,
- restriction?: Record
- ): void;
- addToSiweMessage(siwe: SiweMessage): SiweMessage;
-
- /**
- * Encode the session capability object as a SIWE resource.
- */
- encodeAsSiweResource(): string;
-
- /** LIT specific methods */
+export type AttenuationsObject = z.infer;
- /**
- * Add a LIT-specific capability to the session capability object for the
- * specified resource.
- *
- * @param litResource The LIT-specific resource being added.
- * @param ability The LIT-specific ability being added.
- * @example If the ability is `LitAbility.AccessControlConditionDecryption`,
- * then the resource should be the hashed key value of the access control
- * condition.
- * @example If the ability is `LitAbility.AccessControlConditionSigning`,
- * then the resource should be the hashed key value of the access control
- * condition.
- * @example If the ability is `LitAbility.PKPSigning`, then the resource
- * should be the PKP token ID.
- * @example If the ability is `LitAbility.RateLimitIncreaseAuth`, then the
- * resource should be the RLI token ID.
- * @example If the ability is `LitAbility.LitActionExecution`, then the
- * resource should be the Lit Action IPFS CID.
- * @throws If the ability is not a LIT-specific ability.
- */
- addCapabilityForResource(
- litResource: ILitResource,
- ability: LitAbility,
- data?: unknown
- ): void;
-
- /**
- * Verify that the session capability object has the specified LIT-specific
- * capability for the specified resource.
- */
- verifyCapabilitiesForResource(
- litResource: ILitResource,
- ability: LitAbility
- ): boolean;
-
- /**
- * Add a wildcard ability to the session capability object for the specified
- * resource.
- */
- addAllCapabilitiesForResource(litResource: ILitResource): void;
-}
-
-export interface ILitResource {
- /**
- * Gets the fully qualified resource key.
- * @returns The fully qualified resource key.
- */
- getResourceKey(): string;
-
- /**
- * Validates that the given LIT ability is valid for this resource.
- * @param litAbility The LIT ability to validate.
- */
- isValidLitAbility(litAbility: LitAbility): boolean;
+export type CID = string;
- toString(): string;
+export type ISessionCapabilityObject = z.infer<
+ typeof ISessionCapabilityObjectSchema
+>;
- readonly resourcePrefix: LitResourcePrefix;
- readonly resource: string;
-}
+export type ILitResource = z.infer