lighter.session

Documentation for eth_defi.lighter.session Python module.

HTTP session management for Lighter API.

Every Lighter API call goes through one of the classes in this module:

Limits published in Lighter’s rate limit documentation, read on 2026-11-05:

  • L2CreateSubAccount and L2CreatePublicPool: 2 requests per minute.

  • L2Withdraw: 2 requests per minute and 3 per 2 hours, per L1 address.

  • Standard accounts: 60 requests per rolling minute, per IP and L1 address.

  • Exceeding a limit returns HTTP 429 or HTTP 405.

  • The firewall cooldown is a static 60 seconds.

Lighter documents no Retry-After header, and the 429 for the sub-account limit carried none on 2026-11-04. Responses pass through CloudFront, though, so another layer can send one. Both retrying classes honour it when it is present.

Executors on one host share the IP budget, so a limit can be reached without the current process being busy.

Module Attributes

DEFAULT_RETRIES

Default number of retries for API requests.

DEFAULT_BACKOFF_FACTOR

Default backoff factor for retries (seconds)

LIGHTER_RATE_LIMIT_STATUSES

Statuses Lighter documents for an exceeded rate limit.

LIGHTER_RETRYABLE_READ_STATUSES

Statuses retried for a read.

LIGHTER_SEND_TX_PATH

The only mutation path LighterSDKSession retries.

LIGHTER_SUBMISSION_DEADLINE

Seconds after which a pre-signed submission is not attempted again.

LIGHTER_SDK_DEFAULT_POLICY

Default policy for reads and live transactions.

LIGHTER_SDK_SLOW_TRANSACTION_POLICY

Policy for transactions with a low per-minute limit and no price or sizing exposure, such as sub-account creation.

Functions

create_lighter_session([api_url, retries, ...])

Create a LighterSession configured for Lighter API.

create_lighter_submission_session([api_url, ...])

Create a session for one pre-signed, persisted transaction.

parse_lighter_retry_after(value)

Read a Retry-After header without trusting its format.

Classes

LighterSDKRetryPolicy

Backoff settings for LighterSDKSession.

LighterSDKSession

Exponential backoff for all HTTP traffic of the official Lighter SDK.

LighterSession

A requests.Session subclass that carries the Lighter API URL.

LighterSubmissionSession

Send one pre-signed transaction, resending it only after a rate limit.

LIGHTER_RATE_LIMIT_SQLITE_DATABASE: pathlib.Path = PosixPath('/home/runner/.tradingstrategy/lighter/rate-limit.sqlite')

Default SQLite database path for rate limiting state.

Using SQLite ensures thread-safe rate limiting across multiple threads when using joblib.Parallel or similar parallel processing.

DEFAULT_RETRIES: int = 8

Default number of retries for API requests.

With DEFAULT_BACKOFF_FACTOR the waits total about 127 seconds, which outlasts Lighter’s 60-second firewall cooldown.

DEFAULT_BACKOFF_FACTOR: float = 0.5

Default backoff factor for retries (seconds)

LIGHTER_RATE_LIMIT_STATUSES: frozenset[int] = frozenset({405, 429})

Statuses Lighter documents for an exceeded rate limit.

LIGHTER_RETRYABLE_READ_STATUSES: frozenset[int] = frozenset({405, 429, 500, 502, 503, 504})

Statuses retried for a read.

LIGHTER_SEND_TX_PATH: str = '/api/v1/sendTx'

The only mutation path LighterSDKSession retries.

LIGHTER_SUBMISSION_DEADLINE: float = 15.0

Seconds after which a pre-signed submission is not attempted again.

Short because signed pool transactions have no USDC slippage limit and their sizing comes from an observation at most 30 seconds old.

parse_lighter_retry_after(value)

Read a Retry-After header without trusting its format.

Lighter does not document this header, so an unusable value must not turn a rate limit into a crash. urllib3’s parser covers both forms the header allows, seconds and an HTTP date. See RFC 9110.

Parameters

value (Optional[str]) – Header value, or None if the response had none.

Returns

Seconds to wait, or 0 if the header is missing or unusable.

Return type

float

class LighterSDKRetryPolicy

Bases: object

Backoff settings for LighterSDKSession.

Deadlines are measured from the first attempt. No new attempt starts if its wait would pass the deadline, so a call overruns by at most one request.

initial_delay: float

Wait before the first retry, in seconds. Doubles for each retry.

max_delay: float

