### Advance Example: State Machine Transition Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/event-listener/README.md This example demonstrates an advanced state machine configuration, specifically transitioning to 'waitForFunds' to suspend the machine when additional funds are required. It shows how to define transitions within a state machine setup. ```javascript // Going back to waitForFunds to suspend machine if we need more sepolia eth or sepolia USDC transitions: [{ toState: 'waitForFunds' }], }, ], }); await stateMachine.startMachine('setPKP'); } bridgeBaseSepoliaUSDCToEthereumSepolia().catch(console.error); ``` -------------------------------- ### Install @lit-protocol/core Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/core/README.md Install the core package using yarn. ```bash yarn add @lit-protocol/core ``` -------------------------------- ### Install Auth Helpers Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/auth-helpers/README.md Install the auth-helpers package using yarn. ```bash yarn add @lit-protocol/auth-helpers ``` -------------------------------- ### Install @lit-protocol/event-listener Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/event-listener/README.md Install the event listener package using npm or yarn. ```bash npm install @lit-protocol/event-listener # or yarn add @lit-protocol/event-listener ``` -------------------------------- ### Install PKP SUI SDK Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-sui/README.md Install the necessary packages for using the PKP SUI wallet. ```bash yarn add @lit-protocol/pkp-sui @mysten/sui.js ``` -------------------------------- ### Install PKP WalletConnect Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-walletconnect/README.md Install the PKP WalletConnect package using yarn. ```bash yarn add @lit-protocol/pkp-walletconnect ``` -------------------------------- ### Install @lit-protocol/crypto Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/crypto/README.md Install the crypto package using yarn. ```bash yarn add @lit-protocol/crypto ``` -------------------------------- ### Basic State Machine Example Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/event-listener/README.md A simple example demonstrating how to set up a state machine to mint a PKP, a Capacity Delegation NFT, and then run a Lit Action every hour. Configure your private key and Lit network settings. ```typescript async function runLitActionInterval() { const stateMachine = StateMachine.fromDefinition({ privateKey: '0xPRIVATE_KEY_WITH_LIT_TOKENS', litNodeClient: { litNetwork: 'datil-test', }, litContracts: { network: 'datil-test', }, states: [ { key: 'setPKP', actions: [ { key: 'usePkp', mint: true, }, ], transitions: [{ toState: 'setCapacityNFT' }], }, { key: 'setCapacityNFT', actions: [ { key: 'useCapacityNFT', mint: true, daysUntilUTCMidnightExpiration: 10, requestPerSecond: 1, }, ], transitions: [{ toState: 'runLitAction' }], }, { key: 'runLitAction', actions: [ { key: 'litAction', code: `(async () => { if (magicNumber >= 42) { LitActions.setResponse({ response:"The number is greater than or equal to 42!" }); } else { LitActions.setResponse({ response: "The number is less than 42!" }); } })();`, jsParams: { magicNumber: Math.floor(Math.random() * 100), }, }, ], transitions: [{ toState: 'cooldown' }], }, { key: 'cooldown', transitions: [ { toState: 'runLitAction', timer: { // One hour, checking every second interval: 1000, // one second until: 1 * 60 * 60, // 3600 times }, }, ], }, ], }); // Start the machine at the desired state await stateMachine.startMachine('setPKP'); } runLitActionInterval().catch(console.error); ``` -------------------------------- ### Install PKP Base Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-base/README.md Install the PKP Base package using yarn. ```bash yarn add @lit-protocol/pkp-base ``` -------------------------------- ### Install Auth Browser Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/auth-browser/README.md Install the auth-browser package using yarn. ```bash yarn add @lit-protocol/auth-browser ``` -------------------------------- ### Install Lit Auth Client Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/lit-auth-client/README.md Install the Lit Auth Client package using yarn. ```bash yarn add @lit-protocol/lit-auth-client ``` -------------------------------- ### Install Wrapped Keys Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/wrapped-keys/README.md Install the @lit-protocol/wrapped-keys package using yarn. ```bash yarn add @lit-protocol/wrapped-keys ``` -------------------------------- ### Install Dependencies Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Installs project dependencies using Yarn. Ensure Node.js and Yarn are installed. ```bash yarn ``` -------------------------------- ### Install Contracts SDK Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/contracts-sdk/README.md Install the Contracts SDK package using yarn. ```bash yarn add @lit-protocol/contracts-sdk ``` -------------------------------- ### Install PKP Cosmos Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-cosmos/README.md Install the PKP Cosmos package using yarn. ```bash yarn add @lit-protocol/pkp-cosmos ``` -------------------------------- ### Install Lit Protocol Types Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/types/README.md Install the @lit-protocol/types package using yarn. ```bash yarn add @lit-protocol/types ``` -------------------------------- ### Install Lit Node Client Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/lit-node-client/README.md Install the Lit Node Client package using yarn. ```bash yarn add @lit-protocol/lit-node-client ``` -------------------------------- ### Run Development Server Source: https://github.com/lit-protocol/js-sdk/blob/master/tools/scripts/nextjs-demo-template/README.md Use these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Initialize and Use PKPCosmosWallet Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-cosmos/README.md Initialize the PKPCosmosWallet with authentication details and PKP public key. Use the wallet to get an address and sign direct transactions. ```typescript import { PKPCosmosWallet } from '@lit-protocol/pkp-cosmos'; // Initialize wallet const wallet = new PKPCosmosWallet({ controllerAuthSig: authSig, pkpPubKey: publicKey, addressPrefix: 'cosmos', }); // Get wallet address const address = await wallet.getAddress(); // Sign transaction const signedTx = await wallet.signDirect(address, { bodyBytes: tx.bodyBytes, authInfoBytes: tx.authInfoBytes, chainId: chainId, }); ``` -------------------------------- ### Install PKP Ethers Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-ethers/README.md Install the PKP Ethers package and its peer dependency, ethers.js. ```bash yarn add @lit-protocol/pkp-ethers ethers ``` -------------------------------- ### Install @lit-protocol/uint8array Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/uint8arrays/README.md Install the package using yarn for Node.js or browser environments. ```bash yarn add @lit-protocol/uint8array ``` -------------------------------- ### Install @lit-protocol/nacl Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/nacl/README.md Install the NaCl package for Node.js or browser environments using Yarn. ```bash yarn add @lit-protocol/nacl ``` -------------------------------- ### Create PKP SUI Wallet and Get Address Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-sui/README.md Instantiate the PKPSuiWallet with controller authentication and a public key, then retrieve the wallet's SUI address. ```typescript import { PKPSuiWallet } from '@lit-protocol/pkp-sui'; import { JsonRpcProvider, mainnetConnection } from '@mysten/sui.js'; const pkpSuiWallet = new PKPSuiWallet( { controllerAuthSig: AuthSig, pkpPubKey: PKPPubKey, }, new JsonRpcProvider(mainnetConnection) ); return await pkpSuiWallet.getAddress(); ``` -------------------------------- ### Install Lit Protocol JavaScript SDK Source: https://context7.com/lit-protocol/js-sdk/llms.txt Install the Lit Protocol JavaScript SDK using yarn. Choose the universal package for browser and Node.js, or the Node.js-only package. ```bash # Universal (browser + Node.js) yarn add @lit-protocol/lit-node-client # Node.js only (no browser-specific methods) yarn add @lit-protocol/lit-node-client-nodejs ``` -------------------------------- ### Install Access Control Conditions Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/access-control-conditions/README.md Install the @lit-protocol/access-control-conditions package using yarn. ```bash yarn add @lit-protocol/access-control-conditions ``` -------------------------------- ### Initialize LitCore and Connect Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/core/README.md Initialize the LitCore class and establish a connection. This is a basic setup for using core functionalities. ```typescript import { LitCore } from '@lit-protocol/core'; // Initialize core functionality const litCore = new LitCore(); // Use core utilities await litCore.connect(); ``` -------------------------------- ### Install Wrapped Keys LIT Actions Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/wrapped-keys-lit-actions/README.md Install the wrapped keys LIT actions package as a dependency using yarn. ```bash yarn add @lit-protocol/wrapped-keys-lit-actions ``` -------------------------------- ### Install @lit-protocol/misc Package Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/misc/README.md Install the misc package using yarn for use in Node.js or browser environments. ```bash yarn add @lit-protocol/misc ``` -------------------------------- ### Install @lit-protocol/constants Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/constants/README.md Add the @lit-protocol/constants package to your project using Yarn. ```bash yarn add @lit-protocol/constants ``` -------------------------------- ### Install NodeJS Exclusive Lit SDK Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Use this command to install the NodeJS exclusive version of the Lit SDK, which omits browser-specific methods. ```bash yarn add @lit-protocol/lit-node-client-nodejs ``` -------------------------------- ### Install @lit-protocol/encryption Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/encryption/README.md Install the encryption submodule using Yarn. This package is required for both Node.js and browser environments. ```bash yarn add @lit-protocol/encryption ``` -------------------------------- ### Lit Contracts Configuration File Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/contracts-sdk/README.md Example of the lit-contracts.config.json file used for configuring the Contracts SDK. It specifies the root URL for contract data, the contracts file, and ABIs directory. ```json { "root": "https://raw.githubusercontent.com/LIT-Protocol/LitNodeContracts/main/", "contracts": "deployed_contracts_serrano.json", "abis": { "dir": "deployments/mumbai_80001/", "ignoreProperties": ["metadata", "bytecode", "deployedBytecode"] } } ``` -------------------------------- ### Listen for Ethereum Blocks with Hash Ending in Zero Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/event-listener/README.md Use a functional interface to define custom logic for listening to Ethereum blocks. This example specifically monitors block hashes for those ending in '0'. Requires LitNodeClient and LitContracts initialization. ```typescript async function monitorEthereumBlocksWithHashEndingWithZero() { const litNodeClient = new LitNodeClient({ litNetwork: 'datil-dev', }); const litContracts = new LitContracts({ network: 'datil-dev', }); const stateMachine = new StateMachine({ // When the machine doesn't mint nor use Lit, these values do not matter privateKey: 'NOT_USED', litNodeClient, litContracts, }); // const stateMachine = StateMachine.fromDefinition({...}) also works to extend a base definition // Add each state individually stateMachine.addState({ key: 'listenBlocks', onEnter: async () => console.log('Waiting for a block with a hash ending in 0'), onExit: async () => console.log('Found a block whose hash ends in 0!'), }); stateMachine.addState({ key: 'autoAdvancingState', }); // Then add transitions between states stateMachine.addTransition({ // Because this transition does not have any listeners, it will be triggered automatically when the machine enters fromState fromState: 'autoAdvancingState', toState: 'listenBlocks', }); stateMachine.addTransition({ fromState: 'listenBlocks', toState: 'autoAdvancingState', // listeners are the ones that will produce the values that the transition will monitor listeners: [new EVMBlockListener(LIT_EVM_CHAINS.ethereum.rpcUrls[0])], // check is the function that will evaluate all values produced by listeners and define if there is a match or not check: async (values): Promise => { // values are the results of all listeners const blockData = values[0] as BlockData; if (!blockData) return false; console.log(`New block: ${blockData.number} (${blockData.hash})`); return blockData.hash.endsWith('0'); }, // when check finds a match (returns true) this function gets executed and the machine moves to toState onMatch: async (values) => { // values are the results of all listeners console.log('We have matching values here'); }, onMismatch: undefined, // when check returns false (there is a mismatch) this function gets executed but the machine does not change state onError: undefined, }); await stateMachine.startMachine('listenBlocks'); } monitorEthereumBlocksWithHashEndingWithZero().catch(console.error); ``` -------------------------------- ### Bridge USDC Between EVM Chains with State Machine Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/event-listener/README.md Implement a cross-chain messaging service to bridge USDC between Base Sepolia and Ethereum Sepolia. This example configures a State Machine PKP to listen for USDC transfers on Base Sepolia and automatically send the same amount to the sender on Ethereum Sepolia. ```typescript async function bridgeBaseSepoliaUSDCToEthereumSepolia() { const evmSourceNetwork = LIT_EVM_CHAINS.baseSepolia; const evmDestinationNetwork = LIT_EVM_CHAINS.sepolia; const pkp = { tokenId: '0x123...', publicKey: '456...', ethAddress: '0x789...', } as PKPInfo; // Minted Previously const capacityTokenId = '123456'; // Minted previously // Because the pkp and the capacity token nft were minted previously, this private key only needs to be an authorized signer of the pkp. It can be empty, without funds of any kind const ethPrivateKey = '0xTHE_PKP_AUTHORIZED_SIGNER_PRIVATE_KEY'; const stateMachine = StateMachine.fromDefinition({ 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 // activePkp: pkp, }, litNodeClient: { litNetwork: 'datil', }, litContracts: { network: 'datil', }, states: [ { key: 'setPKP', actions: [ { key: 'usePkp', pkp, // Configure the pkp passed. Not minting a new one }, ], transitions: [{ toState: 'setCapacityNFT' }], }, { key: 'setCapacityNFT', actions: [ { key: 'useCapacityNFT', capacityTokenId: capacityTokenId, // Configure the capacity token to use. Not minting a new one }, ], transitions: [{ toState: 'waitForFunds' }], }, { key: 'waitForFunds', // Waits for our emitting PKP to have some USDC and native balance in destination chain transitions: [ { toState: 'waitForTransfer', balances: [ { address: pkp.ethAddress as Address, evmChainId: evmDestinationNetwork.chainId, type: 'native' as const, comparator: '>=' as const, amount: '0.001', }, { address: pkp.ethAddress as Address, evmChainId: evmDestinationNetwork.chainId, type: 'ERC20' as const, tokenAddress: USDC_ETH_SEPOLIA_ADDRESS, tokenDecimals: 6, comparator: '>=' as const, amount: '20', }, ], }, ], }, { key: 'waitForTransfer', actions: [ { key: 'context', log: { path: '', // We want to log the full context for debugging }, }, ], transitions: [ // Waits to receive an USDC transfer in our listening chain { toState: 'transferFunds', evmContractEvent: { evmChainId: evmSourceNetwork.chainId, contractAddress: USDC_BASE_SEPOLIA_ADDRESS, contractABI: USDC_ABI, eventName: 'Transfer', // Filter events using params for just listening the pkp.ethAddress as destination eventParams: [null, pkp.ethAddress], contextUpdates: [ // The transition can perform some updates to the context { contextPath: 'transfer.sender', // The context path to update dataPath: 'event.args[0]', // The value from the event to save in the context }, { contextPath: 'transfer.amount', dataPath: 'event.args[2]', }, ], }, }, ], }, { key: 'transferFunds', // Sends a transaction to transfer some USDC in destination chain actions: [ { key: 'transaction', evmChainId: evmDestinationNetwork.chainId, contractAddress: USDC_ETH_SEPOLIA_ADDRESS, contractABI: [ 'function transfer(address to, uint256 amount) public returns (bool)', ], method: 'transfer', params: [ // Params can be hardcoded values such as ['0x123...', '100'] or values from the state machine context { contextPath: 'transfer.sender', }, { contextPath: 'transfer.amount', }, ], }, ], }, ], }); await stateMachine.run(); } ``` -------------------------------- ### Initialize and Use PKPBase Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-base/README.md Initialize the PKPBase with controller authentication and public key, then connect to the LIT node and run a LIT action. ```typescript import { PKPBase } from '@lit-protocol/pkp-base'; // Initialize PKP Base const pkpBase = new PKPBase({ controllerAuthSig: authSig, pkpPubKey: publicKey, }); // Connect to LIT node await pkpBase.init(); // Run LIT action const signature = await pkpBase.runLitAction(dataToSign, 'sign'); ``` -------------------------------- ### Initialize PKP WalletConnect Client and Handle Events Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-walletconnect/README.md Initialize the PKPWalletConnect client and set up event handlers for session proposals and requests. Use this to manage dApp connections and respond to session interactions. ```typescript import { PKPWalletConnect } from '@lit-protocol/pkp-walletconnect'; // Initialize WalletConnect client const client = new PKPWalletConnect(); // Handle session proposals client.on('session_proposal', async (proposal) => { const approved = await client.approveSession(proposal); }); // Handle session requests client.on('session_request', async (request) => { const response = await client.respondToRequest(request); }); ``` -------------------------------- ### Initialize and Use PKPEthersWallet Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-ethers/README.md Initialize the PKPEthersWallet with controller authentication and PKP public key. Obtain the wallet address and sign a transaction. ```typescript import { PKPEthersWallet } from '@lit-protocol/pkp-ethers'; // Initialize wallet const wallet = new PKPEthersWallet({ controllerAuthSig: authSig, pkpPubKey: publicKey, }); // Get wallet address const address = await wallet.getAddress(); // Sign transaction const signedTx = await wallet.signTransaction({ to: recipient, value: ethers.utils.parseEther('0.1'), }); ``` -------------------------------- ### Build Project Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Builds the entire project for testing and publishing. This command performs a full build including all operations. ```bash yarn build ``` -------------------------------- ### PKPBase Initialization Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-base/README.md Initializes the PKPBase class with controller authentication and public key. ```APIDOC ## PKPBase Initialization ### Description Initializes the PKPBase class, establishing a connection to the LIT node. ### Method `new PKPBase(options: { controllerAuthSig: AuthSig, pkpPubKey: string })` ### Parameters #### Constructor Parameters - **controllerAuthSig** (AuthSig) - Required - The controller's authentication signature. - **pkpPubKey** (string) - Required - The public key of the PKP. ### Method `init()` ### Description Initializes and connects to the LIT node. ### Request Example ```typescript import { PKPBase } from '@lit-protocol/pkp-base'; const authSig = { ... }; // Your controller auth signature const publicKey = '0x...'; // Your PKP public key const pkpBase = new PKPBase({ controllerAuthSig: authSig, pkpPubKey: publicKey }); await pkpBase.init(); ``` ``` -------------------------------- ### Initialize and Connect LitNodeClientNodeJs Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/lit-node-client-nodejs/README.md Instantiate the LitNodeClientNodeJs for Node.js environments and establish a connection to the Lit network. Ensure you have the necessary authentication callback defined. ```javascript import * as LitJsSdkNodeJs from '@lit-protocol/lit-node-client-nodejs'; import { checkAndSignAuthMessage } from '@lit-protocol/auth-browser'; const client = new LitJsSdkNodeJs.LitNodeClientNodeJs({ litNetwork: 'serrano', defaultAuthCallback: checkAndSignAuthMessage, }); await client.connect(); const authSig = await checkAndSignAuthMessage({ chain: 'ethereum', }); ``` -------------------------------- ### Initialize LitContracts Instance Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/contracts-sdk/README.md Demonstrates various ways to initialize the LitContracts instance, including using a third-party wallet, a random private key, local storage, a custom private key, or a custom signer. ```javascript const litContracts = new LitContracts(); ``` ```javascript const litContracts = new LitContracts({ randomPrivatekey: true }); ``` ```javascript const litContracts = new LitContracts({ randomPrivatekey: true, options: { storeOrUseStorageKey: true, }, }); ``` ```javascript const litContracts = new LitContracts({ options: { storeOrUseStorageKey: true, }, }); ``` ```javascript const litContracts = new LitContracts({ privateKey: TEST_FUNDED_PRIVATE_KEY }); ``` ```javascript const privateKey = TEST_FUNDED_PRIVATE_KEY; const provider = new ethers.providers.Web3Provider(window.ethereum, 'any'); const signer = new ethers.Wallet(privateKey, provider); const litContracts = new LitContracts({ signer }); ``` ```javascript const pkpWallet = new PKPWallet({ pkpPubKey: PKP_PUBKEY, controllerAuthSig: CONTROLLER_AUTHSIG, provider: 'https://rpc-mumbai.maticvigil.com', }); await pkpWallet.init(); const litContracts = new LitContracts({ signer: pkpWallet }); ``` -------------------------------- ### Get SUI Balance with PKP SUI Wallet Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-sui/README.md Retrieve the SUI balance for the PKPSuiWallet address using a JsonRpcProvider. ```typescript const provider = new JsonRpcProvider(mainnetConnection); const address = await pkpSuiWallet.getAddress(); const balance = await provider.getBalance(address); ``` -------------------------------- ### Generate New Library with Nx Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Generates a new JavaScript library within the Nx workspace. This command requires Nx to be installed. ```bash nx generate @nx/js:library ``` -------------------------------- ### Using devEnv API in Tests Source: https://github.com/lit-protocol/js-sdk/blob/master/local-tests/README.md Demonstrates setting network availability and interacting with the Lit Node Client and creating test users. Use this to set up the testing environment and perform initial actions. ```typescript export const testExample = async (devEnv: TinnyEnvironment) => { // ========== Enviorment ========== // This test will be skipped if we are testing on the DatilDev network devEnv.setUnavailable(LIT_NETWORK.DatilDev); // Using litNodeClient const res = await devEnv.litNodeClient.executeJs({...}); // ========== Creating a new identify/user profile ========== const alice = await devEnv.createRandomPerson(); // Alice minting a capacity creditrs NFT const aliceCcNft = await alice.mintCapacityCreditsNFT(); // Alice creating a capacity delegation authSig const aliceCcAuthSig = await alice.createCapacityDelegationAuthSig(); }; ``` -------------------------------- ### Initialize and Connect Lit Node Client Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/lit-node-client/README.md Initialize the LitNodeClient for the 'datil' network and establish a connection. ```typescript import { LitNodeClient } from '@lit-protocol/lit-node-client'; // Initialize the client const client = new LitNodeClient({ litNetwork: 'datil', }); // Connect to the network await client.connect(); ``` -------------------------------- ### Build WASM Module with wasm-pack Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/wasm/rust/README.md Use `wasm-pack build` to compile Rust code into a WebAssembly module for web targets. Ensure Rust version 1.70.0 or higher and `wasm-pack` are installed. ```bash wasm-pack build ./rust --target web --release --out-name wasm-internal ``` -------------------------------- ### Configure Local Node Development Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Sets environment variables to enable local node development and configure a funded wallet for the Chronicle testnet. ```bash # Enable local node development export LIT_JS_SDK_LOCAL_NODE_DEV="true" # Set funded wallet for Chronicle testnet export LIT_JS_SDK_FUNDED_WALLET_PRIVATE_KEY="your-funded-private-key" ``` -------------------------------- ### LitNodeClient - Connect to the Lit Network Source: https://context7.com/lit-protocol/js-sdk/llms.txt Demonstrates how to instantiate and connect to the Lit network using `LitNodeClient` for isomorphic environments (browser + Node.js) and `LitNodeClientNodeJs` for Node.js-only environments. ```APIDOC ## `LitNodeClient` — Connect to the Lit Network The main entry point for all SDK operations. `LitNodeClient` (isomorphic) and `LitNodeClientNodeJs` (Node.js-only) connect to the Lit node network, manage authentication, and expose methods for encryption, signing, and JS execution. Must be connected before any other operations. ```typescript import { LitNodeClient } from '@lit-protocol/lit-node-client'; const client = new LitNodeClient({ litNetwork: 'datil-test', // 'datil', 'datil-test', 'datil-dev', 'custom' debug: false, }); await client.connect(); console.log('Connected:', client.ready); // true // Node.js alternative with explicit auth callback import * as LitJsSdkNodeJs from '@lit-protocol/lit-node-client-nodejs'; import { checkAndSignAuthMessage } from '@lit-protocol/auth-browser'; const nodeClient = new LitJsSdkNodeJs.LitNodeClientNodeJs({ litNetwork: 'datil-test', defaultAuthCallback: checkAndSignAuthMessage, }); await nodeClient.connect(); ``` ``` -------------------------------- ### Build Nx Project with Dependencies Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Builds an Nx project, optionally including its dependencies. Use `--with-deps=false` to exclude dependencies. ```bash yarn nx run lit-node-client-nodejs:build --with-deps=false ``` -------------------------------- ### Publish Packages Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Publishes the packages. This command should be run after building, testing, and generating documentation. ```bash yarn publish:packages ``` -------------------------------- ### Initialize LitContracts with Private Key Source: https://context7.com/lit-protocol/js-sdk/llms.txt Initialize the LitContracts SDK using a private key for authentication. Ensure the private key is securely managed and the correct network is specified. ```typescript import { LitContracts } from '@lit-protocol/contracts-sdk'; import { ethers } from 'ethers'; // Initialize with a custom private key const litContracts = new LitContracts({ privateKey: process.env.FUNDED_PRIVATE_KEY, network: 'datil-test', }); await litContracts.connect(); ``` -------------------------------- ### Initialize LitContracts with Browser Wallet Source: https://context7.com/lit-protocol/js-sdk/llms.txt Initialize the LitContracts SDK using a browser-based wallet like MetaMask. This requires requesting account access from the user's wallet. ```typescript // Initialize with browser wallet (MetaMask) const provider = new ethers.providers.Web3Provider(window.ethereum, 'any'); await provider.send('eth_requestAccounts', []); const browserContracts = new LitContracts({ signer: provider.getSigner() }); await browserContracts.connect(); ``` -------------------------------- ### Generate and Push Documentation Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Generates documentation and pushes it. This command is part of the publishing workflow. ```bash yarn gen:docs --push ``` -------------------------------- ### Mint PKP NFT with Auth Methods Source: https://context7.com/lit-protocol/js-sdk/llms.txt Mint a PKP NFT and associate it with specific authentication methods and scopes in a single call. This is useful for setting up initial access controls. ```typescript // Mint with auth methods in one call (mintWithAuth) const mintWithAuth = await litContracts.mintWithAuth({ authMethod: { authMethodType: AUTH_METHOD_TYPE.EthWallet, accessToken: authSig.sig, }, scopes: [AUTH_METHOD_SCOPE.SignAnything], }); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Executes unit tests for all packages within the project. ```bash yarn test:unit ``` -------------------------------- ### Configure LIT Actions Code Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/wrapped-keys-lit-actions/README.md Provide the litActionRepository or individual lit actions to the wrapped keys package. This configuration should be done once before using the `api` methods. You can either import and set all lit actions, or set individual ones. ```javascript // import all lit actions code import { litActionRepository } from '@lit-protocol/wrapped-keys-lit-actions'; // or import individual lit actions import { generateEncryptedEthereumPrivateKey } from '@lit-protocol/wrapped-keys-lit-actions'; import { config, api } from '@lit-protocol/wrapped-keys'; // set the litActionRepository to set all lit actions config.setLitActionsCode({ litActionRepository }); // or set individual lit actions config.setLitActionsCode({ generateEncryptedKey: { evm: generateEncryptedEthereumPrivateKey.code, }, }); // Now this call will use the lit action code from the litActionRepository instead of making nodes fetch it from IPFS api.generatePrivateKey(/* params */); ``` -------------------------------- ### Using the devEnv API in a test Source: https://github.com/lit-protocol/js-sdk/blob/master/local-tests/README.md Demonstrates how to use the `devEnv` object within a test function to interact with the Lit Node Client and manage test environments. ```APIDOC ## Using the devEnv API in the test This section shows how to utilize the `devEnv` object, which is automatically provided as the first parameter to your test functions. It allows you to interact with the Lit Node Client and manage test environments. ### Example Usage ```ts export const testExample = async (devEnv: TinnyEnvironment) => { // ========== Enviorment ========== // This test will be skipped if we are testing on the DatilDev network devEnv.setUnavailable(LIT_NETWORK.DatilDev); // Using litNodeClient const res = await devEnv.litNodeClient.executeJs({...}); // ========== Creating a new identify/user profile ========== const alice = await devEnv.createRandomPerson(); // Alice minting a capacity creditrs NFT const aliceCcNft = await alice.mintCapacityCreditsNFT(); // Alice creating a capacity delegation authSig const aliceCcAuthSig = await alice.createCapacityDelegationAuthSig(); }; ``` ### `devEnv` API Details - `devEnv.setUnavailable(network)`: Skips the test if the specified network is unavailable. - `devEnv.litNodeClient.executeJs(options)`: Executes JavaScript on the Lit Node Client. - `devEnv.createRandomPerson()`: Creates a new random person (test user) with associated wallet and keys. ``` -------------------------------- ### Link Local Package for Development Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Links a local package for development by running `npm link` in the package directory. This is part of the process to test local changes in a client application. ```bash cd ./packages/*/ npm link ``` -------------------------------- ### Build Development Packages Source: https://github.com/lit-protocol/js-sdk/blob/master/README.md Builds the project packages for development. This command is optimized for local development and excludes production-only operations. ```bash yarn build:dev ``` -------------------------------- ### Stake SUI Tokens with PKP SUI Wallet Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-sui/README.md Construct and execute a transaction to stake SUI tokens using the PKPSuiWallet. ```typescript import { SUI_SYSTEM_STATE_OBJECT_ID, TransactionBlock } from '@mysten/sui.js'; const tx = new TransactionBlock(); const stakeCoin = tx.splitCoins(tx.gas, [tx.pure(amount)]); tx.moveCall({ target: '0x3::sui_system::request_add_stake', arguments: [ tx.object(SUI_SYSTEM_STATE_OBJECT_ID), stakeCoin, tx.pure(validator), ], }); return await pkpSuiWallet.signAndExecuteTransactionBlock({ transactionBlock: tx, }); ``` -------------------------------- ### Run All Tests Locally Source: https://github.com/lit-protocol/js-sdk/blob/master/local-tests/README.md Execute all tests on the local chain. Ensure DEBUG and NETWORK environment variables are set. ```bash DEBUG=true NETWORK=custom yarn test:local ``` -------------------------------- ### runSign Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/pkp-base/README.md Signs a given message using the PKP's private key. ```APIDOC ## runSign ### Description Signs a message using the PKP's private key. This is a specific implementation for signing operations. ### Method `runSign(message: string)` ### Parameters #### Method Parameters - **message** (string) - Required - The message to be signed. ### Request Example ```typescript // Assuming pkpBase is an initialized instance of PKPBase const messageToSign = 'This is a message to sign'; const signature = await pkpBase.runSign(messageToSign); ``` ``` -------------------------------- ### Connect to Lit Network with LitNodeClient Source: https://context7.com/lit-protocol/js-sdk/llms.txt Instantiate and connect to the Lit node network using LitNodeClient. The client must be connected before performing other operations. For Node.js, an explicit auth callback can be provided. ```typescript import { LitNodeClient } from '@lit-protocol/lit-node-client'; const client = new LitNodeClient({ litNetwork: 'datil-test', // 'datil', 'datil-test', 'datil-dev', 'custom' debug: false, }); await client.connect(); console.log('Connected:', client.ready); // true ``` ```typescript // Node.js alternative with explicit auth callback import * as LitJsSdkNodeJs from '@lit-protocol/lit-node-client-nodejs'; import { checkAndSignAuthMessage } from '@lit-protocol/auth-browser'; const nodeClient = new LitJsSdkNodeJs.LitNodeClientNodeJs({ litNetwork: 'datil-test', defaultAuthCallback: checkAndSignAuthMessage, }); await nodeClient.connect(); ``` -------------------------------- ### Create SIWE Messages with Lit Capabilities Source: https://context7.com/lit-protocol/js-sdk/llms.txt Use these functions to create SIWE messages enriched with Lit resource capabilities for authentication. Ensure LitNodeClient is initialized and connected. ```typescript import { createSiweMessage, createSiweMessageWithRecaps, createSiweMessageWithCapacityDelegation, } from '@lit-protocol/auth-helpers'; import { LIT_ABILITY } from '@lit-protocol/constants'; import { LitPKPResource } from '@lit-protocol/auth-helpers'; // Basic SIWE message with resource capabilities const siweMsg = await createSiweMessageWithRecaps({ walletAddress: wallet.address, nonce: await client.getLatestBlockhash(), litNodeClient: client, uri: 'https://myapp.com/login', expiration: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), resources: [ { resource: new LitPKPResource('*'), ability: LIT_ABILITY.PKPSigning, }, ], }); // SIWE message with capacity delegation (for delegating rate-limit credits) const delegationMsg = await createSiweMessageWithCapacityDelegation({ walletAddress: dAppOwnerWallet.address, nonce: await client.getLatestBlockhash(), litNodeClient: client, dAppOwnerWallet: dAppOwnerWallet, capacityTokenId: '42', // rate limit NFT token ID delegateeAddresses: ['0xUserAddress'], uses: '100', }); ``` -------------------------------- ### Update Contracts SDK Configuration Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/contracts-sdk/README.md Run the update script for the Contracts SDK. This is necessary if the directory structures in the LitNodeContracts repository have changed. ```bash node ./packages/contracts-sdk/tools.mjs --update ``` -------------------------------- ### Configure Lit Actions Code with LIT-Provided Repository Source: https://github.com/lit-protocol/js-sdk/blob/master/packages/wrapped-keys/README.md Configure the SDK to use LIT-provided Lit Actions source code by importing the repository and setting it via config.setLitActionsCode. This approach bundles LIT action source code into your application. ```javascript import { litActionRepository } from '@lit-protocol/wrapped-keys-lit-actions'; import { config, api } from '@lit-protocol/wrapped-keys'; config.setLitActionsCode({ litActionRepository }); ``` -------------------------------- ### Import an Existing Private Key Source: https://context7.com/lit-protocol/js-sdk/llms.txt Import an existing private key into the Wrapped Keys service. The key is encrypted before storage, ensuring the plaintext private key is not retained. ```typescript import { api } from '@lit-protocol/wrapped-keys'; const { importPrivateKey } = api; const { pkpAddress, id } = await importPrivateKey({ pkpSessionSigs: sessionSigs, privateKey: '0xYourExistingPrivateKey', publicKey: '0x04yourCorrespondingPublicKey', keyType: 'K256', // 'K256' | 'ed25519' litNodeClient: client, memo: 'Imported legacy hot wallet', }); console.log('Imported key associated with PKP:', pkpAddress); console.log('Wrapped key ID:', id); ``` -------------------------------- ### PKP-Backed Ethereum Wallet for Signing Source: https://context7.com/lit-protocol/js-sdk/llms.txt Utilize PKPEthersWallet as an ethers.js Signer replacement. It signs requests using the Lit network's threshold ECDSA, never materializing the private key. ```typescript import { PKPEthersWallet } from '@lit-protocol/pkp-ethers'; import { LitNodeClient } from '@lit-protocol/lit-node-client'; import { ethers } from 'ethers'; const client = new LitNodeClient({ litNetwork: 'datil-test' }); await client.connect(); const pkpWallet = new PKPEthersWallet({ pkpPubKey: '0x04yourPKPPublicKey...', litNodeClient: client, controllerSessionSigs: sessionSigs, rpc: 'https://mainnet.infura.io/v3/YOUR_KEY', }); await pkpWallet.init(); // Get address (derived from PKP public key) const address = await pkpWallet.getAddress(); console.log('PKP Address:', address); // Sign a message const signature = await pkpWallet.signMessage('Hello from PKP!'); console.log('Signature:', signature); // Sign and send a transaction const provider = new ethers.providers.JsonRpcProvider('https://rpc-url'); const connectedWallet = pkpWallet.connect(provider); const tx = await connectedWallet.sendTransaction({ to: '0xRecipientAddress', value: ethers.utils.parseEther('0.01'), gasLimit: 21000, }); console.log('TX hash:', tx.hash); await tx.wait(); // Sign typed data (EIP-712) const typedSig = await pkpWallet._signTypedData( { name: 'MyDApp', version: '1', chainId: 1 }, { Message: [{ name: 'content', type: 'string' }] }, { content: 'Hello' } ); ```