Skip to main content

lit-python-sdk

A Python SDK for interacting with the Lit Protocol.

Getting Started

The Lit Python SDK provides a simple way to interact with the Lit Protocol from Python applications. The SDK automatically manages a Node.js server (using nodejs-bin) to communicate with the Lit Network.

Installation

Install the SDK in your Python environment:

pip install -e .

Authentication

Before using the SDK, you'll need to set up authentication using a private key.

from lit_python_sdk import connect

# Initialize the client
client = connect()
client.set_auth_token(os.getenv("LIT_POLYGLOT_SDK_TEST_PRIVATE_KEY"))

# Initialize and connect to the network
client.new(lit_network="datil-test", debug=True)
client.connect()

Features and Examples

Executing JavaScript Code on the Lit Network

You can execute JavaScript code across the Lit Network. First, you'll need to get session signatures, then execute the code:

from datetime import datetime, timedelta, timezone

# Get session signatures
expiration = (datetime.now(timezone.utc) + timedelta(minutes=10)).strftime("%Y-%m-%dT%H:%M:%SZ")
session_sigs_result = client.get_session_sigs(
    chain="ethereum",
    expiration=expiration,
    resource_ability_requests=[{
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-litaction",
        },
        "ability": "lit-action-execution",
    }]
)
session_sigs = session_sigs_result["sessionSigs"]

# Execute the code
js_code = """
(async () => {
    console.log("Testing executeJs endpoint");
    Lit.Actions.setResponse({response: "Test successful"});
})()
"""

result = client.execute_js(
    code=js_code,
    js_params={},
    session_sigs=session_sigs
)

# The result contains:
# - response: any data set using Lit.Actions.setResponse
# - logs: console output from the execution

Minting PKPs and Signing Messages

The SDK allows you to mint a PKP (Programmable Key Pair) and sign messages:

# Initialize the contracts client
client.new_lit_contracts_client(
    private_key=os.getenv("LIT_POLYGLOT_SDK_TEST_PRIVATE_KEY"),
    network="datil-test",
    debug=True
)

# Create a SIWE message for authentication
expiration = (datetime.now(timezone.utc) + timedelta(minutes=10)).strftime("%Y-%m-%dT%H:%M:%SZ")
siwe_result = client.create_siwe_message(
    uri="http://localhost:3092",
    expiration=expiration,
    resources=[{
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-litaction",
        },
        "ability": "lit-action-execution",
    }],
    wallet_address=wallet_address  # Your wallet address, derived from the private key you use for your auth token.
)

# Generate auth signature
auth_sig_result = client.generate_auth_sig(siwe_result["siweMessage"])

# Mint a new PKP
mint_result = client.mint_with_auth(
    auth_method={
        "authMethodType": 1,  # EthWallet
        "accessToken": auth_sig_result["authSig"],
    },
    scopes=[1]
)
pkp = mint_result["pkp"]

# Get session signatures for signing
session_sigs_result = client.get_session_sigs(
    chain="ethereum",
    expiration=expiration,
    resource_ability_requests=[{
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-pkp",
        },
        "ability": "pkp-signing",
    },
    {
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-litaction",
        },
        "ability": "lit-action-execution",
    }]
)
session_sigs = session_sigs_result["sessionSigs"]

# Sign a message
to_sign_hex = "0xadb20420bde8cda6771249188817098fca8ccf8eef2120a31e3f64f5812026bf"
hex_str = to_sign_hex[2:] if to_sign_hex.startswith("0x") else to_sign_hex
to_sign = [int(hex_str[i:i+2], 16) for i in range(0, len(hex_str), 2)]

signature = client.pkp_sign(
    pub_key=pkp["publicKey"],
    to_sign=to_sign,
    session_sigs=session_sigs
)

String Encryption and Decryption

The SDK provides methods to encrypt and decrypt strings using the Lit Protocol. This allows you to create access-controlled encrypted content:

from datetime import datetime, timedelta, timezone

# Get session signatures for decryption
expiration = (datetime.now(timezone.utc) + timedelta(minutes=10)).strftime("%Y-%m-%dT%H:%M:%SZ")
session_sigs_result = client.get_session_sigs(
    chain="ethereum",
    expiration=expiration,
    resource_ability_requests=[{
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-litaction",
        },
        "ability": "lit-action-execution",
    }, {
        "resource": {
            "resource": "*",
            "resourcePrefix": "lit-pkp",
        },
        "ability": "pkp-signing",
    }]
)
session_sigs = session_sigs_result["sessionSigs"]

# Define access control conditions
# This example allows only a specific wallet address to decrypt the content
access_control_conditions = [{
    "contractAddress": "",
    "standardContractType": "",
    "chain": "ethereum",
    "method": "",
    "parameters": [":userAddress"],
    "returnValueTest": {
        "comparator": "=",
        "value": "0x..." # Replace with the authorized wallet address
    }
}]

# Encrypt a string
encrypt_result = client.encrypt_string(
    data_to_encrypt="Hello, World!",
    access_control_conditions=access_control_conditions
)

# The encrypt_result contains:
# - ciphertext: the encrypted string
# - dataToEncryptHash: hash of the original data

# Decrypt the string
decrypt_result = client.decrypt_string(
    ciphertext=encrypt_result["ciphertext"],
    data_to_encrypt_hash=encrypt_result["dataToEncryptHash"],
    chain="ethereum",
    access_control_conditions=access_control_conditions,
    session_sigs=session_sigs
)

# decrypt_result["decryptedString"] contains the original message
print(decrypt_result["decryptedString"])  # Output: "Hello, World!"

You can also use other types of access control conditions:

  • EVM contract conditions (evm_contract_conditions)
  • Solana RPC conditions (sol_rpc_conditions)
  • Unified access control conditions (unified_access_control_conditions)

Development Setup

For development and testing:

  1. Install test dependencies:
pip install pytest
  1. Bundle the Node.js server dependencies:
cd js-sdk-server && npm install && npm run build
  1. Run tests:
pytest

Publishing

  1. Update the version in pyproject.toml
  2. Run ./publish.sh

Metadata

Release files for lit-python-sdk 1.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lit-python-sdk 1.2.3
File Size Uploaded Provenance Actions
lit_python_sdk-1.2.3.tar.gz 1.5 MB Without provenance Details for lit_python_sdk-1.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lit-python-sdk 1.2.3
File Interpreter ABI Platform Actions
lit_python_sdk-1.2.3-py3-none-any.whl Python 3 none any Details for lit_python_sdk-1.2.3-py3-none-any.whl

Total release size: 3.1 MB

Release files / lit_python_sdk-1.2.3.tar.gz

Download URL lit_python_sdk-1.2.3.tar.gz
Size 1.5 MB
Tags Source
SHA-256 checksum
How to use checksums
4f7fcf67cb6c80a29337defa51d852582e0830ad3642cee8ec1b589557cfc316
BLAKE2b-256 checksum
How to use checksums
62376899719042a4b86de25b9156615498c206eb5dc08c6fa9afa4e7245f3497
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.10.14

Release files / lit_python_sdk-1.2.3-py3-none-any.whl

Download URL lit_python_sdk-1.2.3-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
5764e8082ac067ee396bcf11be4b6d76af5fa77bf6ab6d3b8b47b40b057ee7f0
BLAKE2b-256 checksum
How to use checksums
b5e6d59a7550cf6f19fb0f4075c72311e149f0e2816e1820dadcc947d1a6c760
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.10.14

Security for lit-python-sdk 1.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page