Longest computed wait between attempts, in seconds, including jitter. Longer than the firewall cooldown. A larger Retry-After takes precedence.

read_deadline: float

Deadline for a read, in seconds.

transaction_deadline: float

Deadline for a signed transaction, in seconds.

Short by default, because a transaction may be sized from market data and a live cycle waits for it.

request_timeout: float

Timeout of one attempt, in seconds. The SDK’s own default is 300.

__init__(initial_delay=1.0, max_delay=64.0, read_deadline=130.0, transaction_deadline=30.0, request_timeout=30.0)
Parameters
  • initial_delay (float) –

  • max_delay (float) –

  • read_deadline (float) –

  • transaction_deadline (float) –

  • request_timeout (float) –

Return type

None

LIGHTER_SDK_DEFAULT_POLICY = LighterSDKRetryPolicy(initial_delay=1.0, max_delay=64.0, read_deadline=130.0, transaction_deadline=30.0, request_timeout=30.0)

Default policy for reads and live transactions.

LIGHTER_SDK_SLOW_TRANSACTION_POLICY = LighterSDKRetryPolicy(initial_delay=1.0, max_delay=64.0, read_deadline=130.0, transaction_deadline=300.0, request_timeout=30.0)

Policy for transactions with a low per-minute limit and no price or sizing exposure, such as sub-account creation. A signed transaction stays valid for longer than this deadline.

class LighterSession

Bases: requests.sessions.Session

A requests.Session subclass that carries the Lighter API URL.

All Lighter API functions accept a LighterSession and read api_url from it, removing the need for a separate api_url argument on every call.

Use create_lighter_session() to create instances.

__init__(api_url=None, deployment=LighterAPIConfig(slug='ethereum', name='Lighter Ethereum', chain_id=9998, deployment_chain_id=1, api_url='https://mainnet.zklighter.elliot.ai', app_url='https://app.lighter.xyz', address_prefix='lighter-pool', denomination='USDC', lockup=datetime.timedelta(seconds=300), llp_account_index_override=None))
Parameters
api_url: str

Lighter API base URL (e.g. https://mainnet.zklighter.elliot.ai).

deployment: eth_defi.lighter.constants.LighterAPIConfig

Deployment whose API and vault namespace this session accesses.

close()

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

Return type

requests.adapters.BaseAdapter

get_redirect_target(resp)

Receives a Response. Returns a redirect URI or None

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

merge_environment_settings(url, proxies, stream, verify, cert)

Check the environment and merge it with some settings.

Return type

dict

mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by prefix length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

post(url, data=None, json=None, **kwargs)

Sends a POST request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session.

Parameters

request – Request instance to prepare with this session’s settings.

Return type

requests.PreparedRequest

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).

This method also replaces the Proxy-Authorization header where necessary.

Return type

dict

request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)

Constructs a Request, prepares it and sends it. Returns Response object.

Parameters
  • method – method for the new Request object.

  • url – URL for the new Request object.

  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • headers – (optional) Dictionary of HTTP Headers to send with the Request.

  • cookies – (optional) Dict or CookieJar object to send with the Request.

  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.

  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.

  • timeout (float or tuple) – (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • allow_redirects (bool) – (optional) Set to True by default.

  • proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.

  • hooks – (optional) Dictionary mapping hook name to one event or list of events, event must be callable.

  • stream – (optional) whether to immediately download the response content. Defaults to False.

  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True. When set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to False may be useful during local development or testing.

  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Return type

requests.Response

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

Receives a Response. Returns a generator of Responses or Requests.

send(request, **kwargs)

Send a given PreparedRequest.

Return type

requests.Response

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

headers

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

auth

Default Authentication tuple or object to attach to Request.

proxies

Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request.

hooks

Event-handling hooks.

params

Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.

stream

Stream response content default.

verify

SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.

cert

SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

max_redirects

Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.

trust_env

Trust environment settings for proxy configuration, default authentication and similar.

cookies

A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object.

class LighterSDKSession

Bases: object

Exponential backoff for all HTTP traffic of the official Lighter SDK.

The SDK sends everything through ApiClient.rest_client.request() using aiohttp, so LighterSession cannot see it. This class replaces rest_client by composition, which keeps the optional SDK out of eth-defi’s imports. It does not change the SDK’s error handling: the final response is returned unchanged and the SDK raises its usual ApiException.

Retrying here rather than around a signer method matters. The SDK does not roll its nonce back when a 429 escapes, so a retry above this layer would sign again with a later nonce. Here the same signed body is resent, so the nonce and the transaction hash do not change.

Which requests are retried:

The SDK holds its per-key nonce lock during a wait. That keeps transactions in nonce order, and clients are built per operation, so nothing else is blocked.

Authenticated Lighter requests can carry a token in the query string, and bodies hold signed transactions, so logs only name the method and URL path.

The native Go signer has its own HTTP client, which this class cannot wrap. It is used when an SDK transaction method receives api_key_index without a nonce, and by SignerClient.check_client(). Do not call them that way: omit api_key_index and the Python nonce manager fetches the nonce through this class.

See Lighter’s rate limits and the SDK’s REST client.

rest_client: Any

The SDK’s RESTClientObject.

policy: eth_defi.lighter.session.LighterSDKRetryPolicy

Delays and deadlines.

clock: collections.abc.Callable[[], float]

Monotonic clock, injectable for deterministic tests.

sleep: collections.abc.Callable[[float], collections.abc.Awaitable[None]]

Async sleep, injectable for deterministic tests.

async close()

Close the wrapped SDK client.

Return type

None

async request(method, url, headers=None, body=None, post_params=None, _request_timeout=None)

Send one SDK request, matching RESTClientObject.request().

The body is read here because the SDK reads it only after this returns, which would leave a truncated read outside the retries. RESTResponse caches it, so the SDK’s later read returns the same bytes.

Parameters
  • method (str) – HTTP method.

  • url (str) – Full URL. May contain a token, so it is never logged whole.

  • headers (Optional[dict[str, str]]) – Request headers.

  • body (Any) – JSON body.

  • post_params (Any) – Form parameters.

  • _request_timeout (Optional[Union[float, tuple[float, float]]]) – Timeout of one attempt. Defaults to the policy’s.

Returns

SDK RESTResponse with its body read.

Return type

Any

__init__(rest_client, policy=LighterSDKRetryPolicy(initial_delay=1.0, max_delay=64.0, read_deadline=130.0, transaction_deadline=30.0, request_timeout=30.0), clock=<built-in function monotonic>, sleep=<function sleep>)
Parameters
Return type

None

class LighterSubmissionSession

Bases: eth_defi.lighter.session.LighterSession

Send one pre-signed transaction, resending it only after a rate limit.

A pool executor persists a transaction before posting it and reconciles an uncertain outcome by hash, so nothing here may replay one. Only LIGHTER_RATE_LIMIT_STATUSES are retried. Connection and read errors, and every other status, reach the caller after one attempt.

No attempt starts after a wall-clock deadline, because a slow refusal must not lead to a replay of stale sizing. Each attempt’s timeout is the time remaining. requests applies it to the connection and the read separately, so an attempt already under way can finish slightly late, which cannot cause a replay. The loop lives here rather than in a urllib3 Retry, which only counts attempts and which retries a 413 or 503 carrying Retry-After whatever its status list says.

This session has no client-side limiter: a submission is a single request.

See the sendTx API reference.

Create the session without retry adapters.

Parameters
  • api_url – Optional Lighter API base URL override.

  • deployment – Deployment whose API this session accesses.

  • deadline – Seconds after which post() starts no further attempt.

__init__(api_url=None, deployment=LighterAPIConfig(slug='ethereum', name='Lighter Ethereum', chain_id=9998, deployment_chain_id=1, api_url='https://mainnet.zklighter.elliot.ai', app_url='https://app.lighter.xyz', address_prefix='lighter-pool', denomination='USDC', lockup=datetime.timedelta(seconds=300), llp_account_index_override=None), deadline=15.0)

Create the session without retry adapters.

Parameters
deadline: float

Seconds after which post() starts no further attempt.

close()

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

Return type

requests.adapters.BaseAdapter

get_redirect_target(resp)

Receives a Response. Returns a redirect URI or None

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

merge_environment_settings(url, proxies, stream, verify, cert)

Check the environment and merge it with some settings.

Return type

dict

mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by prefix length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

post(url, data=None, **kwargs)

Post a signed transaction within the deadline.

Parameters
  • url (str) – sendTx URL.

  • data (Any) – Form fields holding the signed transaction. Never logged.

  • kwargs (Any) – Passed to requests.Session.post(). The timeout comes from the remaining deadline.

Returns

The final response. A rate limit that outlasts the deadline is returned for the caller to handle.

Return type

requests.models.Response

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session.

Parameters

request – Request instance to prepare with this session’s settings.

Return type

requests.PreparedRequest

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type

requests.Response

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).

This method also replaces the Proxy-Authorization header where necessary.

Return type

dict

request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)

Constructs a Request, prepares it and sends it. Returns Response object.

Parameters
  • method – method for the new Request object.

  • url – URL for the new Request object.

  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • headers – (optional) Dictionary of HTTP Headers to send with the Request.

  • cookies – (optional) Dict or CookieJar object to send with the Request.

  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.

  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.

  • timeout (float or tuple) – (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • allow_redirects (bool) – (optional) Set to True by default.

  • proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.

  • hooks – (optional) Dictionary mapping hook name to one event or list of events, event must be callable.

  • stream – (optional) whether to immediately download the response content. Defaults to False.

  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True. When set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to False may be useful during local development or testing.

  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Return type

requests.Response

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

Receives a Response. Returns a generator of Responses or Requests.

send(request, **kwargs)

Send a given PreparedRequest.

Return type

requests.Response

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

api_url: str

Lighter API base URL (e.g. https://mainnet.zklighter.elliot.ai).

deployment: eth_defi.lighter.constants.LighterAPIConfig

Deployment whose API and vault namespace this session accesses.

headers

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

auth

Default Authentication tuple or object to attach to Request.

proxies

Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request.

hooks

Event-handling hooks.

params

Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.

stream

Stream response content default.

verify

SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.

cert

SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

max_redirects

Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.

trust_env

Trust environment settings for proxy configuration, default authentication and similar.

cookies

A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object.

create_lighter_session(api_url=None, retries=8, backoff_factor=0.5, max_retry_duration=None, requests_per_second=2.0, pool_maxsize=32, rate_limit_db_path=PosixPath('/home/runner/.tradingstrategy/lighter/rate-limit.sqlite'), deployment=LighterAPIConfig(slug='ethereum', name='Lighter Ethereum', chain_id=9998, deployment_chain_id=1, api_url='https://mainnet.zklighter.elliot.ai', app_url='https://app.lighter.xyz', address_prefix='lighter-pool', denomination='USDC', lockup=datetime.timedelta(seconds=300), llp_account_index_override=None))

Create a LighterSession configured for Lighter API.

The session is configured with:

  • The API URL stored in LighterSession.api_url

  • Rate limiting to respect Lighter API throttling (thread-safe via SQLite)

  • Retry logic for handling transient errors using exponential backoff

Only idempotent reads are retried. LoggingRetry leaves POST out by default. SDK traffic is not covered: see LighterSDKSession.

The rate limiter uses SQLite backend for thread-safe coordination across multiple threads (e.g., when using joblib.Parallel with threading backend).

Example:

from eth_defi.lighter.session import create_lighter_session

session = create_lighter_session()
Parameters
  • api_url (Optional[str]) – Optional Lighter API base URL override. Defaults to the configured deployment URL.

  • retries (Optional[int]) – Maximum number of retry attempts for failed requests. None bounds retries by max_retry_duration alone.

  • backoff_factor (float) – Backoff factor for exponential retry delays.

  • max_retry_duration (Optional[float]) – Optional seconds after the first failure during which a request is retried. Live executors set this to ride out a Lighter API outage instead of failing a fail-closed valuation after a few seconds. See max_retry_duration.

  • requests_per_second (float) – Maximum requests per second to avoid rate limiting.

  • pool_maxsize (int) – Maximum number of connections to keep in the connection pool. Should be at least as large as max_workers when using parallel requests.

  • rate_limit_db_path (pathlib.Path) – Path to SQLite database for storing rate limit state. Using SQLite ensures thread-safe rate limiting across multiple threads.

  • deployment (eth_defi.lighter.constants.LighterAPIConfig) – Deployment whose pool namespace this session accesses. Defaults to the backwards-compatible Ethereum deployment.

Returns

Configured LighterSession with rate limiting and retry logic.

Return type

eth_defi.lighter.session.LighterSession

create_lighter_submission_session(api_url=None, deployment=LighterAPIConfig(slug='ethereum', name='Lighter Ethereum', chain_id=9998, deployment_chain_id=1, api_url='https://mainnet.zklighter.elliot.ai', app_url='https://app.lighter.xyz', address_prefix='lighter-pool', denomination='USDC', lockup=datetime.timedelta(seconds=300), llp_account_index_override=None), deadline=15.0)

Create a session for one pre-signed, persisted transaction.

Parameters
Returns

Session whose post() retries rate limits only, within the deadline.

Return type

eth_defi.lighter.session.LighterSubmissionSession